angularjs - 为什么 Angular 不更新范围?

标签 angularjs firebase

我对 Angular 还很陌生,我使用 firebase 作为后端。我希望有人可以调试这个问题。当我第一次访问我的页面 www.mywebsite.com/#defaultHash 时,数据不会加载到 DOM 中,而是在访问另一个哈希链接并返回后加载到 DOM 中。

我的 Controller 是这样的:

/* initialize data */

var fb = new Firebase('https://asdf.firebaseio.com/');

/* set data to automatically update on change */

fb.on('value', function(snapshot) {

  var data = snapshot.val();
  $scope.propertyConfiguration = data.products;
  console.log($scope.propertyConfiguration);
  console.log("Data retrieved");

});

/* save data on button submit */

$scope.saveConfigs = function(){

  var setFBref = new Firebase('https://asdf.firebaseio.com/products');
  setFBref.update($scope.propertyConfiguration);
  console.log("configurations saved!");

};

我有 3 个哈希路由,分别为“共享”、“注册”和“主页”,否则.redirectTo 设置为“共享”。(它们都使用此 Controller )这是发生的错误:(所有“链接”都是href="#hashWhereever")

1) 前往 website.com/#Shared 或刷新。控制台记录 $scope.propertyConfiguration 和“检索到的数据”。 DOM 没有显示任何内容。

2) 点击website.com/#Registration,控制台正确记录$scope数据,DOM正确加载。

3) 单击返回 website.com/#Shared,控制台正确记录 $scope 数据,但这次 DOM 正确加载。

4) 刷新当前正确加载的website.com/#Shared。 DOM 元素消失。

由于 $scope.data 在所有情况下都是正确的,Angular 不应该确保 DOM 正确反射(reflect)模型吗?为什么只有当我从另一个链接单击该页面时,DOM 才能正确加载。

我可以通过添加 window.location.hash = "Shared"来“修复”它,但它会在控制台中引发大量错误。

已修复:(有点)

函数 $scope.$apply() 强制 View 与模型同步。我会自己回答这个问题并关闭它,但我仍然想知道为什么当我正确地将值分配给 $scope 时 View 无法正确加载。如果 Angular 的“脏检查”会在模型可能发生更改时进行检查,那么为 $scope 赋值是否会超出资格?

最佳答案

Angular 无法知道您已为 $scope.variable 分配了值。这里没有魔法。当您运行指令(ng-click/ng-submit)或 Angular 内部函数时,它们都会调用 $apply() 并触发摘要(检查脏标志和更新例程)。

比 $apply 更安全的方法是使用 $timeout。目前,如果您在 Firebase 中调用写入操作,它可以同步触发事件监听器(child_added、child_changed、value 等)。这可能会导致您在 $apply 范围内调用 $apply。如果您这样做,则会引发错误。 $timeout 绕过了这个。

参见this SO Question有关摘要和 $timeout 主题的更多信息。

This doc in the Angular Developer Guide covers how compile works ;对于任何认真的 Angular 开发人员来说,这都是非常好的背景知识。

此外,您可以通过使用 official Firebase bindings for Angular 为自己节省大量精力。 ,它已经考虑了所有这些实现细节。

模糊相关说明:在不久的将来,Angular 将能够利用 Object.observe magic处理这些更新。

关于angularjs - 为什么 Angular 不更新范围?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28935808/

相关文章:

javascript - 使用谷歌地图自动完成时,ng 模型仅在点击后更新输入

javascript - AngularJS 多选复选框保存在逗号分隔的字符串中

javascript - AngularJS 指令调用另一个指令未正确传递数据以使用 $compile 进行渲染

javascript - angularjs 数据绑定(bind)到按钮不起作用

java - 如何重用不同类中的方法

firebase - 在现有 Firebase 项目目录中初始化 firebase CLI 功能

javascript - 在 Firebase Cloud Functions 中使用 Google Vision API 时出现类型错误

android - Firebase Analytics 甚至会出现在日志中,但不会出现在 Firebase 控制台上

angularjs - ASP.Net 应用程序干扰远程主机 Let's Encrypt(通过 Plesk)安装?

node.js - 在 Firebase Functions 服务器中设置 Swagger Ui