如何从变量执行表达式?
我需要像其他输入一样的公式。 例如我的数据:
$scope.items = [{
name: 'first',
formula: '',
value: 1,
type: 'text',
},{
name: 'second',
formula: '',
value: 2,
type: 'text',
},{
name: 'third',
formula: '{first}+{second}',
type: 'formula',
}];
和我的观点:
<ul>
<li ng-repeat="item in items">
<div ng-switch on="item.type">
<div ng-switch-when="text">
<input type="text" ng-model="item.value" name="{{item.name}}">
</div>
<div ng-switch-when="formula">
<span>{{item.formula}}</span>
</div>
</div>
</li>
我希望结果是3 但它是{first} + {second} of course
答案 0 :(得分:1)
<div ng-switch-when="formula">
<span>
{{getFormulaResult(item.formula)}}
</span>
</div>
控制器方法:
$scope.getFormulaResult = function(formula){
var formulaSplits = formula.split("+");
var left = formulaSplits[0];
left = left.substr(1);
left = left.substring(0, left.length-1);
var right = formulaSplits[1];
right = right.substr(1);
right = right.substring(0, right.length-1);
var sum = 0;
for(var i = 0; i < $scope.items.length; i++){
if($scope.items[i].name == left || $scope.items[i].name == right){
sum = sum + parseInt($scope.items[i].value, 10);
}
}
return sum || 0;
}