AngularFire: How to update scope without syncing to Firebase (i.e. local states, like “loading” or “selected”)
我是Firebase和AngularJS(和AngularFire)的新手,但是我正在设法解决大多数问题……但是,这让我很沮丧。
情况:
我有一个服务器和一个单独的前端。前端没有针对Firebase的写权限-它只能读取自己的数据(使用服务器提供的令牌)。服务器具有前端可用来进行更新的API。
为了使前端请求更新列表中的特定项目,它需要将该项目的Firebase ID提供给服务器(以及API需要的其他信息)。服务器将首先验证该ID,然后使用它来更新正确的Firebase数据。
我已经让AngularFire对这些动作进行了三向数据绑定,这太棒了!
问题:
可以说我的Firebase结构如下:
1 2 3 4 5 6 7 8 9 10 11 12 13 | actions: { -JFeuuEIFDh: { // Firebase IDs for arrays label:"One", . . . }, -JfuDu2JC81: { "label":"Two", . . . } |
我有以下HTML:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 | <ul> <!-- key is the Firebase ID for the action, which is required for my server to know which object to update --> <li ng-repeat="(key, action) in actions"> action.label <!-- **Loading IS NOT and SHOULD NOT be stored in Firebase,** it's simply a local state which AngularJS should manage --> <p ng-hide="!action.loading">Loading... </p> </li> </ul> |
doAction看起来像这样:
1 2 3 4 5 6 7 8 9 10 11 12 13 | $scope.doAction = function(key, item) { $scope.actions[key].loading = true; var onComplete = function () { $scope.actions[key].loading = false; } // Calls to the server, etc... . . . } |
我正在使用
但是,由于AngularFire设置了三向数据绑定,因此它尝试将所做的更改保存到数据库中,但由于客户端没有写权限而失败!
我不希望它将加载保存到数据库中!在那里只是简单地更新了该段落的
那我该怎么办?如果不取消三向绑定,我想不出任何方法来更新范围...我是否认为这是错误的方式?
编辑
嵌套在AngularJS文档的$ FirebaseObject。$ bindTo下是:
use a variable prefixed with
_ , which will not be saved to the server, but will trigger$watch() .
但是,当我改用
我有同样的问题。但这似乎可以解决。
https://www.firebase.com/docs/web/libraries/angular/api.html#angularfire-firebaseobject-bindtoscope-varname
If $destroy() is emitted by scope (this happens when a controller is > destroyed), then this object is automatically unbound from scope. It can > also be manually unbound using the unbind() method, which is passed into ? > the promise callback.
//照常设置同步数组
1 | $scope.syncedArray = $firebaseArray(ref); |
//对变量调用取消绑定
1 | $scope.syncedArray.unbind(); |
//照常对数组进行排序,过滤和处理,完成后在其上调用.bind()。
我找不到解决该问题的干净方法。
use a variable prefixed with
_ , which will not be saved to the server, but will trigger$watch() .
这实际上不是用代码实现的。我当时正在考虑自己提交一个实现,但这并不像我希望的那么简单。即使toJSON停止返回_'d变量后,它仍然尝试将(未更改的)JSON保存到Firebase,因此您必须以某种方式更正它...我没有去过。
为了解决这个问题,我使用了AngularFire的$ asArray而不是$ asObject。该数组是只读的。除非您调用特殊功能,否则Firebase不会尝试同步任何更改。就我而言,这行得通,但是在其他情况下,可能还不够。
我不得不改变使用数组而不是对象的模板,因为现在提供的是数字键,而不是Firebase中使用的实际键。我用
真是一团糟..但是它现在会让我通过。