AngularJS 控制器和"use strict"



我最近开始使用jshint,它要求我使用"使用严格"的函数形式。从那时起,AngularJS引发了一个错误:

"错误:参数'WebAddressController'不是一个函数,没有定义"

当我删除"使用严格"功能形式时,控制器加载正负。

控制器:

(function () {
    "use strict";
    function webAddressController($scope, $rootScope, web_address_service) {
             // Do things
    }
}());

有人对这里发生的事情有任何见解吗?

首先,我想指出pkozlowski确实知道他在Angular上的东西,但这实际上并不是一个角度问题,因为它是关闭的问题。

Angular在两个地方寻找控制器:

  1. 在通过Module.controller()注册的控制器注册表中
  2. 在A 全局变量(或全局函数声明)

问题在于,"使用严格"内部的所有内容都不是全局。它已包裹并私有化包含它的匿名函数。

(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;
  })();

在一天结束时,您可以在任何功能中使用"严格",也可以在文件级别中放置。"使用严格"本身并没有为您打破任何东西。如您所见,有一千种注册控制器的方法。最好的选择可能只是按建议的.Controller方法明确注册它们。

我想Jshint试图在这里告诉您是为了避免全局变量(这显然是一个很好的做法!)。

angularjs对解决相同的问题(即避免全局变量)有略有不同的看法,并允许您在模块中定义控制器(使用全局angular名称空间)。您可以使用这样的模块重写示例:

angular.module('myApp',[]).controller('webAddressController', function($scope) {
    // Do things
});

这是JSFIDDLE,在实践中说明了这一点:http://jsfiddle.net/t3vbe/1/

使用这种方法,您不会用控制器构造函数污染全局名称空间。

,如果要使用严格的模式,则需要更改Jshint配置以允许angular全局变量。另外,您也可以将整个代码(再次使用模块)包装到执行Imediatelly的函数中:

(function () {
    "use strict";
angular.module('myApp',[]).controller('webAddressController', function($scope) {
    $scope.name = 'World';
    // Do things
});
}());​

这是jsfiddle:http://jsfiddle.net/t3vbe/4/

对我来说,只有当您想定义纯JavaScript,"助手"功能时,这才有意义

如果您的Angular模块已经在其他地方加载了@pkzolowski正在执行的操作:

var app = angular.module('myApp');
app.controller(...);
app.service(...);
...

它基于这里的评论:AngularJS定义不同文件中同一模块的服务

注意使用Angular.Module('MyModule',[])将创建模块myModule并覆盖任何名为MyModule的现有模块。使用Angular.Module('MyModule')检索现有模块。

您是否尝试过在外部和之前编写'使用严格'(function()

"use strict"; // <-- add it here
(function () {
    //"use strict"; <-- remove from here
    function webAddressController($scope, $rootScope, web_address_service) {
         // Do things
    }
}());

我的答案是基于我看到的文件

的文件

最新更新