AngularFire 0.5.0 $on 'change' event not firing correctly

冷暖自知 提交于 2019-12-08 05:27:01

问题


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

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));
  }

}]);

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

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>

回答1:


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);
   });
}


来源:https://stackoverflow.com/questions/20859515/angularfire-0-5-0-on-change-event-not-firing-correctly

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!