0

如何从变量执行表达式?

我需要类似公式的东西,它取决于其他输入。例如我的数据:

    $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}

4

1 回答 1

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;
}
于 2013-09-07T10:12:00.550 回答