首页 > 解决方案 > 奇怪:AngularJS $scope 可以在 View 中显示除 Firebase user.email 之外的所有内容

问题描述

这里发生了一些奇怪的事情还是我错过了其他东西?我有以下模板视图:

用户配置文件.html

<div id="divUserProfile" ng-controller="userProfileController">
    <h1>User Profile</h1>

    <fieldset>
        <legend>Organizational Information</legend>
        <table>
            <tr>
                <td>
                    <label>Email Address</label>
                    <label id="lblEmail" class="label-value">{{email}}</label>
                </td>
                <td>
                    <label>Contact Number</label>
                    <input id="txtContactNo" type="text" value="{{contactNumber}}">
                </td>
            </tr>
        </table>
    </fieldset>
</div>

index.js

var app = angular.module("myApp", ["ngRoute"])
.config( // $routeProvider config here... )
.controller("userProfileController", function ($scope) {
    console.log("This is userProfileController!");

    firebase.auth().onAuthStateChanged(function (user) {
        if (user) {
            console.log("User = " + user.email); // User does exist and singed in!
            $scope.email = user.email; // Email not rendered!
            console.log("$scope.email = " + $scope.email); // It does contain my email address!
        } else {
            console.log("User = " + user);
        }
    });
});

问题:{{email}}未渲染!但如果你硬编码$scope.email = "ee@eee.com";,它就会出现!另外,如果你console.log($scope.email),它确实包含我登录的电子邮件地址但从未呈现,为什么???事实上,我已经在我的标签上填充了更多标签,<fieldset>并且所有标签都使用相同的标签正确渲染,$scope除了分配有 Firebase 的标签user.email,为什么?我试图用 替换onAuthStateChangedvar user = firebase.auth().currentUser;也没有工作。

有人可以告诉我它有什么问题吗?如果您需要我显示代码的更多其他部分,请告诉我,谢谢!

注意:我还注意到谷歌浏览器的自动填充已将我txtContactNo作为我的登录输入框,不确定这是否与问题有关。

在此处输入图像描述

标签: angularjsfirebasefirebase-authentication

解决方案


使用 $apply:

var app = angular.module("myApp", ["ngRoute"])
.config( // $routeProvider config here... )
.controller("userProfileController", function ($scope) {

    console.log("This is userProfileController!");

    firebase.auth().onAuthStateChanged(function (user) {
        if (user) {
            console.log("User = " + user.email); // User does exist and singed in!
            $scope.email = user.email; // Email not rendered!
            //IMPORTANT
            $scope.$apply();
            console.log("$scope.email = " + $scope.email); // It does contain my email address!
        } else {
            console.log("User = " + user);
        }
    });
});

AngularJS 通过提供自己的事件处理循环来修改正常的 JavaScript 流程。这将 JavaScript 拆分为经典和 AngularJS 执行上下文。只有在 AngularJS 执行上下文中应用的操作才能受益于 AngularJS 数据绑定、异常处理、属性监视等。

您还可以使用$apply()从 JavaScript 输入 AngularJS 执行上下文。请记住,在大多数地方(控制器、服务),处理事件的指令已经为您调用了 $apply。仅在实现自定义事件回调或使用第三方库回调时才需要显式调用 $apply 。

有关详细信息,请参阅


推荐阅读