AngularFire 0.5.0 $on 'change' 事件未正确触发 [英] AngularFire 0.5.0 $on 'change' event not firing correctly

查看:24
本文介绍了AngularFire 0.5.0 $on 'change' 事件未正确触发的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

假设我有一组文章,我想通过它进行分页.

Let's say I have a collection of articles I am trying to paginate through.

我正在使用 $on("change") 事件来监听 indexlimit

I'm using the $on("change") event to listen for changes to index and limit

.controller('articlesCtrl', ["$scope", "$firebase", "$stateParams", function($scope, $firebase, $stateParams) {

  var limit = 2;
  var index = $stateParams.id;
  var articlesRef = new Firebase("https://example.firebaseio.com/articles").startAt(null, index).limit(limit);
  var obj = $firebase(articlesRef);

  obj.$on("change", function() {
    var keys = obj.$getIndex();
    index = keys[keys.length-1];
    console.log(obj);
  });

  $scope.update = function(){
    limit = limit + 2;
    obj = $firebase(articlesRef.startAt(null, index).limit(limit));
  }

}]);

我注意到 - 在初始加载时,$on("change") 事件会触发两次.

What I'm noticing - is on initial load the $on("change") event fires twice.

并且每次后续调用更新indexlimit都不会触发$on("change")事件.

And every subsequent call to update the index or limit does not fire the $on("change") event.

<button type="button" ng-click="update();">Update</button>

推荐答案

每次 $scope.update 触发时,您将 obj 变量分配给一个新的引用.但是,您只需将 obj.$on(change) 附加到原始 obj.

Each time $scope.update fires, you assign the obj variable to a new reference. However, you only attach obj.$on(change) to the original obj.

这可能可以通过一些实验来优化;这里有一个快速的蛮力让你开始:

This could probably be optimized with some experimentation; here's a quick brute force to get you started:

var limit = 2;
var index = $stateParams.id;
var articlesRef = new Firebase("https://example.firebaseio.com/articles");

$scope.update = update;
update(); // initialize

function update(){
   limit = limit + 2;
   var obj = $firebase(articlesRef.startAt(null, index).limit(limit));
   obj.$on("loaded", function() {
      var keys = obj.$getIndex();
      index = keys[keys.length-1];
      console.log(obj);
   });
}

这篇关于AngularFire 0.5.0 $on 'change' 事件未正确触发的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆