简体   繁体   English

访问AngularJS常量

[英]Accessing AngularJS constants

I have the following constant in my AngularJS app and want to access its values using the function shown below. 我的AngularJS应用程序中有以下常量,并希望使用下面显示的函数访问其值。 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: 我如何称呼getConstE如下:

   getConstV('clientDetails');

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] . 您的问题不是AngularJS问题,而是Javascript问题:在Javascript中,您可以通过两种方式访问​​关联数组:一种是点号array.key ,另一种是方括号array[key] If you use the dotted notation, Javascript try to access the property with name key inside the associative array. 如果您使用点分表示法,则Javascript会尝试在关联数组中使用名称key访问属性。 In your object, though, there isn't an attribute with that name and you obtain undefined . 但是,在您的对象中,没有具有该名称的属性,并且您获得了undefined On the contrary, the bracket notation lets you decide how to access the associative array (with a constant or a variable ). 相反,使用括号表示法可以决定如何访问关联数组(使用constantvariable )。 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. key显然是一个变量。

Difference between using bracket (`[]`) and dot (`.`) notation 使用方括号(`[]`)和点(`.`)表示法之间的区别

Did you inject your clients constant? 您是否为clients注入了常数?

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM