Accessing AngularJS constants

我怕爱的太早我们不能终老 提交于 2020-01-07 06:45:18

问题


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');

回答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




回答2:


Did you inject your clients constant?

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


来源:https://stackoverflow.com/questions/24286337/accessing-angularjs-constants

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!