hohn doe hohn doe - 22 days ago 5
AngularJS Question

Angular js filter for ng repeat

I have two scopes: users and userGroups.

$scope.user = [
{id: 1, username: 'Vasya1', group_id: 1},
{id: 2, username: 'Vasya2', group_id: 1},
{id: 3, username: 'Vasya3', group_id: 2}
];

$scope.userGroups = [
{id: 1, groupname: 'name1'},
{id: 2, groupname: 'name2'}
];


users.group_id is foreign key for userGroups. I need to make filter for users scope for each group.

<div ng-repeat="(gKey, g) in userGroups">
<div ng-repeat="(uKey, u) in users">
...
</div>
</div>


How can i add filter?

Answer

You could use the angular filters and achieve it.

var app = angular.module("sampleApp", []);

app.controller("sampleController", ["$scope",
  function($scope) {
    $scope.users = [{
      id: 1,
      username: 'Vasya1',
      group_id: 1
    }, {
      id: 2,
      username: 'Vasya2',
      group_id: 1
    }, {
      id: 3,
      username: 'Vasya3',
      group_id: 2
    }];

    $scope.userGroups = [{
      id: 1,
      groupname: 'name1'
    }, {
      id: 2,
      groupname: 'name2'
    }];
  }
]);
.group {
  padding: 10px;
}
.group:nth-child(even) {
  background-color: #cecece;
  color: #212121;
}
.group:nth-child(odd) {
  background-color: #989898;
  color: #dedede;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.5.8/angular.min.js"></script>
<div ng-app="sampleApp">
  <div ng-controller="sampleController">
    <div ng-repeat="group in userGroups" class="group">
      Group Name: {{group.groupname}}
      <div ng-repeat="user in users | filter: { group_id: group.id}">
        User Name: {{user.username}}
      </div>
    </div>
  </div>
</div>