AngularJS控制器和“使用严格”

前端之家收集整理的这篇文章主要介绍了AngularJS控制器和“使用严格”前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
我最近开始使用JSHint,它要求我使用“使用严格”的函数形式。从那以后,AngularJS抛出一个错误

错误:参数’webAddressController’不是一个函数,得到undefined”

当我删除“使用严格”的功能形式控制器加载精细。

控制器:

  1. (function () {
  2. "use strict";
  3.  
  4. function webAddressController($scope,$rootScope,web_address_service) {
  5. // Do things
  6. }
  7.  
  8. }());

有谁有任何洞察这里发生了什么?

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

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

>在自己的注册表控制器注册通过Module.controller()
>在全局变量(或全局函数声明)

问题是,你的闭包中的“使用严格”的一切都不是全局的。它包装和私有化在包含它的匿名函数

  1. (function() {
  2. // nothing in here is global or even public.
  3. // "use strict" or not.
  4.  
  5. "use strict"; // this is mostly irrelevant.
  6.  
  7. // this will not work,because it's wrapped and not global
  8. function ThisDoesntWork($scope) {
  9. };
  10.  
  11. // window is the global root variable. So this works.
  12. window.ThisWorks = function($scope) {
  13.  
  14. };
  15.  
  16. // this will work,because it's explicitly registering the controller
  17. // presuming app is your Module variable from outside of the closure.
  18. app.controller('ThisIsBest',function($scope) {
  19.  
  20. });
  21.  
  22. })();
  23.  
  24. //this works because it's global.
  25. function ThisAlsoWorks($scope) {
  26.  
  27. }
  28.  
  29. // if you declare a global var,then set it inside
  30. // of your closure,you're good to go too.
  31. var ThisWillWorkToo;
  32.  
  33. (function {
  34. //here we're setting it again.
  35. ThisWillWorkToo = function($scope) {
  36. };
  37. })();
  38.  
  39.  
  40. // if you're really crazy you can even do this...
  41. var ThisWillWorkButItsWeird = (function() {
  42. "use strict";
  43.  
  44. function ThisWillWorkButItsWeird($scope) {
  45.  
  46. }
  47.  
  48. return ThisWillWorkButItsWeird;
  49. })();

在一天结束时,您可以在任何函数内部使用“use strict”,如果愿意,也可以在文件级别。 “使用严格”本身不打破你的任何东西。有一千种方法注册控制器,你可以看到。最好的选择可能是显式地使用.controller方法注册它们。

猜你在找的Angularjs相关文章