如何迭代两组数据并匹配angularjs中的值

时间:2017-02-22 03:49:45

标签: angularjs ng-repeat

以角度迭代这样的数据集以获得每个城市中有多少人的数量的最有效方法是什么?

app.factory('Person', function($resource) {
  return $resource('/api/person/:id', {id: '@_id'});
});

app.controller('MainCtrl', ['$scope', 'Person', function($scope, Person) {
  $scope.cities = ['Seattle', 'Phoenix', 'Las Vegas', 'Dallas', 'Chicago'];

  $scope.getCount = function(city) {
    Person.query({location: city}, function(data) {
      return data.length;
    });
  };
}]);

显示每个城市的人数

<ul>
  <li ng-repeat="city in cities">{{ city }}: {{ getCount(city) }}</li>
</ul>

2 个答案:

答案 0 :(得分:1)

试试这个

<ul>
  <li ng-repeat="city in cities">{{ city }}: {{ getCount(city) }}</li>
</ul>

在控制器中

  $scope.getCount = function(city){
      $scope.people = People.query();//you can pass city name here
      return $scope.people.length;
  }

答案 1 :(得分:0)

我能够通过在我的控制器中使用angular.forEach来解决无限的摘要错误,如下所示:

angular.forEach($scope.cities, function(city) {
    Student.query({city: city}, function(data) {
        $scope.count[city] = data.length;
    });
});

这仍然需要每个城市一次点击API,我不知道是否有更好的方法来做到这一点。

我将就这个问题提出一个单独的问题。