MChan
MChan

Reputation: 7192

Accessing AngularJS constants

I have the following constant in my AngularJS app and want to access its values using the function shown below. Problem is that I pass the key as string but obviously as shown in the code below it returns undefined, so I was wondering is there a way I can convert the string passed to constant key in order to return the correct constant value corresponding to the key being passed? Thanks

myApp.constant('clients', {
    clientData: "clientDetails",
    clientList: "clients" });


getConstV : function(Key){
      //this one returns clientDetails
      console.log(clients.clientData);           

      //This one FAIL...returns undefined   
      console.log(clients.Key);            
    }

How I call getConstE is as follows:

   getConstV('clientDetails');

Upvotes: 0

Views: 243

Answers (2)

superpuccio
superpuccio

Reputation: 12992

Your problem is not an AngularJS problem, but a Javascript issue: in Javascript you can access the associative arrays in two ways: one is the dotted notation array.key and the other is the bracket notation array[key]. If you use the dotted notation, Javascript try to access the property with name key inside the associative array. In your object, though, there isn't an attribute with that name and you obtain undefined. On the contrary, the bracket notation lets you decide how to access the associative array (with a constant or a variable). To recap: this notation

array["key"]

produces the same result as

array.key

but if you want a flexible solution (using a variable) you must use the bracket notation this way

array[key]

where key is, clearly, a variable.

Difference between using bracket (`[]`) and dot (`.`) notation

Upvotes: 2

Klaus Native
Klaus Native

Reputation: 3509

Did you inject your clients constant?

angular.module('myAngularApp')
    .factory('MyService', function (clients) {
        ...
        function getConstV (Key){
            console.log(clients.clientData);   
        }  
        ...              
    }
}

Upvotes: 1

Related Questions