ng-repeat仅显示数组的前2个元素(有25个)。有什么问题?
我是Angular的新手。我迷失了它的原因,在控制台没有错误。有什么建议吗?
<div ng-app="myApp" id="posts" ng-controller="myCtrl as posts">
<li ng-repeat="post in posts" track by $index>
<p>{{posts.data.children[$index].data.ups}}</p>
<p>{{posts.data.children[$index].data.title}}</p>
</li>
</div>
<script>
var app = angular.module('myApp', []);
app.controller('myCtrl', function($scope, $http) {
var vm = this;
vm.mydata = [];
$http.get("http:/www.reddit.com/.json")
.then(function(response) {
vm.mydata = response.data;
$scope.posts = vm.mydata;
//console.log(vm.mydata);
//console.table(vm.mydata);
}, function(response) {
$scope.posts = "Something went wrong";
});
});
</script>
最终代码已更正。这是一个非常基本的脚本,用于管理Reddit首页中的帖子提取,并通过upvotes按降序显示。感谢大家的帮助!请参阅以下代码:
<!DOCTYPE html>
<html>
<!-- _________________________________________________________-->
<!-- Framework: AngularJs -->
<!-- Author: Vanessa Torres -->
<!-- Date: March 30, 2016 -->
<!-- Description: Reddit's Front page posts extraction -->
<!-- _________________________________________________________-->
<script src="http://ajax.googleapis.com/ajax/libs/angularjs/1.4.8/angular.min.js"></script>
<body>
<div ng-app="myApp" id="posts" ng-controller="myCtrl as posts">
<li ng-repeat="post in posts.data.children | orderBy:'-data.ups'" track by $index>
<p>{{post.data.ups}}</p>
<p>{{post.data.title}}</p>
<p>{{post.data.url}}</p>
</li>
</div>
<script>
var app = angular.module('myApp', []);
app.controller('myCtrl', function($scope, $http) {
$scope.posts = [];
$http.get("http:/www.reddit.com/.json")
.then(function(response) {
$scope.posts = response.data;
console.table(vm.mydata);
//
}, function(response) {
$scope.posts = "Something went wrong";
});
});
</script>
</body>
</html>
答案 0 :(得分:4)
因为您正在迭代帖子,它们基本上只有两个属性 ups 和 title
使用:
<li ng-repeat="post in posts.data.children" track by $index>
<p>{{post.data.ups}}</p>
<p>{{post.title}}</p>
</li>
答案 1 :(得分:3)
HTML应如下所示:
<div ng-app="myApp" id="posts" ng-controller="myCtrl as posts">
<li ng-repeat="post in posts track by $index">
<p>{{post.data.children.data.ups}}</p>
<p>{{post.data.children.data.title}}</p>
</li>
</div>
这会在posts
数组内部进行迭代,并显示每个帖子键(ups
和title
)的值。有关使用ng-repeat
的正确格式,请查看track by $index
(https://docs.angularjs.org/api/ng/directive/ngRepeat)的文档。
作为基本编码标准,您无需使用var vm = this;
和$scope
。如果您正在使用vm
变量,那么在内部路由(或内部指令)中,您将每个路由(或指令)与控制器相关联,您可以添加额外的字段controllerAs
以使控制器别名化。在HTML代码中使用此别名来访问vm
变量。在您的示例中,您可以按照以下说明进行更改:
<div ng-app="myApp" id="posts" ng-controller="myCtrl as postsCtrl">
<li ng-repeat="post in postsCtrl.posts track by $index">
<p>{{post.data.children.data.ups}}</p>
<p>{{post.data.children.data.title}}</p>
</li>
</div>
在脚本标签中:
<script>
var app = angular.module('myApp', []);
app.controller('myCtrl', function($http) {
var vm = this;
vm.posts = '';
$http.get("http:/www.reddit.com/.json")
.then(function(response) {
vm.posts = response.data;
}, function(response) {
vm.posts = 'Something went wrong';
});
});
</script>