0

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');
3
  • 3
    Mmh...what if you try to write console.log(clients[key]) instead of console.log(clients.key)? Commented Jun 18, 2014 at 13:07
  • @superpuccio to accept your answer (which is correct) you must post it as an answer, can you do so? Commented Jun 18, 2014 at 17:26
  • 1
    I tried to answer as clearly as possible, I'm glad that I have helped you! Commented Jun 19, 2014 at 10:38

2 Answers 2

2

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

Sign up to request clarification or add additional context in comments.

Comments

1

Did you inject your clients constant?

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.