AngularJS merge Arrays for ng-repeat



我把我的帖子保存在一个.json文件中。我对每个帖子的喜欢都保存在另一个连接到我的数据库的php文件中。

a.likesA = [];
$http({
method: 'GET',
url: 'data/get_likes.php'
}).then(function(response) {
a.likesA = response.data;
console.log(response.data);
}, function(error) {
console.log("Likes konnten nicht geladen werden: " + error.status + error.statusText);
});

a.labs = []; //declare an empty array
$http({
method: 'GET',
url: 'data/lab.json'
}).then(function(response) {
a.labs = response.data;
//console.log(response.data.length);
}, function(error) {
console.log("JSON konnte nicht geladen werden: " + error.status + error.statusText);
});

我想用相应的类似编号显示每个帖子。

我试过这个:ng-repeat="lab in combined = labs.concat(likesA)但后来我得到了 6 个 ng 重复而不是 3 个。(我目前在我的 .json 中有 3 个帖子(

为什么你不能这样做。使用实验室的$index属性获取相应点赞数的位置。

// <body ng-app='myApp' binds to the app being created below.
var app = angular.module('myApp', []);
// Register MyController object to this app
app.controller('MyController', ['$scope', MyController]);    
// We define a simple controller constructor.
function MyController($scope) {
$scope.likes=[5,4,3,2,1];
$scope.labs = ['5', '4', '3', '2', '1'];
}
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<div ng-controller='MyController' ng-app='myApp'>
<div ng-repeat="lab in labs">
<div>Lab Index: {{lab}}</div>
<div>Number of likes:{{likes[$index]}}</div>
<br>
<br>
</div>
</div>

尝试这样,Object.assign将合并数组或对象

var combined = Object.assign([], labs, likesA);
ng-repeat="lab in combined"

最新更新