Fairly new to Angular and building a twitter stream that loads cached tweets on click event. Problem I am seeing is that tweets are loaded before button to load more is clicked. There is a binding to the tweets scope that I am not understanding. Below is relevant code:
html:
<button ng-if="moreTweets" ng-click="loadMoreTweets()">Load More Tweets</button>
<div ng-repeat="tweet in tweets" class="tweetContainer" ng-bind-html="tweet" ></div>
factory:
angular.module('TweetService', ['ngResource'])
.factory('TweetData', function ($resource) {
return $resource('/2/messages', {}, {
query: { method: 'GET', isArray: false }
})
})
controller:
.controller('MainCtrl', function ($scope, $timeout,TweetData) {
$scope.tweets = [];
var allTweets = [];
(function tick() {
TweetData.get({payload: $scope.payload},function(data){
tweethandler(data)
$timeout(tick, 5000);
})
})();
$scope.loadMoreTweets = function(){
$scope.moreTweets = false;
$scope.tweets = allTweets;
}
var tweethandler = function(body){
var tweets = messages.map(function(body.messages) { return encodeTweet(body.messages.tweet); });
if (tweets.length>0){
$scope.moreTweets = true;
Array.prototype.unshift.apply(allTweets, tweets);
$scope.payload = body.next_request;
}
}
}
The Load More Tweets button shows on initial load. After that, whenever allTweets is updated the $scope.tweets gets updated as well before button is clicked.
Thanks to Eylen I understand the behavior a little better now.
Changed the assignment to a push after resetting array:
in loadMoreTweets: