jquery - AngularJS: Sum of Input values -
i have simple list of inputs bound list of items display nicely. when change value in input, the sum doesn't update??
example: http://plnkr.co/edit/b7teasxsfvylrmj5xcnj?p=preview
html
<body ng-controller="mainctrl"> <div ng-repeat="item in items"> <p><input type=text value="{{item}}"></p> </div> total: <input type=text value="{{sum(items)}}"> </body>
script
app.controller('mainctrl', function($scope) { $scope.items = [1,2,5,7]; $scope.sum = function(list) { var total=0; angular.foreach(list , function(item){ total+= item; }); return total; } });
check fiddle implementation: http://jsfiddle.net/9tsdv/
the points take note of:
- use ng-model directive input element allow two-way binding between item model , input element
- since ng-repeat creates child scope , elements in items array of primitive type or value type , hence copied value during first digest cycle , further changes made input fields not reflected in sum because modifications bound present variables in ng-repeat's created child scope. (see other references on scope inheritance more details)
html:
<body ng-controller="mainctrl"> <div ng-repeat="item in items"> <p><input type=text ng-model="item.value"></p> </div> total: <input type=text value="{{sum(items)}}"> </body>
controller code:
app.controller('mainctrl', function($scope) { $scope.items = [ { value: 1 }, { value: 2 }, { value: 5}, { value: 7 } ]; $scope.sum = function(list) { var total=0; angular.foreach(list , function(item){ total+= parseint(item.value); }); return total; } });
Comments
Post a Comment