xrcwrn
xrcwrn

Reputation: 5327

How to append json objects below exixting data in angularjs

as html page

 <div class="posts" ng-repeat="s in news" ng-init="moreNews()">
      {{s.news}}
 </div>
 <input type="button" value="get data" onclick="moreNews()"/>

at controller

$scope.moreNews = function () {
       $http.get("test?p=" + $scope.pno)
                .then(function (response) {
                    console.log(response);
                    $scope.news = response.data.news;
                    $scope.pno++;
                  }, function (data) {
                    alert("Oops! Unable to get data from server")
                });
    };

Here I am getting data from server and showing to html page. Here first response is showin data properly. but for second response it is overriding the data I want to add next data to below the first one and so one.

How to append lists below the existing data?

Upvotes: 0

Views: 38

Answers (3)

Dilushika Weerawardhana
Dilushika Weerawardhana

Reputation: 1611

$scope.news = [];

$scope.moreNews = function () {
   $http.get("test?p=" + $scope.pno)
            .then(function (response) {
                $scope.news.push(response.data.news);
                $scope.pno++;
              }, function (data) {
                alert("Oops! Unable to get data from server")
            });
};

The push() method - Adds one or more elements to the end of the same array.

Upvotes: 1

manish kumar
manish kumar

Reputation: 4692

Try out this code

$scope.moreNews = function () {
       $http.get("test?p=" + $scope.pno)
                .then(function (response) {
                    console.log(response);
                    $scope.news=$scope.news.concat(response.data.news);
                    $scope.pno++;
                  }, function (data) {
                    alert("Oops! Unable to get data from server")
                });
    };

Upvotes: 2

Chatar Singh
Chatar Singh

Reputation: 1063

$scope.moreNews = function () {
       $http.get("test?p=" + $scope.pno)
                .then(function (response) {
                    console.log(response);
                    for(var i=0;i<response.data.news.length;i++){
                      $scope.news.push(response.data.news[i]);
                    }                    
                    $scope.pno++;
                  }, function (data) {
                    alert("Oops! Unable to get data from server")
                });
    };

Upvotes: 3

Related Questions