仅更换一次ng-change

时间:2014-04-29 02:54:50

标签: javascript angularjs

我需要在类型文本的输入上只调用一次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是正确的吗?

2 个答案:

答案 0 :(得分:0)

使用$ 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(); 
        }
      });

    }]);

答案 1 :(得分:-1)

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

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