0

I've defined two collections in Angular:

app.controller('MainCtrl', function($scope, PieceService, TeamService) {
  PieceService.query(function(data){
    $scope.pieces = data;
  });
  TeamService.query(function(data){
    $scope.teams = data;
  });
});

pieces is a collection that looks like this: [{name:'Petra',team_id:2},{name:'Jan',team_id:3}] team is a collection that looks like this: [{name:'TeamA',id:2},{name:'Team',id:3}]

In the template I am iterating over the pieces collection:

<tr data-ng-repeat="piece in pieces">

How can I print the teamname of each piece?

I've tried creating a filter that does this, but as I don't see how I can access the scope in a filter I'm without luck so far.

4

2 回答 2

1

不确定这是否是最性感的角度方式,但我会在你的控制器中创建一个函数来进行查找。我还决定缓存 team_id 以进行名称查找,但我意识到这对于 2x2 搜索并不是必需的。

var app = angular.module('plunker', []);

app.controller('MainCtrl', function($scope) {
    $scope.pieces = [{name:'Petra',team_id:2},{name:'Jan',team_id:3}];
    $scope.teams = [{name:'TeamA',id:2},{name:'TeamB',id:3}];

    var idcache = {};

    $scope.getTeam = function(id) {
      if(idcache[id]) {
        return idcache[id];
      } 

      //cache this
      $scope.teams.forEach(function(team) {
        idcache[team.id] = team.name;
      });

      return idcache[id];

    }        
});

我用示例代码创建了一个 plunkr。 http://plnkr.co/edit/DsafIfMfARurNeVcl9Qd?p=preview

于 2013-06-02T22:40:05.827 回答
1

使用团队 ID 作为对象键,如下所示:

$scope.teamLookup = {}

// do this in the query callback
angular.forEach($scope.teams, function(val, key){
    $scope.teamLookup[val.id] = val.name
});

然后,您的标记可能如下所示:

<tr data-ng-repeat="piece in pieces">
    <td>{{teamLookup[piece.team_id]}}</td>
    <td>{{piece.name}}</td>
</tr>
于 2013-06-02T22:58:09.737 回答