Skip to content Skip to sidebar Skip to footer

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 t

Solution 1:

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

Solution 2:

Did you inject your clients constant?

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

Post a Comment for "Accessing Angularjs Constants"