0

I'm looking to filter the following list with AngularJS by both category and location. The difficulty I'm having is being able to properly nest the results beneath their respective categories (see below) after the filtering has occurred.

var jobs = [
    {
        title: "Software Engineer",
        category: "Engineering",
        location: "New York"
    },
    {
        title: "Web Developer",
        category: "Engineering",
        location: "Chicago"
    },
    {
        title: "UX Designer",
        category: "Design",
        location: "New York"
    }
]

This is the desired output (also note the alphabetically ordered categories):

Design
UX Designer

Engineering
Software Engineer
Web Developer

Any help would be much appreciated. Thanks!

Steven G.
  • 3
  • 3

3 Answers3

0

Do you have something like this in your mind:

  <b>Design</b>
  <ul>
      <li ng-repeat="job in jobs | filter: { category:'Design'}">
        {{job.title}}
      </li>
  </ul>
  <b>Engineering</b>
  <ul>
      <li ng-repeat="job in jobs | filter: { category:'Engineering'}">
        {{job.title}}
      </li>
  </ul>

There is working JSFiddle.

PrimosK
  • 13,848
  • 10
  • 60
  • 78
  • I've, thought of something like this, but I don't want to need additional markup for every new category that gets added. – Steven G. Mar 14 '14 at 13:45
  • Then I would suggest making set of categories and iterate trough them with the use of `ng-repeat`. – PrimosK Mar 14 '14 at 13:51
0

I would re-structure my JSON as follows:

  $scope.parsedJobs = [];
  angular.forEach($scope.jobs, function(value, key) {
    var j = $scope.parsedJobs.filter(function(element) {
      return element.category == value.category;
    });
    if (j.length > 0) {
      $scope.parsedJobs[0].elements.push({
        title: value.title, 
        location: value.location
      });
    } else {
      $scope.parsedJobs.push({
        category: value.category,
        elements: [{
          title: value.title, 
          location: value.location
        }]
      });
    }
  });

Fiddle

Beterraba
  • 6,515
  • 1
  • 26
  • 33
0

Here is a working example with your data on plnkr using the filter solution from AngularJS Group By Directive without External Dependencies:

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

Community
  • 1
  • 1
chr1s1202
  • 477
  • 2
  • 8
  • Exactly, what I needed - thanks a million! Do you know if this will create any limitations with filtering the list? – Steven G. Mar 14 '14 at 14:14
  • No there are no limitations with filter. Updated the plnkr with applied filter "New York" on location. `
    `
    – chr1s1202 Mar 14 '14 at 14:25