简体   繁体   中英

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.

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;
        });
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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