Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

AngularJS - Getting Module constants from a controller

I'm trying to build a myApp.config module to store some settings for my app, I wrote a config.js file:

angular.module('myApp.config', [])     .constant('APP_NAME','My Angular App!')     .constant('APP_VERSION','0.3'); 

I added it to my app.js (angular-seed):

angular.module('myApp', ['myApp.filters', 'myApp.services', 'myApp.directives', 'myApp.controllers', 'myApp.config']). 

I added it to the index.html file, and now I'm trying to figure out how to get it in my controllers, I tried:

angular.module('myApp.controllers', ['myApp.config'])   .controller('ListCtrl', ['$scope', 'myApp.config', function($scope, $config) {     $scope.printme = $config;   }]) 

but I'm getting:

Unknown provider: myApp.configProvider <- myApp.config

I'm probably doing something wrong here, any ideas ?

like image 697
Asaf Avatar asked Jun 29 '13 18:06

Asaf


2 Answers

I don't think it is valid to use the module name in an injection like that. You can simply inject the constants by name, though:

angular.module('myApp.controllers', ['myApp.config'])   .controller('ListCtrl', ['$scope', 'APP_NAME', function($scope, appName) {      $scope.printme = appName; }]); 
like image 132
mfelix Avatar answered Sep 28 '22 08:09

mfelix


I think the simplest approach is to add a constant using an object literal. This fits most application configuration use cases I think, because it supports a complex config object. The constant step also runs early, before other providers are registered.

angular.module('myApp').constant('cfg', {   url: 'https://myapi.com/v1/',   httpTimeout: 5000 }) 

To use it you just inject cfg:

angular.module('myApp').factory('user', function(cfg, $http){   // cfg and $http together at last }) 
like image 40
SimplGy Avatar answered Sep 28 '22 08:09

SimplGy