angularjs 根据其他字段的总和更新模型

angularjs update model based on sum of other fields

我希望能够根据其他两个字段的结果更新我的数据模型中的值。使用

<td><input ng-value="s.hours*s.rate"></td>

我计算结果没有问题,但我如何才能将它绑定到 toal?

例如我试过了

<td><input ng-model="s.total" ng-value="s.hours*s.rate"></td> 

但是模型覆盖了这里的值?

查看完整示例

    'use strict';
    var app = angular.module('app', []);
        app.controller('MainCtrl', ['$scope', function ($scope) {
            $scope.staff = [
            {"id": "1","name": "Alex","rate": "10", "hours": "10","total":"0"},
            {"id": "2","name": "Brad","rate": "20", "hours": "10","total":"0"},
            {"id": "3","name": "Cam","rate": "15", "hours": "10","total":"0"}
        ];
        }]);
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
    <div ng-app="app">
            <div ng-controller="MainCtrl">
              <table>
                <tr><td>name</td><td>rates</td><td>hours</td><td>total</td><td>total</td></tr>
                <tr ng-repeat="s in staff">
                    <td>{{s.name}}</td>
                    <td><input  ng-model="s.rate"></td>  
                    <td><input  ng-model="s.hours"></td>
                    <td><input ng-value="s.hours*s.rate"></td>
                  <td><input ng-model="s.total"></td>
                </tr>
                </table>
        </div>
    </div>

如何实现?

许多 方法可以完成此任务。这是一个简单的循环,每当列表更改时更新 total 属性:

$scope.$watch('staff'. function(newVal, oldVal) {
  angular.forEach(newVal, function(s) {
    s.total = s.rate * s.hours;
  });
});

您可以在 "rate" 或 "hours" 的任何变化时触发计算。

        $scope.calc= function(s) {
             s.total=s.hours*s.rate;   
        }
        angular.forEach($scope.staff, function(s) { $scope.calc(s)});

我已将 fiddle 代码和 HTML 修改为:

http://jsfiddle.net/macl/sx3zouuv/

希望对您有所帮助。

我可能会在您的代码段中替换它:

<input ng-model="s.total">

与:

{{ total(s) }}

然后在你的控制器中:

$scope.total = function (staffmember) { return staffmember.rate * staffmember.hours; }

请记住,您可以始终在 AngularJS 表达式中嵌入函数调用以清理您的代码,并且您可以在您的范围内公开函数以供此类使用。