[英]angularjs: resolve value from key pair
有沒有一種簡單的方法可以在數組中找到鍵並返回它的值而不是使用angularjs返回鍵(可能是通過使用表達式)?
現在,我做這樣的事情:
vm.topics = [{id:1,value:"a"} , {id:2,value:"b"} , {id:3,value:"c"}];
vm.tickets= [{topic:2,summary:"summary 1"} , {topic:1,summary:"summary 2"}];
vm.getTopicName = function (id) {
for (int t=0 ; t<vm.topics.length ; t++)
if (vm.topics[t].id == id)
return vm.topics[t].value;
return id;
};
並在html部分:
<tr data-ng-repeat="item in vm.tickets">
<td>{{vm.getTopicName(item.topic)}}</td>
<td>{{item.summary}}</td>
</tr>
有什么像
<td>{{item.topic | id as value in vm.topics}}</td>
有趣的例子,但我認為這說明了重點。
-更新-
正如@jantimon在評論中提到的那樣,一種方法是將列表更改為真實密鑰對的對象並簡化所有操作:
vm.topics1 = {};
for (var i=0; i < vm.topics.length; i++) {
var t = vm.topics[i];
vm.topics1[t.id] = t.value;
}
HTML只需更改為:
<td>{{vm.topics1(item.topic)}}</td>
實際上,您使用了兩個不同的數組,並且從您的注釋(ajax調用)中,我將在Service中創建一個合並 topics
和tickets
新數組,例如:
[... ,
{
topic:2,
summary:"summary 1",
ticket_value: "b"
},
... ]
因此,控制器應該只繪制它(沒有其他邏輯)。 這種方式將減少ng-repeat
循環中的觀察者,並且您無需調用(重建) getTopicName()
我認為這是正確的方法,
為了簡化您的示例,如果您使用Underscorejs庫,則可以編寫:
<td>{{topics[_.findIndex(topics, {id: item.topic})].value}}</td>
小提琴演示
HTML
<div data-ng-repeat="item in tickets">
<td>{{topics[_.findIndex(topics, {id: item.topic})].value}} </td>
</div>
JS
$scope._ = _;
$scope.topics = [{id:1,value:"a"} , {id:2,value:"b"} , {id:3,value:"c"}];
$scope.tickets = [{topic:2,summary:"summary 1"} , {topic:1,summary:"summary 2"}];
**作為旁注,請嘗試避免從HTML調用方法,例如:
<td>{{vm.getTopicName(item.topic)}}</td>
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.