简体   繁体   English

如何从angularjs中的json api获取固定数量的数据

[英]How to get fixed number of data from json api in angularjs

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 . 在上面的例子中我们编写了用于获取记录中所有数据的代码存储在名称中,但要求是前5个数据应该存储在名称中

Thanks in advance 提前致谢

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);
});

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> 

用切片

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM