angular load more tweets onclick

174 views Asked by At

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.

2

There are 2 answers

0
septemberbrain On

Thanks to Eylen I understand the behavior a little better now.

Changed the assignment to a push after resetting array:

in loadMoreTweets:

   $scope.tweets = [];  
   Array.prototype.push.apply($scope.tweets, allTweets);
0
Eylen On

That's the expected behaviour. You are assigning $scope.allTweets to $scope.tweets thus creating a reference to that array. This means that when a change is made to either $scope.allTweets or $scope.tweets, the change will be made to the same object pointed by this two variables.

if you want a subset of allTweets you should push or create a new array just with them