例如,我们有这个 index.html
代码:
<!DOCTYPE html>
<html ng-app="sample">
<head>
...
</head>
<body>
<div ng-controller="myController">
...
<script src="js/modules/app.js"></script>
</div>
</body>
</html>
在 app.js
中,我们有一个模块和一个 Controller :
var app = angular.module('sample', []);
// controller here
所以我的问题是,我看到 Controller 定义为两种类型,一种是 Controller ,另一种是普通函数:
app.controller('myController', function(args){
...
});
或
var myController = function(args){
...
};
应该使用哪一个,为什么?我在基于 Angular 的代码中看到的大多是第一个,但即使在教程中我也遇到过第二个。我个人不使用第二个,因为我读到它“污染了全局命名空间”。
我的另一个问题是我已经看到了 Controller 的这种用法:
app.controller('myController', ['$scope', '$http', function($scope, $http) {
...
}]);
为什么我们需要数组?我们不能只靠争论凑合吗?
最佳答案
根据 Angular,基于数组注解的依赖注入(inject)或定义是首选方式:
someModule.controller('MyController', ['$scope', 'greeter', function($scope, greeter) {
// ...
}]);
This is the preferred way to annotate application components. This is how the examples in the documentation are written.
另一方面,获取依赖项的最简单方法是假设函数参数名称是依赖项的名称(对于类似的生产应用程序而言,这不是首选)。
someModule.controller('MyController', function($scope, greeter) {
// ...
});
Angular 可以通过检查函数声明和提取参数名称来推断要注入(inject)的服务的名称。在上面的例子中,$scope
和greeter
是需要注入(inject)到函数中的两个服务。
但是,由于它们重命名参数的方式,此方法不适用于 JavaScript 压缩器/混淆器。
压缩后的代码如下:
someModule.controller('MyController', function(a, b) {
// ...
});
所以现在,Angular 不知道什么是依赖项 a
和 b
而如果你使用基于数组注释,输出将是:
someModule.controller('MyController',['$scope','greeter', function(a,b) {
// ...
}]);
因此,现在 Angular 可以将 a
映射到 $scope
并将 b
映射到 greeter
并且能够解决依赖关系。
关于javascript - 哪种是定义 AngularJS Controller 的首选方式?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34431126/