简体   繁体   中英

angular update property on change of another property

I have an array as shown below

var testData = {
    section1: [{
        Number1: 0
    }],
    Total: 0
}

In the above array I can have number of ui elements bound to number as textboxes. I want on change of each textbox value to update the "Total" on the testData.

Example:

If i hav e 3 textboxes bound to Number1 with values 10, 20, 30 the total value should be 60 ie 10+20+30.

I tried using $scope.$watch, I am not sure how to watch a list array inside an array.

Please help.

try using :

<input type="text" ng-change="updateTotal ()" />

in your controller, define updateTotal to calcul the new total.

The offical documentation : https://docs.angularjs.org/api/ng/directive/ngChange

You can create a function to calculate the total and show the value. The AngularJS 1.x "double binding" will do the rest.

 var myApp = angular.module('myApp',[]); myApp.controller('MyCtrl', ['$scope', function($scope) { // added more data for demonstration $scope.testData = { section1: [{ Number1: 0 }, { Number1: 0 }, { Number1: 0 }], Total: 0 }; $scope.trackTotal = function() { var total = 0; // I tried using reduce but didn't work, still figuring why for (var i = 0; i < $scope.testData.section1.length; i++) { total += Number($scope.testData.section1[i].Number1); } // keeping the object property updated $scope.testData.Total = total; console.log($scope.testData.Total); return total; }; }]); 
 <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script> <div ng-app="myApp" ng-controller="MyCtrl"> <ul ng-repeat="data in testData.section1"> <li> Number1[{{$index}}] <input type="text" ng-model="data.Number1"> </li> </ul> <p>{{trackTotal()}}</p> </div> 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM