简体   繁体   中英

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)?

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:

<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:

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:

<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:

[... ,
 {
  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()

This is a right way I think,


To simplify your example, if you use Underscorejs library, you can write:

 <td>{{topics[_.findIndex(topics, {id: item.topic})].value}}</td>

Demo in Fiddle

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"}];

**As a side note, try to avoid calling methods from HTML like:

<td>{{vm.getTopicName(item.topic)}}</td>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM