How To Separate Angularjs Files Without Using Global Scope
Solution 1:
In controller and directive snippets IIFEs aren't needed because nothing is exposed to global scope.
var app = ...
shouldn't be exposed to global scope. Module getter can be used instead:
var app = angular.module("myApp")
This requires to preserve the order of loaded JS files. The module should be defined first with angular.module("myApp", [])
, only then then module units can be defined.
Unless the app uses JS modules (AMD, CommonJS, ES6) for modularity, it is beneficial to follow 'one module per file' pattern. This allows to considerably improve testability and never run into module-related race conditions:
(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"]);
In this case it doesn't matter in which order module files are loaded.
Solution 2:
we can build relation between angular files for example
- controllers
- services
- factories
- and so on
with angular module
for example: angular.module("myApp",["dependencies"])
angular.module("myApp").controller("myCtrl",function(){}) or angular.module("myApp").service("myservice",function(){})
Post a Comment for "How To Separate Angularjs Files Without Using Global Scope"