我最近开始使用JSHint,它要求我使用“使用严格”的函数形式。从那以后,AngularJS抛出一个错误:
“错误:参数’webAddressController’不是一个函数,得到undefined”
控制器:
- (function () {
- "use strict";
- function webAddressController($scope,$rootScope,web_address_service) {
- // Do things
- }
- }());
有谁有任何洞察这里发生了什么?
首先,我想说明pkozlowski真的知道他在Angular的东西,但这实际上不是一个角度问题,因为它是一个关闭的问题。
Angular正在两个地方寻找控制器:
>在自己的注册表控制器注册通过Module.controller()
>在全局变量(或全局函数声明)
问题是,你的闭包中的“使用严格”的一切都不是全局的。它包装和私有化在包含它的匿名函数。
- (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”,如果愿意,也可以在文件级别。 “使用严格”本身不打破你的任何东西。有一千种方法来注册控制器,你可以看到。最好的选择可能是显式地使用.controller方法注册它们。