Search code examples
angularjsangularjs-ng-repeatangular-filters

Angular Filter Removes HTML When Filtering


I've created an angular filter that filters a list of contacts from a json objects based on the group button that is clicked. The filter works however, when you click the group button it removes the html for the buttons that are not the current group button being filtered on.

For example, in the plunkr below, if you click on personal it filters for all the contacts w the group name "Personal" but then removes all the other group buttons.

http://plnkr.co/edit/B3g075?p=preview

Can someone explain why the angular filter removes the html? Is it because I have the group buttons as an ng-repeat?

   $scope.groups = [
{
    name: "Personal",
    contacts: [
      {
        "firstName": "Person",
        "lastName": "One",
        "mobile": "519-555-5555",
        "home": "519-999-9999",
        "email": "person@example.com",
        "company": "blah Incorporated"
      }
    ]
  },
  {
   name: "Family",
    contacts: [
      {
        "firstName": "Person",
        "lastName": "Two",
        "mobile": "519-555-5555",
        "home": "519-999-9999",
        "email": "person@example.com",
        "company": "blah Incorporated"
       }
    ]
  },

 $scope.filter = function (name) {
  console.log("group.name = "  + name);
    $scope.groups = $filter('filter')($scope.groups, {'name': name});
};


<div class="row">
<div class="col-md-3">
  <!-- Groups Section -->
  <div class="group-list">
    <h4>All Contacts</h4>
    <div class="list-group scrolls">
      <a href="javascript:void(0);" ng-model="all" ng-click="filter('All')" class="list-group-item btn-hover">All Contacts 
        <span class="onHover pull-right"><i class="fa fa-times"></i></span>
      </a>
      <a href="javascript:void(0);" ng-repeat="group in groups" ng-click="filter(group.name)"class="list-group-item btn-hover">{{group.name}}
        <span ng-click="deleteGroup()" class="onHover pull-right"><i class="fa fa-times"></i></span>
      </a>
    </div>
    <div class="group-list-bottom">
      <button class="btn btn-default"><i class="fa fa-plus"></i> New Group</button>
    </div>
  </div>
</div>

Solution

  • You use $scope.groups to populate both the group buttons and the contacts. So when you apply your filter it has effect on both.

    Break it up in two separate arrays, one for the buttons and one for the contacts.