$scope变量发生更改时未触发Angular$watch

Angular $watch not triggered on change in $scope variable

本文关键字:watch Angular scope 变量      更新时间:2023-09-26

所以我有一个例程,需要使用在应用程序初始化时检索到的用户数据来运行。

我的主页控制器检查存储中是否有令牌(登录用户),然后如果$scope.currentUser已经存在,则运行例程,或者监视AJAX调用何时返回该数据。

但是$watch回调在初始化之后永远不会被触发。

这是进料控制器代码

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

应用程序控制器代码

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

假设您可以从两个控制器中看到currentUser(您提到它们是不同的),您需要在$watch上传递一个函数,而不是立即执行它(使用(),这是该函数的结果):

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