我最近开始使用 JSHint,它要求我使用“use strict”的函数形式。从那时起,AngularJS 就会抛出错误:
“错误:参数‘webAddressController’不是函数,未定义”
当我删除“use strict”的函数形式时,控制器加载正常。
控制器:
(function () {
"use strict";
function webAddressController($scope, $rootScope, web_address_service) {
// Do things
}
}());
有人对这里发生的事情有任何了解吗?
首先,我想说 pkozlowski 确实了解 Angular 的东西,但这实际上并不是 Angular 的问题,而是闭包的问题。
Angular 在两个地方寻找控制器:
- 在通过 Module.controller() 注册的自己的控制器注册表中
- In a global变量(或全局函数声明)
问题是“use strict”闭包中的所有内容都不是全局的。它被包含在包含它的匿名函数中并被私有化。
(function() {
// nothing in here is global or even public.
// "use strict" or not.
"use strict"; // this is mostly irrelevant.
// this will not work, because it's wrapped and not global
function ThisDoesntWork($scope) {
};
// window is the global root variable. So this works.
window.ThisWorks = function($scope) {
};
// this will work, because it's explicitly registering the controller
// presuming app is your Module variable from outside of the closure.
app.controller('ThisIsBest', function($scope) {
});
})();
//this works because it's global.
function ThisAlsoWorks($scope) {
}
// if you declare a global var, then set it inside
// of your closure, you're good to go too.
var ThisWillWorkToo;
(function {
//here we're setting it again.
ThisWillWorkToo = function($scope) {
};
})();
// if you're really crazy you can even do this...
var ThisWillWorkButItsWeird = (function() {
"use strict";
function ThisWillWorkButItsWeird($scope) {
}
return ThisWillWorkButItsWeird;
})();
最后,您可以将“use strict”放在任何函数中,或者如果您愿意,也可以放在文件级别。 “use strict”本身不会给你带来任何破坏。如您所见,注册控制器的方法有一千种。最好的选择可能是按照建议使用 .controller 方法显式注册它们。
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)