简体   繁体   中英

why angularJs $watch only run once

codes in the watch run only once . how can i fix it ?

 this.$rootScope.$watch('tabType', () => {
            if (this.$rootScope["tabType"] === TabType.Sent) {
                this.$scope.refreshSentList();
            } else if (this.$rootScope["tabType"] === TabType.Archive) {
                this.$scope.refreshArchiveList();
            } else if (this.$rootScope["tabType"] === TabType.Inbox) {
                this.$scope.refreshInboxList();
            } else if (this.$rootScope["tabType"] === TabType.Snooz) {
                this.$scope.refreshSnoozList();
            } else if (this.$rootScope["tabType"] === TabType.Trash) {
                this.$scope.refreshTrashList();
            }
        },true);

So the probable reason for this issue is that $watch is not able to find that element in view when controller initiates. For $watch to bind/work the element should be already present in the view.

My guess - You must be using ng-if in view. And ng-if creates element only when the condition is true.

I faced this issue two times and removing ng-if worked both times.

This is an example working on ES5, i see you use ES6 if i'm not wrong.

however, that shouldn't affect how $watch work

$scope.$watch('tabType', function (newValue, oldValue) {
    console.log(newValue);
    console.log(oldValue);
});

Also with this on the begining isn't nessesary with $watch

Hope this help you

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