在承诺之后从.catch函数中访问$ scope

时间:2017-10-23 11:25:03

标签: javascript angularjs firebase angularjs-scope firebase-authentication

我遇到了一个我无法解决的范围问题。

我的应用使用Google Firebase API通过发布到API来验证用户,然后通过更新$ scope变量向用户显示成功/错误消息。这是我的功能

$scope.message = "";

$scope.signin = function () {

    var auth = firebase.auth();
    auth.signInWithEmailAndPassword(signinEmail, signinPassword).catch(function (error) {
        var errorCode = error.code;
        console.log("errorCode " + errorCode);
        $scope.message = "An error Alert";
});
}

更新了我的signin函数中的$ scope工作正常,但是在内部catch函数中访问它不起作用。

到目前为止,我已尝试过:

  1. 更改我要使用的代码"此"而不是$ scope - 这似乎引起了更大的麻烦,因为当这个'这个'用来。 (可能是由于应用程序使用ng-Route这一事实)我想要使用$ scope或'这个'来保持我的应用程序。

  2. 我尝试以各种方式将$ scope注入函数中但没有成功。

  3. 我试图创建一个可以在我的catch块$scope.updateMessage(){ }中调用的第二个函数,但是这个函数不会调用,因为它是在$ scope上的事实。如果将其用作常规函数var fn = updateMessage(){ },则无法访问范围。

1 个答案:

答案 0 :(得分:0)

感谢您的回复

由于我试图在角度上下文之外更新范围变量,我可以通过访问HTML元素并使用$ apply

来更改它。
var scope = angular.element(document.getElementById('myElement')).scope();
    scope.$apply(function () {
    scope.message = errorMessage;
    });