javascript - 如何在不使用全局范围的情况下分离 angularjs 文件

标签 javascript angularjs module declaration iife

我看过这篇文章AngularJS best practices for module declaration?但我仍然对为模块、 Controller 、服务等声明和分离 AngularJS 文件的最佳方法感到有点困惑。

我知道将 Controller 和服务包装在 IIFE 中是一种很好的做法,因为它可以防止它们在范围之外使用。将 Controller 和模块分成单独的文件以进行组织是一种很好的做法。

我的问题是,如果我有 Controller 文件

myCtrl.js

(function(){
  "use strict";

  app.controller("myCtrl", ['$scope', function($scope) {
    $scope.firstName = "John";
    $scope.lastName = "Doe";
  }]);
})();

指令文件

myDirective.js

(function(){
  "use strict";
  app.directive("w3TestDirective", function() {
    return {
      template : "I was made in a directive constructor!"
    };
  });
})();

在自己的文件中声明模块的最佳实践是什么

myModule.js

是否应该将其保留在全局范围内,以便任何东西都可以访问它,如下所示:

var app = angular.module("myApp", []);

或者有没有办法将其包装在像 IIFE 这样的东西中,以使其远离全局范围,但仍然可以被其他文件访问?

最佳答案

在 Controller 和指令片段中,不需要 IIFE,因为没有任何内容暴露在全局范围内。

var app = ... 不应暴露在全局范围内。可以使用模块 getter 来代替:

var app = angular.module("myApp")

这需要保留加载的 JS 文件的顺序。模块应该首先使用 angular.module("myApp", []) 定义,然后才能定义模块单元。

除非应用程序使用 JS 模块(AMD、CommonJS、ES6)来实现模块化,否则遵循“每个文件一个模块”模式是有益的。这可以显着提高可测试性,并且永远不会遇到与模块相关的竞争条件:

(function(){
  "use strict";

  var app = angular.module("myApp.myCtrl", []);

  app.controller("myCtrl", ['$scope', function($scope) {
    $scope.firstName = "John";
    $scope.lastName = "Doe";
  }]);
})();
<小时/>
angular.module("myApp", ["myApp.myCtrl", "myApp.w3TestDirective"]);

在这种情况下,模块文件的加载顺序并不重要。

关于javascript - 如何在不使用全局范围的情况下分离 angularjs 文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41307696/

相关文章:

angularjs - Angular 在 Cordova 上的行为不同

java - 代码中的变量范围

javascript - 两个相互依赖的选择字段

javascript - 将类添加到添加到数组中的最新项目以表明它们是新的

c# - 将 JSON 对象转换为 C# 模型 Web API 2

python - 在哪里克隆 Python 模块 git 存储库?

ruby - Ruby 中的模块方法

c# - C# 中的类和模块是什么

javascript - 三个复选框的 if 语句 javascript

javascript - cordova 插件网络接口(interface)问题