我有来自2个不同控制器的2个(数组)对象。
对象1(名称控制器1):
[{id:1,"name":"jakov"},...]
对象2(昵称控制器2):
[{id:1, "nickname" : "jandric", "nameId" :1, "title" : "master"},...]
我通过服务从控制器1广播对象:
$http.get('names/').success(function(data) {
sharedService.broadcastItem(data);
});
我在Controller 2中处理广播对象:
$scope.$on('handleBroadcast', function() {
$scope.names= sharedService.message;
});
控制器2也有GET请求:
$http.get('nicknames/').success(function (data) {
$scope.nicknames = data;
});
我有简单的表格,我想要显示:nicknameId,昵称,名称和标题。
这样的事情:
<div ng-controller="Nickname">
<table>
<tr>
<th>nicknameId</th>
<th>nickname</th>
<th>name</th>
<th>title</th>
</tr>
<tr ng-repeat="nick in nicknames">
<td>{{nick.id}}</td>
<td>{{nick.nickname}}</td>
<td ng-controller="Name">{{??????}}</td> //GET name request trigger
<td>{{nick.title}}</td>
</tr>
</table>
</div>
如何从第一个对象获取名称,对于给定的nameId,在第二个对象中获取名称?
Plz帮助:D
更新
我设法用html这样做:
<div ng-controller="Nickname">
<table>
<tr>
<th>nicknameId</th>
<th>nickname</th>
<th>name</th>
<th>title</th>
</tr>
<tr ng-repeat="nick in nicknames">
<td>{{nick.id}}</td>
<td>{{nick.nickname}}</td>
<td ng-controller="Name">
<div ng-repeat="name in names">
<div ng-if="nick.nameId === name.id">
{{name.name}}
</div>
</div>
</td>
<td>{{nick.title}}</td>
</tr>
</table>
</div>
所以我在for循环中使用for循环。有更简单的答案吗?
答案 0 :(得分:2)
我希望我的问题是正确的: 在昵称控制器 $ scope 中创建一个索引,该索引通过id映射到名称:
/**
*
* @param {Array.<obj>} source: The array of objects the index should be created with.
* @param {string} property: The property that shall be used as key for the new index
* @return {object} provides access to all objects by the chosen property
*/
var buildIndex = function(source, property) {
var temp = {};
for(var i = 0, len = source.length; i < len; ++i) {
temp[source[i][property]] = source[i];
}
return temp;
};
然后您可以访问模板中的索引:
<div ng-controller="Nickname">
<table>
<tr>
<th>nicknameId</th>
<th>nickname</th>
<th>name</th>
<th>title</th>
</tr>
<tr ng-repeat="nick in nicknames">
<td>{{nick.id}}</td>
<td>{{nick.nickname}}</td>
<td>{{index[nick.id].name}}</td>
<td>{{nick.title}}</td>
</tr>
</table>
答案 1 :(得分:0)
试试这个
<div ng-controller="Nickname">
<table>
<tr>
<th>nicknameId</th>
<th>nickname</th>
<th>name</th>
<th>title</th>
</tr>
<tr ng-repeat="nick in nicknames">
<td>{{nick.id}}</td>
<td>{{nick.nickname}}</td>
<td ng-controller="Name">
<span ng-reapeat="n in names">
<span ng-if="nick.nameId == n.id">{{n.name}}</span>
</span>
</td> //GET name request trigger
<td>{{nick.title}}</td>
</tr>
</table>
</div>