簡體   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