简体   繁体   中英

Angular $watch not triggered on change in $scope variable

So I have a routine that needs to run with user data that is retrieved at the initialization of the app.

My controller for the home page checks to see if there's a token in storage (a logged-in user) and then either runs the routine if $scope.currentUser already exists, or places a watch on it for when the AJAX call returns that data.

But the $watch callback is never triggered after its initialization.

Here's the Feed Controller code

if (sessionStorage.getItem('token'))
{
    if ($scope.currentUser) {getItems()}
    else {$scope.$watch('currentUser', popFeed()) }
}

function delayForUser()
{
    if ($scope.currentUser) {popFeed()}
}

And the Application Controller code

if (sessionStorage.getItem('token') && sessionStorage != 'null')
{
    UserSvc.getUser()
    .then(function (response) 
    {
        $scope.currentUser = response.data
    })

Assuming you can see currentUser from both controllers (you mentioned they are distinct), you need to pass a function on the $watch , not execute it immediately (with (), which is the result of that function ):

$scope.$watch('currentUser', function(newValue) {
    popFeed();
});

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