Hai Bui
Hai Bui

Reputation: 303

Angularjs how to get constant in controller

How can I get constant in controller.

 angular.module('app').register.controller('navigationCtrl', function ($scope, navigationSvc, $STORAGE_KEY) {
    alert($STORAGE_KEY);

$STORAGE_KEY is constant variable. I want get it without injecting. I want something like:

angular.constant('$STORAGE_KEY')

Upvotes: 3

Views: 11711

Answers (3)

maitre_c
maitre_c

Reputation: 41

You can try this:

angular.module('app').constant('$STORAGE_KEY', {
  value : 'myval'
});

And you can call her by your controller

angular.module('app').controller('navigationCtrl', ['$STORAGE_KEY',function($STORAGE_KEY){
 alert($STORAGE_KEYS.value);
}]);

Don t forget that a change on the value of your constant will be applied everywhere in your angular's module.

Upvotes: 3

sylwester
sylwester

Reputation: 16498

You can create object containing all keys like :

var keys = {
    $STORAGE_A: 'a',
    $STORAGE_B: 'b',
    $STORAGE_C: 'c',
    $STORAGE_D: 'd',

}

add this object to your app:

angular.module('app').value('keys', keys);

and after that inject only one keys to conntrolles and easy access all your keys ie:

angular.module('app').controller(['$scope', 'keys', function ($scope, keys) {

    //ie
    $scope.keya = keys.$STORAGE_A



}]);

Upvotes: 1

pedro.nofuentes
pedro.nofuentes

Reputation: 61

You have to declare the constant in your module:

angular.module('app').constant('$STORAGE_KEY', 'your_constant_value');

You can see an example in Plunkr

And in Angular's module docs

Upvotes: 0

Related Questions