AngularJS - 控制器初始化时触发的 ng-change

AngularJS - ng-change fired with the controller initialization

我的模板中有这样的东西:

<input name="searchText" placeholder="Search" data-type="search" 
       ng-model="searchText" 
       ng-change="searchRecords()" 
       ng-keyup="onKeyUp()">

当我到达那个模板时,searchRecords() 函数被调用(ng-change 被触发)。我希望 searchRecords() 仅在我开始输入时被调用(更改 searchText 将触发 ng-change)。现在它通过控制器初始化被触发。

我尝试在控制器中将searchText设置为null'',但都是一样的。

这种行为是设计使然还是我遗漏了什么?

编辑:

我意识到这段代码触发了我的 searchRecords():

$scope.$watchGroup(['daysBefore', 'daysAhead'], function (newValues, oldValues, scope) { ... }

编辑:

我删除了 ng-change 并添加了这个:

$scope.$watch('searchText', function (newValue, oldValue) {
                $scope.searchRecords();
            });

在不对 $scope.searchText 进行任何更改的情况下,此代码在控制器初始化时执行。

如果你有一个ng-model,那么有一个ng-change事件是正常的。 您应该对 $scope.searchText var 进行 $watch。

我在 angular 的 google 组中找到了一个关于此的帖子 - https://groups.google.com/forum/#!topic/angular/uXldMqsQvRw

The watch fires automatically (and asynchronously via $evalAsync) upon registration, this is initialize the watcher and let your code know what the initial value is.

If this is undesirable then you can put this check into your save method:

function save(newVal, oldVal) { if (newVal === oldVal) return; // do stuff here }

是的,我想摆脱这样的代码,但显然我做不到

你可以使用ng-init设置一个标志,例如:“ng-init='initializing=true'”,并在ng-change函数中查看

您不需要使用 ng-change,您可以为该输入的 ng-model 创建观察器。

$scope.$watch(function() {
  return $scope.searchText;
}, function(n, o) {
  if(n != o){
    $scope.searchRecords();
  }  
}, true);
<input ng-model="searchText">

干杯