i've seen lot of examples online showing following basic angularjs code:
var app = angular.module("exampleapp", []); // setter, creates new module app.controller(...
and in other files under same angular module:
var app = angular.module("exampleapp"); // getter, retrieves existing module app.service(...
this reads memory global "app" variable, accessible across other files. second file works if rid of "getter" , start right off app.service(...
.
i assume bad practice not use getter , use global variable in first place, i'm wondering if it's bad practice declare global variable at all. first thoughts wrap every file in iife locally scope variables, or rid of var app
part , chain .controller
, .service
, etc. right onto angular.module()
.
thanks in advance professional advice.
as global variables mutable everywhere, it's safer , more maintainable not using global variables. create modules in first place js file:
angular.module("exampleapp", []);
and in everyfile without assigning variable:
angular.module("exampleapp") .service("myservice", function () {});
or
angular.module("exampleapp") .component("mycomponent", {});
if need variables use functions:
(function () { var mycontroller = function () {}; mycontroller.$inject = ["$scope"]; angular.module("exampleapp") .controller(mycontroller); })();
also using bundlers webpack or browserify option. automatically create scopes per js files. don't need use invoked functions hide variables global scope. example:
var mycontroller = require('./mycontroller.js'); var myapp = require('./exampleapp.js'); myapp.controller(mycontroller);
in here, webpack, mycontroller
, myapp
variables not global variables. simple , clean...
Comments
Post a Comment