Any idea how can I update the total when the selected value changed? http://jsfiddle.net/yx97x0xk/1
angular.module('app', ['QuickList']).controller('mainCtrl', function($scope) {
$scope.getSum = function() {
return $scope.myJson.map(function(x) {
return x.price * x.qty
}).reduce(function(a, b) {
return a + b
});
}
$scope.myJson = [{
"id": "1",
"name": "banana",
"price": 12,
"qty": 3,
}, {
"id": "2",
"name": "watermelon",
"price": 12.9,
"qty": 4,
}]
})
They are not the same, clearly. One is used solely in the controller; the other is a directive on an input element.
But even in their application they differ.
When you use $watch the watched expression will be evaluated on every digest cycle, and if there is a change, the handler is invoked.
With ng-change, the change is restricted to a user action on a particular input element.
With ng-change, the handler is invoked explicitly in response to an event.
With $watch, change can come from anywhere: user action, controller function, service - all will trigger the handler.
Just use ng-model="json.qty"
in your select
tag and remove ng-selected
from option
tag. This will do the trick. :-)
Angular will automatically execute a function ( getSum
in this case) if the returning value from the function changes.
See it working below:
angular.module('app', []).controller('mainCtrl', function($scope) { $scope.getSum = function() { return $scope.myJson.map(function(x) { return x.price * x.qty }).reduce(function(a, b) { return a + b }); }; $scope.myJson = [{ "id": "1", "name": "banana", "price": 12, "qty": 3, }, { "id": "2", "name": "watermelon", "price": 12.9, "qty": 4, }] });
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script> <div ng-app='app' ng-controller='mainCtrl'> <div ng-repeat="json in myJson"> <li>{{json.name}}</li> <select name="" id="" ng-model="json.qty"> <option ng-repeat="i in [1,2,3,4,5,6,7,8,9,10]">{{$index + 1}}</option> </select> </div> <h1>total:{{getSum()}}</h1> </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.