gpt4 book ai didi

angularjs - Angular 中用于 Controller 、服务和其他的不同语法

转载 作者:行者123 更新时间:2023-12-04 21:12:53 24 4
gpt4 key购买 nike

和有什么区别

app.controller("MyCtrl", function($scope, $http){
//...
});


app.controller("MyCtrl", ["$scope", "$http", function($scope, $http){
//...
}]);

即使两者都给出相同的结果并且没有错误。事实上,第一个使代码更简洁,编写更少。在服务、指令方面也是如此。谁能给我一个简短的介绍。

最佳答案

没有功能上的区别。使用 .controller('ctrl',['$scope', function($scope){...}是允许正确读取缩小版本。

关于缩小的说明 - AngularJS

Since Angular infers the controller's dependencies from the names of arguments to the controller's constructor function, if you were to minify the JavaScript code for MyCtrl controller, all of its function arguments would be minified as well, and the dependency injector would not be able to identify services correctly.



我们可以通过使用依赖项的名称注释函数来克服这个问题,作为字符串提供,它不会被缩小。有两种方法可以提供这些注入(inject)注解:
  • 在包含字符串数组的 Controller 函数上创建一个 $inject 属性。数组中的每个字符串都是为相应参数注入(inject)的服务的名称:
    function MyCtrl($scope, $http) {...}
    MyCtrl.$inject = ['$scope', '$http'];
    app.controller('MyCtrl', MyCtrl);
  • 使用内联注释,您不仅提供函数,还提供数组。此数组包含服务名称列表,后跟函数本身:
    function MyCtrl($scope, $http) {...}
    app.controller('MyCtrl', ['$scope', '$http', MyCtrl]);

  • 这两种方法都适用于可以由 Angular 注入(inject)的任何函数,因此由项目的样式指南决定使用哪一种。

    使用第二种方法时,通常在注册 Controller 时将构造函数内联作为匿名函数:
    app.controller('MyCtrl', ['$scope', '$http', function($scope, $http) {...}]);

    关于angularjs - Angular 中用于 Controller 、服务和其他的不同语法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30777302/

    24 4 0
    Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
    广告合作:1813099741@qq.com 6ren.com