diplosaurus
diplosaurus

Reputation: 2588

How to suppress a watch statement or digest cycle in Angular

Currently I have a text input attached to a model with a $scope.watch statement observing the model. This is all used to achieve a type of auto complete / typeahead feature.

<!-- HTML -->
<input type="text" ng-model="search.mySearchText">


// JS
var deregister = $scope.$watch('search.mySearchText', doSearch);

function doSearch() {
    mySearchService.executeSearch(search.mySearchText)
        .then(function(res) {
            // do something with the data
        });
}

This works fine. However, occasionally in my .then function I want to make changes to search.mySearchText. Obviously this would cause the watcher to be fired again, but I don't want this.

What I'm hoping to do is find a way to suppress the $watch from firing that next time. Maybe by somehow telling Angular that that particular watched model property is no longer dirty?

I tried removing the $watch by de/re- registering the watch at appropriate times, but that didn't work either.

function doSearch() {
    mySearchService.executeSearch(search.mySearchText)
        .then(function(res) {
            deregister(); // shut off the watch
            search.mySearchText = 'some new string'; // manipulate the model property that I don't want to cause a search
            deregister = $scope.$watch('search.mySearchText', doSearch); 

        });
}

However, this didn't prevent the event firing like I expected, which is why I'm now looking for a way to suppress the event.

Upvotes: 0

Views: 78

Answers (1)

Nicholas
Nicholas

Reputation: 486

You could have a variable that determines whether doSearch exits early, like so:

var searchActive = true;
function doSearch() {
    if (!searchActive) return;
    mySearchService.executeSearch(search.mySearchText)
        .then(function(res) {
            searchActive = false;
            // do manipulation of search.mySearchText
            searchActive = true;
        });
}

Upvotes: 1

Related Questions