javascript - 使用 AngularJS 中的指令更改值输入 AngularJS

标签 javascript angularjs angularjs-directive angularjs-scope

当输入的值不满足条件时,我需要更改该值。在此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/

相关文章:

JavaScript 函数不起作用

javascript - Angular 自定义验证指令 - 如何正确跳过 ng-disabled 字段?

angularjs - Angular Bootstrap DatePicker 指令(Eternicode 版本)未保持打开状态

javascript - 使用类似 jQuery 的插件扩展 AngularJS

Javascript if/else 提交

javascript - WebView.loadUrl() 中的 Android JS

javascript - JS 类型错误 : is not a function

javascript - 使用 Angularjs 和 ng-model 进行数据绑定(bind),将毫米转换为英尺和英寸,反之亦然

javascript - 使用 onclick javascript 更改元素的类

angularjs - 在 ui-router 解析期间应用加载微调器