Search code examples
javascriptangularjsangularjs-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). I want searchRecords() to be called only when I start typing (change searchText will fire 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.

Is this behavior by design or I am missing something?

EDIT:

I realized that this code fires my searchRecords():

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

EDIT:

I deleted the ng-change and added this:

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

Without any change of the $scope.searchText this code is executing on controller initialization.


Solution

  • I found a thread about that in a google group for angular - 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 }

    So yeah, I wanted to get away from such code, but obviously I can't