Angularfire:从$FirebaseObject的子对象创建$FirebaseObject

Angularfire: Create a $FirebaseObject from a child of a $FirebaseObject

本文关键字:FirebaseObject 对象 创建 Angularfire      更新时间:2023-10-13

我正在构建一个时间线系统,它从根本上是由许多不同的指令构建的。

在抽象中,每个项目看起来是这样的:

<project id='id'>
  <h3 ng-bind='project.name'></h3>
  <timeline items='project.timelines[0]'>
    <timeline-item item='item' ng-repeat='item in timeline'>
      <comments items='item.comments'>
        <comment item='comment' ng-repeat='comment in comments'>
          <user id='comment.user'></user> 
          <p ng-bind='comment.body'></p>
        </comment>
      </comments>
    </timeline-item>
  </timeline>
</project>

在顶层,我通过获取对项目的原始firebase引用来创建项目的对象,然后将其包装在$firebase包装器中。最后,我使用$asObject()为模型准备了一份副本。

这种技术对<project>指令来说很好,因为我可以访问所有顶级属性以及.$save()方法。

但是,当我将此对象的子对象传递给子指令时,我将失去调用.$save()的能力。这意味着模型会在视图中完美更新,但不会保存在Firebase中。

一般来说,如何从现有的$FirebaseObject中提取$FirebaseObject$FirebaseArray以传递给指令

我知道我可以获得原始参考来实现这一点,但在实践中,这看起来像:

...
// timeline-item.js
scope: {
  item: '='
},
link: function(scope) {
  scope.item; // is a $FirebaseObject
  scope.comments scope.item.$ref().child('comments');
},
template:
"<comments items='comments'></comments>"
// comments.js
scope: {
  items: '='
},
link: function(scope) {
  scope.items; // is a Firebase reference
  scope.items = $firebase(scope.items).$asArray();
}

也许这个问题可以用$bindTo来解决?但我也不知道这将如何在多个指令中发挥作用。

$asArray有一个名为$getRecord的函数,我认为它可以为您解决这个问题。

var list = $firebase(ref).$asArray();
var rec = list.$getRecord("foo"); 
rec.update(data);

https://www.firebase.com/docs/web/libraries/angular/api.html#angularfire-firebasearray getrecordkey