为什么这个角度值没有更新?

时间:2014-07-16 13:49:48

标签: javascript angularjs angularjs-scope angularfire

这看起来像AngularFire 101,但我无法弄清楚为什么它不起作用。

在我的控制器中:

var unamecallback = function(exists) {
        console.log("exists = " + exists);
        if(exists) {
            $scope.data.usernameAvailable = -1;
        } else {
            $scope.data.usernameAvailable = 1;
        }
    };

    $scope.usernameInUse = function()
    {
        var username = $scope.data.color.value + $scope.data.animal.value + $scope.data.digits;
        usergenService.usernameInUse(username, unamecallback);
    };

在服务中:

usernameInUse: function(username, callback) {
            console.log("searching for " + username);
            var usersRef = new Firebase(FBURL + '/users/');
            var user = usersRef.child(username);
            user.once('value', function(ss) {
                var exists = (ss.val() !== null);
                callback(exists);

            });
        }

当触发usernameInUse时,从控制台输出:

//searching for Username2 usergenService.js:23   // username being searched for
//exists = false usergenController.js:47  // does not exist
//searching for Username1 usergenService.js:23  // a different username
//exists = true  // does exists

我在$ scope.data.usernameAvailable:

上有以下$ watch
$scope.$watch('data.usernameAvailable', function() {
        console.log($scope.data.usernameAvailable);
    });

但是从控制台输出中可以看到 - 每次都会调用回调,但$ scope.data.usernameAvailable值没有更新。这不完全正确。它有时更新,但肯定不是每次回调都被击中。当它更新时,它也不总是'正确'。有时候它应该设置为false,反之亦然。

呃。帮助

1 个答案:

答案 0 :(得分:3)

尝试在回调中添加$ scope。$ apply():

var unamecallback = function(exists) {
        console.log("exists = " + exists);
        if(exists) {
            $scope.data.usernameAvailable = -1;
        } else {
            $scope.data.usernameAvailable = 1;
        }
        $scope.$apply();
    };