简体   繁体   English

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

[英]AngularJS - ng-change fired with the controller initialization

I have something like this in my template: 我的模板中有以下内容:

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

When I get to that template, searchRecords() function is called (ng-change is fired). 当我转到该模板时,将调用searchRecords()函数(触发ng-change)。 I want searchRecords() to be called only when I start typing (change searchText will fire ng-change ). 我希望仅当我开始键入时才调用searchRecords() (更改searchText将触发ng-change )。 Right now it is fired with the controller initialization. 现在,它通过控制器初始化被触发。

I tried to set searchText to null , '' in the controller but it was the same. 我试图设置searchTextnull''的控制器,但它是一样的。

Is this behavior by design or I am missing something? 这是设计使然,还是我缺少了某些东西?

EDIT: 编辑:

I realized that this code fires my searchRecords() : 我意识到这段代码会触发我的searchRecords()

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

EDIT: 编辑:

I deleted the ng-change and added this: 我删除了ng-change并添加了以下内容:

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

Without any change of the $scope.searchText this code is executing on controller initialization. 在不更改$scope.searchText此代码在控制器初始化时执行。

您可以使用ng-init来设置标志,例如:“ ng-init ='initializing = true'”,然后在ng-change函数中检查

You don't need to use ng-change you can create the watcher for ng-model of that input. 您无需使用ng-change即可为该输入的ng-model创建观察者。

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

Cheers 干杯

If you have a ng-model, then it is normal to have a ng-change event. 如果您有ng-model,那么发生ng-change事件是正常的。 You should do a $watch of the $scope.searchText var instead. 您应该改为对$ scope.searchText var进行$ watch。

I found a thread about that in a google group for angular - https://groups.google.com/forum/#!topic/angular/uXldMqsQvRw 我在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. 手表在注册时自动触发(并通过$ evalAsync异步触发),这将初始化手表并让您的代码知道初始值。

If this is undesirable then you can put this check into your save method: 如果不希望这样做,则可以将此检查放入您的保存方法中:

function save(newVal, oldVal) { if (newVal === oldVal) return; 函数save(newVal,oldVal){如果(newVal === oldVal)返回; // do stuff here } //在这里做事}

So yeah, I wanted to get away from such code, but obviously I can't 是的,我想摆脱这种代码,但显然我不能

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

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