Angular update property when changing another property

I have an array as shown below

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

In the array above, I can have the number of ui elements associated with the number as text fields. I want to change each value of a text field to update "Total" in testData.

Example:

If I hav e 3 text fields bound to Number1 with values ​​of 10, 20, 30, the total value should be 60, that is 10 + 20 + 30.

I tried using $ scope. $ watch, I'm not sure how to watch an array of arrays inside an array.

Please, help.

+4
source share
2 answers

. AngularJS 1.x.

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>
Hide result
+1

:

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

, updateTotal .

: https://docs.angularjs.org/api/ng/directive/ngChange

+2

Source: https://habr.com/ru/post/1618106/


All Articles