注意:类似于:angularjs execute expression from variable但我不想让所有可能性和正在使用的数据集弄乱我的范围。
我希望能够在 Angular 的表达式中使用预先确定的公式。
示例:
var config = {
"Test": {
name: "test",
formula: true,
formulaValue: "item['propertyOne'] + item['propertyTwo']"
}
}
<div ng-repeat="item in myArray">
<span ng-if="config[item.name].formula">{{config[item.name].formulaValue}}</span>
</div>
对 formulaValue
中的公式进行计算,就像我这样输入:
<div ng-repeat="item in myArray">
<span>{{item['propertyOne'] + item['propertyTwo']}}</span>
</div>
我该如何实现这个目标?为每种类型的公式创建 $scope 函数也不太可行,因为这些公式在配置中设置的数量相当大。
最佳答案
这不是最理想的配置设置,但最坏的情况下您需要使用 eval()
,由于安全性,它不太受欢迎
类似于:
function parseConfig(item, configKey){
if(config[configKey].formula){
return eval(config[configKey].formulaValue);
}
}
$scope.parseConfig = parseConfig;
将其放入您的配置的服务中,但现在仅放在范围内。
在 View 中会是这样的
{{parseConfig(item, 'Test')}}
如果是我,我会更喜欢看起来像这样的配置
var config = {
"Test": {
name: "test",
formula: true,
formulaType: 'concat',
formulaValue: ['propertyOne','propertyTwo']
}
然后您将检查 FormulaType 并根据 FormulaValue 中的属性执行所需操作,而无需使用 eval()
关于javascript - 来自字符串的 AngularJS 表达式,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38088164/