javascript - 尽管在 $watch 函数中设置了 $scope 变量,但 $scope 变量未定义

标签 javascript angularjs service angularfire watch

我尝试使用用户的 uid 将一些内容插入到我的 Firebase 数据库中,但由于某种原因,结果未定义。看一下下面的代码:

页面加载时设置用户数据信息(authData)的主 Controller :

flickrApp.controller('mainCtrl', ['$scope', '$rootScope', '$firebase', 'Auth', 'shared', function($scope, $rootScope, $firebase, Auth, shared) {

    Auth.$onAuth(function(authData) {
        shared.setAuth(authData);
        $scope.authData = shared.getAuth();
    });
}]);

处理身份验证状态并在我的 Controller 之间共享它的服务:

flickrApp.service('shared', function() {

    var authentication = false;

    return {
        getAuth: function () {
            return authentication;
        },
        setAuth: function (auth) {
            authentication = auth;
        }
    };
});

这是它不起作用的地方,在我的标签 Controller 中。 $scope.authData$watch 函数中正确设置,但是当我尝试在 var ref 行中使用它时,它说$scope.authData 未定义(因此我无法访问 uid)。我不明白为什么这不能正常工作..

我是否也必须将 $apply 与观察者函数一起使用,还是出了什么问题?

flickrApp.controller('tagsCtrl', ['$scope', '$rootScope', '$firebase', 'shared', function($scope, $rootScope, $firebase, shared) {

    $scope.tagsList = [];
    $scope.shared = shared;

    $scope.$watch('shared.getAuth()', function(authData) {
        $scope.authData = authData;
        console.log($scope.authData);
    });

    var ref = new Firebase ('https://flickr.firebaseio.com/users/' + $scope.authData.uid);
    var sync = $firebase(ref);

    $scope.addTag = function(tag) {

        $scope.tagsList.push(tag);

        sync.$set({favoriteTags: $scope.tagsList});
    }
}]);

最佳答案

我认为问题是,对 ref 的分配是在 $scope.authData 的数据设置在 $watch 中之前完成的。尝试将您的代码更改为:

flickrApp.controller('tagsCtrl', ['$scope', '$rootScope', '$firebase', 'shared', function($scope, $rootScope, $firebase, shared) {

    $scope.tagsList = [];
    $scope.shared = shared;
    var ref,sync;

    $scope.$watch('shared.getAuth()', function(authData) {
        $scope.authData = authData;
        console.log($scope.authData);
        if($scope.authData){
            ref = new Firebase ('https://flickr.firebaseio.com/users/' + $scope.authData.uid);
            sync = $firebase(ref);
        }
    });



    $scope.addTag = function(tag) {

        $scope.tagsList.push(tag);

        sync.$set({favoriteTags: $scope.tagsList});
    }
}]);

关于javascript - 尽管在 $watch 函数中设置了 $scope 变量,但 $scope 变量未定义,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28380325/

相关文章:

javascript - 使用 KendoUI 的 Listview 控件进行服务器端分页

Android:如何安排即使我的应用程序关闭也会调用的 Alarmmanager 广播事件?

Java ServiceImpl 方法不断返回 null

javascript - 使用 JS 以编程方式加载 CSS

javascript - 使用 jquery 或 javascript 单击按键上的按钮

javascript - 如何在从 Google 电子表格中提取数据的 Google 图表上显示注释?

javascript - 从简单数组创建关联数组,每个数组项的键自动递增

javascript - 发生状态更改时不应用 ng-class

angularjs - 如何在 AngularJS 中将变量传递给 css

javascript - Controller <-> 服务交互和单元测试 : Am I doing this wrong?