[英]How to watch on change of select with ng-change?
Any idea how can I update the total when the selected value changed? 知道更改所选值后如何更新总数吗? http://jsfiddle.net/yx97x0xk/1
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. 当您使用$ watch时,将在每个摘要周期对观察到的表达式进行评估,如果有更改,则将调用处理程序。
With ng-change, the change is restricted to a user action on a particular input element. 使用ng-change时,更改仅限于用户对特定输入元素的操作。
With ng-change, the handler is invoked explicitly in response to an event. 使用ng-change时,响应于事件显式调用处理程序。
With $watch, change can come from anywhere: user action, controller function, service - all will trigger the handler. 使用$ watch,更改可以来自任何地方:用户操作,控制器功能,服务-所有这些都将触发处理程序。
Just use ng-model="json.qty"
in your select
tag and remove ng-selected
from option
tag. 只需在您的
select
标签中使用ng-model="json.qty"
并从option
标签中删除ng-selected
。 This will do the trick. 这将达到目的。 :-)
:-)
Angular will automatically execute a function ( getSum
in this case) if the returning value from the function changes. 如果函数的返回值发生更改,Angular将自动执行一个函数(在本例中为
getSum
)。
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>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.