繁体   English   中英

仅触发一次ng-change

[英]Firing ng-change only once

我只需要在输入类型为text的输入上从ng-change调用一次函数,并且在第一次调用时,它将布尔值设置为true,之后我想在输入改变时禁止触发ng-change,因为所有我需要做的是将布尔值更改为true

这是控制器

angular.module("app",[]).controller('FieldCtrl',['$scope',function($scope){
  $scope.Value = '';
  $scope.IsRequired = true;
  $scope.HasBeenForTheFirstTime = false;

  $scope.ValueChanged = function() {
    $scope.HasBeenForTheFirstTime = true;
    console.log("isFired");
  };
}]);

和HTML只是

<input type="text" 
       ng-model="Value"
       value="{{Value}}"  
       ng-change="ValueChanged()">

另一件事是,在这种情况下使用ng-change是否正确?

使用$ watch ...

angular.module("app",[]).controller('FieldCtrl',['$scope',function($scope){
      $scope.Value = '';
      $scope.IsRequired = true;
      $scope.HasBeenEditedBefore = false;


      $scope.UnWatch = $scope.$watch("Value",function(){
        if($scope.Value.length > 0)
        {
            $scope.HasBeenEditedBefore = true;
            $scope.UnWatch(); 
        }
      });

    }]);

您可以删除$ scope.ValueChanged函数并使用以下代码就足够了。

<input type="text" 
       ng-model="Value"
       value="{{Value}}"  
       ng-change="HasBeenForTheFirstTime=true" />

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM