【问题标题】:how to callback angularfire (0.8.2) $firebaseArray to $scope and stay synchronized?如何将 angularfire (0.8.2) $firebaseArray 回调到 $scope 并保持同步?
【发布时间】:2014-11-15 09:07:41
【问题描述】:

我很困惑如何将 angularfire 的 syncArray 的 $loaded 承诺返回的原始数据绑定到 $scope,以防我不能简单地执行 ng-repeat。 我需要将原始数据传递给角度日历,并且没有 ng-repeat。

$scope.snapshot = fbutil.syncArray("snapshot/" + id)
$scope.events = []
$scope.snapshot.$loaded().then (entries) ->
  angular.forEach entries, ((entry) ->
    @push entry
    return
  ), $scope.events
console.log "$scope.events: ", $scope.events

将输出到 $scope.events: [] 而不会将 promise 内部的可用条目数组绑定到 $scope。 它确实适用于 ng-repeat 为什么不通过这种方式?

【问题讨论】:

  • 为什么要创建相同数据的静态(非同步)副本并将其放入同一个 $scope?这真的是你的意图吗?这看起来像 XY problem
  • 这是正确的,我试图用一个监视函数来解决同步问题:snapshot.$watch(function(event) { if (!!event) { console.log(event); return $( "#calendar").fullCalendar("refetchEvents"); } });这种“单向数据绑定”在这里对我有用,因为我没有在日历上设置事件只是显示它们。我确实明白你对 xy 问题的看法,并将更改这篇文章的标题。

标签: angularjs coffeescript firebase angularfire


【解决方案1】:

好吧,经过更多研究后,我偶然发现了 $scope 问题。 它在某种程度上可以使用回调参数,以便将转换后的数据交给 Angular 的 $scope

var resource, snapshot;
snapshot = fbutil.syncArray("snapshot/" + id);
resource = function(callback) {
  return snapshot.$loaded().then(function(entries) {
    var snap;
    snap = [];
    angular.forEach(entries, function(entry) {
      return snap.push({
        title: entry.title,
        start: new Date(entry.start),
        end: new Date(entry.end)
      });
    });
    return callback(snap);
  });
};
$scope.events = resource;

【讨论】:

  • AngularFire 不会默默地失败。它can also handle date objects 使用 $extendFactory。此外,您的问题询问如何将对象放入范围,但您的答案是关于转换数据并且不使用 AngularFire 提供的工具,并且不会保持正确同步。
  • 嗨 Kato 感谢您的反馈和有关日期对象处理的信息。我将编辑我的条目并再次从中删除不良反馈。你会这么好心并指出一个更好的方法来转换数据并尽可能避免回调方法来同步吗?提前致谢
  • 你好,@enigma,我在上一条评论中链接了你to this。那里有一个相当不错的讨论,并附有示例。这是在同步数组中转换数据的规范方法,也涵盖了in the doc。除了这些内容之外,您还有其他具体问题吗?因为我只是在复制该内容来回答您的问题。
猜你喜欢
  • 1970-01-01
  • 2023-03-24
  • 1970-01-01
  • 2016-03-29
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多