我对 AngularJS 有一些不完全理解的地方。如果我这样声明 Controller :
angular.module('ngApp', []).controller('AboutCtrl', ['$scope', function ($scope) {
$scope.awesomeThings = ['HTML5 Boilerplate', 'AngularJS', 'Karma'];
}]);
angular.module('ngApp', []).controller('ContactCtrl', ['$scope', function ($scope) {
$scope.awesomeThings = ['HTML5 Boilerplate', 'AngularJS', 'Karma'];
}]);
angular.module('ngApp', []).controller('MainCtrl', ['$scope', function ($scope) {
$scope.awesomeThings = ['HTML5 Boilerplate', 'AngularJS', 'Karma'];
}]);
...每当我尝试测试它们时,只有其中一个通过测试用例:
describe('MainCtrl', function () {
var scope;
beforeEach(module('ngApp'));
beforeEach(inject(function ($rootScope, $controller) {
scope = $rootScope.$new();
$controller('MainCtrl', { $scope: scope });
}));
it('should attach a list of `awesomeThings` to the scope', function () {
expect(scope.awesomeThings.length).toBe(3);
});
});
(我还有三个文件重复相同的测试用例,唯一改变的是 Controller 名称: AboutCtrl
和 ContactCtrl
在适当的位置)。
另一方面,如果我说:var app = angular.module('ngApp', []);
然后将 Controller “附加”到它上面,一切正常。如果我将它们连接到同一条链上,效果也是一样的 angular.module('ngApp', []).controller(/* ... */).controller(/* ... */);
我希望将它们分开的原因是因为我希望将它们放在(三个...N)不同的文件中。
有人有任何线索吗?
最佳答案
您每次都重新声明您的 ngApp
模块,而不是获取已声明的模块。
来自约翰·帕帕的 Angular Style Guide :
•Only set once and get for all other instances.
Why?: A module should only be created once, then retrieved from that point and after.
/* recommended */ // to set a module angular.module('app', []); // to get a module angular.module('app');
关于javascript - 在单个模块中声明时 Controller 未定义,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34257630/