2014-03-28 124 views
1

当值不满足条件时,需要更改输入的值。在这example,当我添加一个细节,并更改单位价格输入,如果该值不是一个数字应改变值为“0.00”。在AngularJS中使用指令更改值输入AngularJS

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?

+0

我认为[ngModelController](http://docs.angularjs.org/api/ng/type/ngModel.NgModelController)就是要走的路。这是您处理ng模型数据的标准。 –

回答

0

我会做一个深$ scope.watch上invoice.items这样:

$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

+0

最好避免深入观察表演。他想格式化的ngModel已经注册了手表,所以我真的推荐使用它。 – m59