Search code examples
javascriptangularjsangularjs-servicewatchangularjs-watch

Why is my $watch function returning undefined?


Here is my watch function, below... it's currently watching a function in my ViewFactory.

// Watch for when tagsFilterModal is showing:
vs.$watch('ViewFactory.retrieveSavedViews()', function(newVal) {
    console.log("New Data", newVal);
});

The retrieveSavedViews() function calls an API and returns data:

function retrieveSavedViews() {
    console.log('retrieveSavedViews called...');
    ApiFactory.getViews().then(function(data) {
        if (data.data.status === 'Success') {
            // Store views locally:
            return storeSavedViews(data.data.views);
            // Populate load view dropdown:

        }
    });
}

^ you can see above that I return another function storeSavedViews():

function storeSavedViews(data) {
    savedViews = data;
    console.log('storeSavedViews savedViews',savedViews);
    return savedViews;
}

enter image description here

How am I using the $watch service wrong here?


Solution

  • I advice you - nearly never use $watch on functions. Because then function will launch in each digest cycle. Look this example.

    There is simple $scope.$watch('test()'), and you see that test() launches if I change another scope variable and you can not control this.

    What you should do is to store promise to object: $scope.object = Service.get() and watch it. Quite often you can leave watcher creation to angular and just have in html:

    <div ng-if="!object.$resolved">Retrieving data...
    </div>
    <div ng-if="object.$resolved">Got data {{object}}
    </div>
    

    And if you need some specific actions to be done after async call finishes - you better provide callback function.