How to extend or isolate a constant value in AngularJS when using modules? -
How to extend or isolate a constant value in AngularJS when using modules? -
to maintain code clean i'm in habit of defining url's constants in angularjs applications, looking like:
var myapp = angular.module('myapp', ['mymodule']); myapp.constant('url', { google: 'http://www.google.com', facebook: 'http://www.facebook.com' }); now, works fine problems when define (and use) constant in module:
var mymodule= angular.module('mymodule', []); mymodule.constant('url', { twitter: 'http://www.twitter.com' }); because, when want utilize url.twitter constant in directive (inside module) no longer available because definition of url constant in 'myapp' has overriden value. illustration when create directive:
mymodule.directive('mydirective', function(){ homecoming { template: '<div></div>', controller: function(url){ console.log(url.twitter); // logs undefined when used within 'myapp' } }; }); see live example: http://plnkr.co/edit/xiogvwfj4gupsvkts0ic?p=preview
think of 'mymodule' beingness third-party module include in project. if accidentally utilize same names constants, whole thing broken.
how overcome utilize case without having utilize different names same purpose?
i think question boils downwards to:
a 3rd party module (that didn't write) defines 'url' constant.
i include module dependency in app, , define url (without knowing url defined):
var app = angular.module('myapp', ['thirdpartymodule']); app.constant('url', { twitter: 'www.twitter.com'}); all of sudden, app breaks , stops working.
how 1 avoid pitfall?
answer:
you can utilize angular's injector determine if constant defined:
angular.module('myapp', ['thirdpartymodule']); var injector = angular.injector(), url = injector.has('url') ? injector.get('url') : {}; the above code guarantee object returned - either url defined in 3rd party module, or empty object literal, if not defined.
then, can extend 'url' follows:
angular.extend(url, { twitter: 'www.twitter.com' }); word of caution:
this work if url undefined or defined in third-party module object literal. not work if url defined primitive (ie. string).
unfortunately, can't think of way guard against scenario in clean way. recommend not overriding defined constants @ all, , relying on naming convention create injectables unique. example, constants, services, providers , factories, utilize unique prefix reduces likelihood of naming collisions:
var app = angular.module('tgapp', ['thirdpartymodule']); app.constant('tgurl', { ... }); angularjs constants modularity
Comments
Post a Comment