绑定不适用于Angular.js和Firebase简单登录

时间:2014-03-08 03:11:03

标签: angularjs firebase

与Angular一起使用Firebase Simple Login时,我发现了一些奇怪的行为。

我无法按预期获得$ scope变量绑定。我认为或者$ scope.test会在成功登录后发生变化,但事实并非如此。即使在登录后它仍然是假的。鉴于这是我的第一个Angular项目,我猜它很简单,但我看了一遍,但没有找到答案。

代码非常简单。首先是HTML:

<body ng-app>
    <div ng-controller="LoginController">
        <div ng-hide="test">
            <h1>Welcome.  Please log in.</h1>
            <p>Test is {{test}}</p>
            <label>Username</label>
            <input type="text" ng-model="username" />
            <label>Password</label>
            <input type="password" ng-model="password" />
            <button ng-click="login()">Log in</button>
        </div>
        <button ng-show="test" ng-click="logout()">Log out</button>
    </div>

    <script type='text/javascript' src='https://cdn.firebase.com/js/client/1.0.6/firebase.js'></script>
    <script type='text/javascript' src='https://cdn.firebase.com/js/simple-login/1.2.5/firebase-simple-login.js'></script>
    <script type="text/javascript" src="js/lib/angular.js"></script>
    <script type="text/javascript" src="js/controllers/LoginController.js"></script>
</body>

一个控制器:

function LoginController($scope) {
    var FB = new Firebase("https://[myfirebase].firebaseio.com");
    $scope.user = false;
    $scope.error = false;
    $scope.test = false;

    $scope.auth = new FirebaseSimpleLogin(FB, function(error, user){
        if(error) {
            $scope.error = error;
        } else if(user) {
            // would expected binding to take effect here, but not
            $scope.user = user;
            $scope.test = true;
        } else {
            console.log("no user");
        }
    });

    $scope.logout = function() {
        this.auth.logout();
    };

    $scope.login = function () {
        console.log("Attempting login");
        this.auth.login('password', {
            email: this.username,
            password: this.password
        });
    };
}

感谢任何能指出我正确方向的人。

1 个答案:

答案 0 :(得分:3)

您需要使用$scope.$apply()让角度知道您已在范围内更改了某些内容。在将第三方库与监视范围变量集成时,您需要执行此操作。

$scope.auth = new FirebaseSimpleLogin(FB, function(error, user){
    $scope.$apply(function() {
        if(error) {
            $scope.error = error;
        } else if(user) {
            // would expected binding to take effect here, but not
            $scope.user = user;
            $scope.test = true;
        } else {
            console.log("no user");
        }
    }
});