2

See Below Code:

var app = angular.module('myApp', []);
app.controller('customersCtrl', function($scope, $http) {
    $http.get("http://www.w3schools.com/angular/customers.php")
         .then(function (response) {
             $scope.names = response.data.records;
         });
});

In above Example We wrote the code for getting all data in records are stored in names but the requirement is first 5 data should be stored in names.

Thanks in advance

5
  • So will your API always return back the full data and then you need to slice the data and store only the first 5 items? Or are you looking at changing your API? Commented Apr 22, 2016 at 6:23
  • No I don't want to change API. If possible to get 5 data from json api Commented Apr 22, 2016 at 6:27
  • Can you share the json format that you are getting from the API? Is it an Array or Object? Commented Apr 22, 2016 at 6:28
  • w3schools.com/angular/customers.php Commented Apr 22, 2016 at 6:31
  • You can take a look at the answers given below, they should will solve your issue. Commented Apr 22, 2016 at 6:33

3 Answers 3

5

There are two ways to do it -

  1. Make server side changes to get five records only (I think you dont want to use this).
  2. On client side you can use the below code

Sample:

$scope.names=[];
$.each(response.data.records.slice(0,5), function(i, data) {
    $scope.names.push(data);
});
Sign up to request clarification or add additional context in comments.

Comments

3

In this case you can just do slice from response records

$scope.names = response.data.records.slice(0,5);

Sample:

var app = angular.module('myApp', []);
app.controller('customersCtrl', function($scope, $http) {
    $http.get("http://www.w3schools.com/angular/customers.php")
         .then(function (response) {
             $scope.names = response.data.records.slice(0,5);
         });
});
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.5.0/angular.min.js"></script>
<div ng-app="myApp" ng-controller="customersCtrl">
  <pre ng-repeat="name in names">{{$index+1}}: {{name|json}}</pre>
</div>

Comments

0

use slice

$scope.names = response.data.records.slice(0,5);

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.