问题
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