当输入的值不满足条件时,我需要更改该值。在此example ,当我添加详细信息并更改单价输入时,如果该值不是数字,则应将该值更改为“0.00”。
scope.$watch(attrs.ngModel, function(newValue, oldValue) {
if ( isNaN(newValue) ) {
scope.item.price = "0.00";
console.log("isn't numeric");
} else {
console.log("is numeric");
}
});
问题是该值不是数字,打印“不是数字”,但也打印“是数字”。仅当我更改“scope.item.price”的值时才会发生这种情况。
有什么方法可以改变输入的值而不被调用两次scope.$watch?
最佳答案
我会在 invoice.items
上进行深入的 $scope.watch:
$scope.$watch('invoice.items', function(){
$scope.subtotal=0;
angular.forEach($scope.invoice.items,
function(item) {
$scope.subtotal += item.qty * item.price;
});
$scope.igv= $scope.subtotal * 0.18;
$scope.total=$scope.subtotal + $scope.igv;
}, true);
查看 plunkr http://plnkr.co/edit/5rzjeIG0C76a8l0ZAp4u?p=preview ,请注意深度监视末尾的 true
。
关于javascript - 使用 AngularJS 中的指令更改值输入 AngularJS,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22702297/