angularjs - 奇怪: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
,为什么?我试图用 替换onAuthStateChanged
,var user = firebase.auth().currentUser;
也没有工作。
有人可以告诉我它有什么问题吗?如果您需要我显示代码的更多其他部分,请告诉我,谢谢!
注意:我还注意到谷歌浏览器的自动填充已将我txtContactNo
作为我的登录输入框,不确定这是否与问题有关。
解决方案
使用 $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 。
有关详细信息,请参阅
推荐阅读
- javascript - 如何在本地环境中测试共享社交媒体链接预览?
- gcc - 将 Codewarrior 的 Inline Assembler 翻译成 GCC Inline Assembler
- sql-server - 程序出错,sql 发送邮件不起作用
- mysql - 如何使用测试数据填充 MySQL 数据库?
- regex - 正则表达式没有从后面提取正确的值
- linux - 汇编器输出无法在我的 Linux 机器上运行
- math - 为什么SVG绕点旋转公式与普通公式相反?
- c# - 为什么钱会出现错误 CS0649?
- c# - 使用 ModuleInit.Fody 在 ModuleInitializer 中使用多线程
- outlook - 通过 VB 脚本访问电子邮件时弹出消息