Sam Su Sam Su - 2 months ago 10
AngularJS Question

How can I use ngChange in ngRepeat?



angular.module('app',[]).controller('NgListController',function($scope){
$scope.items = [
{name:'Coke', price: 5, sum: 2, sumMoney: 10},
{name:'Bread', price: 3, sum: 2, sumMoney: 6}
];
$scope.priceChange = function(newVal, oldVal){
//TODO
};
});

.sum{
width:25px;
}
.sumMoney{
width:40px;
background-color:#EEE;
}

<!DOCTYPE html>
<html>
<head>
<script data-require="angular.js@*" data-semver="1.3.7" src="https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.3.7/angular.js"></script>
<link rel="stylesheet" href="style.css" />
<script src="script.js"></script>
</head>
<body ng-app="app">
<fieldset ng-controller="NgListController">
<div ng-repeat="item in items">
<p>
<lable>{{item.name}},</lable>
<lable>$ {{item.price}} x </lable>
<input type="text" class="sum" ng-model="item.sum" ng-change="priceChange(item.price)">
=
<input type="text" class="sumMoney" ng-model="item.sumMoney" ng-readonly="true">
</p>
</div>
<span>Totol money : {{totalMoney}}</span>
</fieldset>
</body>
</html>





I'm trying to use ng-repeat and ng-change in an angular-js app. check the snippet above. How can I get every item's sum money when its sum change and get the total money of all items?

Answer

it works:

angular.module('app', []).controller('NgListController', function($scope) {
 $scope.items = [
        {name:'Coke', price: 5, sum: 2, sumMoney: 10},
        {name:'Bread', price: 3, sum: 2, sumMoney: 6}
      ];

  

   $scope.$watch('items', function (newValue, oldValue) {
       $scope.calPrice();
   }, true);

  
   $scope.totalMoney = 0;
   
   $scope.calPrice = function(html_code){
      $scope.totalMoney = 0;
     $scope.items.forEach(function(value) {
        value.sumMoney = (value.price*value.sum);
        $scope.totalMoney += value.sumMoney;
    });
  }
 
  
  
});
.sum {
  width: 25px;
}
.sumMoney {
  width: 40px;
  background-color: #EEE;
}
<!DOCTYPE html>
<html>

<head>
  <script data-require="angular.js@*" data-semver="1.3.7" src="https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.3.7/angular.js"></script>
  <link rel="stylesheet" href="style.css" />
  <script src="script.js"></script>
</head>

<body ng-app="app">
  <fieldset ng-controller="NgListController">
    <div ng-repeat="(itemKey,item) in items">
      <p>
        <lable>{{item.name}},</lable>
        <lable>$ {{item.price}} x</lable>
        <input type="text" class="sum" ng-model="item.sum">=
        <input type="text" ng-model="item.sumMoney" class="sumMoney"  ng-readonly="true">
      </p>
    </div>
    <span>Totol money : {{totalMoney}}</span>
  </fieldset>
</body>

</html>