[英]Angular controller global vs. closure
This issue drives me mad. 这个问题让我很生气。
Test code: 测试代码:
describe('controller', function(){
module('controllers');
var createCtrl;
beforeEach(inject(function($injector){
$rootScope = $injector.get('$rootScope');
var $controller = $injector.get('$controller');
createCtrl = function(){
return $controller('controller', {
$scope: $rootScope
});
}));
it('should create a controller', function(){
var ctrl = createCtrl();
});
});
It works if i controller function is defined in global scope eg 如果i控制器功能在全局范围内定义,则可行
angular.module('controllers', [])
.controller('controller', ['$scope', controller]);
function controller($scope){}
But if i move the function itself to the array, or wrap module code in a closure (in any combination of these): 但是,如果我将函数本身移动到数组,或将模块代码包装在一个闭包中(在这些中的任意组合中):
(function(angular){
angular.module('controllers', [])
.controller('controller', ['$scope', function($scope){}]);
})(angular);
test starts to throw this error Error: [ng:areq] Argument 'controller' is not a function, got undefined
测试开始抛出此错误Error: [ng:areq] Argument 'controller' is not a function, got undefined
Any ideas? 有任何想法吗? I really need this controller not to pollute global scope. 我真的需要这个控制器不污染全球范围。
First you need to fix a syntax issue. 首先,您需要修复语法问题。 The function assigned to createCtrl
is missing a closing curly bracket. 分配给createCtrl
的函数缺少一个结束花括号。
To fix your actual issue you need to include angular-mocks and replace 要解决您的实际问题,您需要包括角度模拟和替换
module('controllers');
with 同
beforeEach(angular.mock.module('controllers'));
Moving the function itself into the array seems totally valid, I personally use this syntax all the time. 将函数本身移动到数组中似乎完全有效,我个人一直使用这种语法。 Wrapping them in a closure seems unnecessary though, since you're not exposing any variables. 将它们包装在闭包中似乎是不必要的,因为你没有暴露任何变量。
I also recommend not using the $rootScope as the current $scope. 我还建议不要使用$ rootScope作为当前的$ scope。 Instead use $rootScope.$new()
. 而是使用$rootScope.$new()
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.