访问AngularJS常数 [英] Accessing AngularJS constants
问题描述
我在AngularJS应用中的以下常量,想用下图所示的功能来访问自己的价值观。问题是,我通过密钥字符串,但很明显,如图中的code以下则返回undefined,所以我想知道有没有办法,我可以通过不断的密钥字符串转换为返回相应的正确的恒定值到关键传递?谢谢
myApp.constant('客户',{
clientData:clientDetails
clientList:顾客});
getConstV:功能(键){
//这个方法返回clientDetails
的console.log(clients.clientData); //这一次FAIL ...返回undefined
的console.log(clients.Key);
}
getConstE如何我呼吁如下:
getConstV('clientDetails');
您的问题不是一个AngularJS的问题,而是一个JavaScript的问题:在Javascript中,您可以访问两种方式的关联数组:一个是点号 array.key
键,另一个是括号标记阵列[关键]
。如果用点号,使用Javascript尝试用名称来访问属性键
关联数组中。在你的对象,虽然没有使用该名称的属性,您获得未定义
。相反,支架符号让您决定如何访问关联数组(以恒
或变量
) 。总的来说:这个符号
数组[钥匙]
产生相同的结果如
array.key
但如果你想有一个灵活的解决方案(使用一个变量),你必须使用括号记号这样
阵列[关键]
其中,键
是,显然,一个变量。
<一个href=\"http://stackoverflow.com/questions/17189642/difference-between-using-bracket-and-dot-notation\">Difference用括号(`[]`)和点之间(`.`)符号
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');
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
这篇关于访问AngularJS常数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!