AngularJS控制器和“使用严格”

我最近开始使用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方法注册它们。

相关文章

ANGULAR.JS:NG-SELECTANDNG-OPTIONSPS:其实看英文文档比看中...
AngularJS中使用Chart.js制折线图与饼图实例  Chart.js 是...
IE浏览器兼容性后续前言 继续尝试解决IE浏览器兼容性问题,...
Angular实现下拉菜单多选写这篇文章时,引用文章地址如下:h...
在AngularJS应用中集成科大讯飞语音输入功能前言 根据项目...
Angular数据更新不及时问题探讨前言 在修复控制角标正确变...