AngularJS calculate a dynamic number of variables in braces -
i want calculate total sum, of dynamic number of variables within angular's brace syntax.
the loop utilize :
var total = 0; for(x=0; x< objects.length; x++) { total += objects[x].num; }
i recreate {{ total }}
or {{total()}}
, have total update when ever 1 of variables changed.
here looking for: jsfiddle
html
<div ng-app="myapp" ng-controller="ctrl" ng-strict-di> {{total()}}<br/> <input type="text" ng-model="item.num" ng-repeat="item in objects"/> </div>
js:
angular.module('myapp',[]).controller('ctrl',function($scope) { angular.extend($scope,{ objects:[ {num:7}, {num:8}, {num:9} ], total : function(){ var res = 0; (var i=0;i<$scope.objects.length;i++) res+=parseint($scope.objects[i].num); homecoming res; } }); });
update test if it's updating total on object's num update play code this:
setinterval(function() { $scope.objects[1].num++; $scope.$apply(); },500); //increase num of 2nd object 1, every half of sec
to test if it's still updating when adding new objects, play code that:
setinterval(function() { $scope.objects.push({num:math.floor(math.random()*100)}); },5000); //add new object, random num: value, every 5 seconds
angularjs
No comments:
Post a Comment