我一直在尝试使用角度过滤器获取嵌套常量的值。但我无法找到获得价值的有效方法。我被允许使用lodash" ^ 2.4.1"我尝试使用_.pick但我仍然只能访问根级别常量而不是嵌套的常量。
//consider this
angular.module('myApp',[])
.constants('appConstants', {
CONS1: 'root',
CONS2: {
NEST1: 'nested cons1',
NEST2: 'nested cons2',
}
)
.filter(getConstants, function () {
return function (input) {
var value = appConstants[input];
if (! value) {
var keys = input.split('.');
value = appConstants;
angular.forEach(keys, function(key, index) {
value = value[key];
});
}
return value;
}
});
//where as
appConstants[CONS1]; //works
appConstants[CONS2.NEST1]; // return undefined
//in lodash
_.pick(appConstants, 'CONS2.NEST1'); // returns empty object
答案 0 :(得分:2)
答案 1 :(得分:1)
AngularJS constant只是它被定义为的值(这里是一个对象)。
{
CONS1: 'root',
CONS2: {
NEST1: 'nested cons1',
NEST2: 'nested cons2',
}
}
要获得NEST1
,请使用常用的property accessors,点符号appConstants.CONS1.NEST1
或括号表示法appConstants["CONS1"]["NEST1"]
。
最简单的方法是将常量对象添加到$rootScope
。
angular.module('myApp', [])
.constants('appConstants', {
CONS1: 'root',
CONS2: {
NEST1: 'nested cons1',
NEST2: 'nested cons2',
}
})
.run(function($rootScope, appConstants) {
$rootScope.CONSTANTS = appConstants;
});
在任何模板中,只需使用CONSTANTS
作为对象。
<span>{{ CONSTANTS.CONS2.NEST1 }}</span>
来源:Can I directly access module constant from HTML under AngularJS
如果你真的想使用lodash,请使用_.get
function使复杂路径能够解析为正确的嵌套对象。
_.get(appConstants, "CONS1.NEST1");
所以过滤器可以简单如下:
.filter("const", function() {
return function(input) {
return _.get(appConstants, input);
};
});
将字符串路径传递给过滤器以获取值。
{{ "CONS2.NEST1" | const }}
Amy Blankenship presents Angular's $parse
在她的回答中,在我看来,在这种情况下,这是一种比Lodash更好的方法。
我无法使用
_.get
,因为我可以使用lodash 2.4.1的旧版本。
有两种选择:
_.get
非常复杂,但对于我们的简单情况,点上的简单字符串split
可能会这样做。
.filter("getConstants", function() {
return function(input) {
var obj = appConstants,
path = input.split('.'),
index = 0,
length = path.length;
while (obj != null && index < length) {
obj = obj[path[index++]];
}
return obj;
};
});
答案 2 :(得分:0)
你在常量声明中忘记了右括号('}')。
也许试试这个:
.constants('appConstants', {
CONS1: 'root',
CONS2: {
NEST1: 'nested cons1',
NEST2: 'nested cons2',
}
})