[英]angularjs: resolve value from key pair
Is there any easy way to find a key in array and return its value instead of the key with angularjs (maybe by using expressions)? 有没有一种简单的方法可以在数组中找到键并返回它的值而不是使用angularjs返回键(可能是通过使用表达式)?
right now, i do something like this: 现在,我做这样的事情:
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;
};
and in html part: 并在html部分:
<tr data-ng-repeat="item in vm.tickets">
<td>{{vm.getTopicName(item.topic)}}</td>
<td>{{item.summary}}</td>
</tr>
Is there anything like 有什么像
<td>{{item.topic | id as value in vm.topics}}</td>
Funny example, but i think it shows the point. 有趣的例子,但我认为这说明了重点。
--- UPDATE --- -更新-
as @jantimon mentioned in comments, one way would be to change list to an object of real key pairs and simplify everything: 正如@jantimon在评论中提到的那样,一种方法是将列表更改为真实密钥对的对象并简化所有操作:
vm.topics1 = {};
for (var i=0; i < vm.topics.length; i++) {
var t = vm.topics[i];
vm.topics1[t.id] = t.value;
}
and HTML simply changes to: HTML只需更改为:
<td>{{vm.topics1(item.topic)}}</td>
Actually you use two different arrays and from your comment (ajax call) I would create new array in Service that merges topics
and tickets
, something like: 实际上,您使用了两个不同的数组,并且从您的注释(ajax调用)中,我将在Service中创建一个合并
topics
和tickets
新数组,例如:
[... ,
{
topic:2,
summary:"summary 1",
ticket_value: "b"
},
... ]
So controller should only draw it (without additional logic). 因此,控制器应该只绘制它(没有其他逻辑)。 This way will reduce watchers from your
ng-repeat
loop and you don't need to call (rebuild) getTopicName()
这种方式将减少
ng-repeat
循环中的观察者,并且您无需调用(重建) getTopicName()
This is a right way I think, 我认为这是正确的方法,
To simplify your example, if you use Underscorejs library, you can write: 为了简化您的示例,如果您使用Underscorejs库,则可以编写:
<td>{{topics[_.findIndex(topics, {id: item.topic})].value}}</td>
HTML HTML
<div data-ng-repeat="item in tickets">
<td>{{topics[_.findIndex(topics, {id: item.topic})].value}} </td>
</div>
JS 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"}];
**As a side note, try to avoid calling methods from HTML like: **作为旁注,请尝试避免从HTML调用方法,例如:
<td>{{vm.getTopicName(item.topic)}}</td>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.