加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 综合聚焦 > 服务器 > 安全 > 正文

AngularJS控制器和“使用严格”

发布时间:2020-12-17 08:31:14 所属栏目:安全 来源:网络整理
导读:我最近开始使用JSHint,它要求我使用“使用严格”的函数形式。从那以后,AngularJS抛出一个错误: “错误:参数’webAddressController’不是一个函数,得到undefined” 当我删除“使用严格”的功能形式控制器加载精细。 控制器: (function () { "use stric
我最近开始使用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方法注册它们。

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读