说我有以下JSON文件
{
"A": [
{"name": "foo",
"BRef": "123"
},
{"name": "Hello",
"BRef": "456"
}
],
"B": [
{"ID": "123",
"lastName": "bar"
},
{
"ID": "456",
"lastName": "World"
}
]
}
我已通过控制器链接模型和视图
$http.get('js/data.json')
.success(function(data) {
$scope.A = data.A;
$scope.B = data.B;
如何循环浏览A并从B中挖出姓氏?
<div ng-repeat="a in A">
<h1>{{a.name}} {{ <<(B.b.ID == a.BRef).lastname>> }}</h1>
</div>
认为带有过滤器的ng-repeat
B可以做到这一点..但我不熟悉角度过滤器(还)
答案 0 :(得分:1)
您可以使用getLast名称的函数或使用嵌套的ng-repeat,并使用ng-if指令显示匹配项。
$scope.getLastName = function(BRef){
var lastName = "";
angular.forEach($scope.data.B,function(b){
if(b.ID == BRef)
lastName = b.lastName;
});
return lastName;
}
在您的视图中使用
<div ng-repeat="a in A">
<h1>{{a.name}} <span ng-bind="getLastName(a.BRef)"></span></h1>
</div>
var editer = angular.module('editer', []);
function myCtrl($scope) {
$scope.data = {
"A": [
{"name": "foo",
"BRef": "123"
},
{"name": "Hello",
"BRef": "456"
}
],
"B": [
{"ID": "123",
"lastName": "bar"
},
{
"ID": "456",
"lastName": "World"
}
]
}
$scope.getLastName = function(BRef){
var lastName = "";
angular.forEach($scope.data.B,function(b){
if(b.ID == BRef)
lastName = b.lastName;
});
return lastName;
}
}
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<div ng-app="editer" ng-controller="myCtrl" class="container">
<div ng-repeat="a in data.A">
<h1>{{a.name}} <span ng-bind="getLastName(a.BRef)"></span></h1>
</div>
OR
----------------------------------
<div ng-repeat="a in data.A">
<h1>{{a.name}} <span ng-repeat="b in data.B" ng-if="b.ID == a.BRef">{{b.lastName}}</span></h1>
</div>
</div>
答案 1 :(得分:1)
从删除的帖子中,我实际上找到了一个优雅的解决方案,将其与ng-show
<div ng-repeat="a in A">
<div ng-repeat="b in B" ng-show="b.ID == a.BRef">
<h1>{{a.name}} {{b.lastname}}</h1>
</div>
</div>
答案 2 :(得分:0)
我认为SSH是对的。
您可以使用javascript的过滤方法,即
$scope.findCorrespondingLastName(bref) {
$scope.B.filter(function(b) {
return b.ID == bref;
});
}
并在您的html文件中使用
<div ng-repeat="a in A">
<h1>{{a.name}} {{findCorrespondingLastName(a.BRef)[0]['lastName']}}</h1>
</div>
还尝试使用controllerAs别名并将变量放在控制器的this
上。根据最新的角度文档,不建议使用$scope
。