1

I have an array of restaurant objects and I want to list them by grouping their cities

My object is like;

restaurant = {
     id: 'id',
     name: 'name',
     city: 'city'
}

This HTML Markup can give some info about what I want to do.

 <div ng-repeat="restaurant in restaurant | filter: ???">
        <div class="header">
            <h1 ng-bind="restaurant.city"></h1>
            <a>Select All</a>
        </div>
        <div class="clearfix" ng-repeat="???">
            <input type="checkbox" id="restaurant.id" />
            <label ng-bind="restaurant.name"></label>
        </div>
    </div>

Can I do it with one single array or do i need to create seperate city and restaurant arrays to do it?

2
  • Do you want to group your array of restaurants by city? Commented Oct 14, 2014 at 13:27
  • Yeah this is exactly what I want to do =) Commented Oct 14, 2014 at 13:31

1 Answer 1

3

If you want to group restaurants by city, you can use groupBy of angular.filter module.

Just add the JS file from here: http://www.cdnjs.com/libraries/angular-filter to your project and use following code.

var myApp = angular.module('myApp',['angular.filter']);

function MyCtrl($scope) {    
    $scope.restaurants = [
       {id: 1, name: 'RestA', city: 'CityA'},
       {id: 2, name: 'RestB', city: 'CityA'},
       {id: 3, name: 'RestC', city: 'CityC'},
       {id: 4, name: 'RestD', city: 'CityD'}
    ];
}

<div ng-controller="MyCtrl">
    <ul ng-repeat="(key, value) in restaurants | groupBy: 'city'">
        <b>{{ key }}</b>
      <li ng-repeat="restaurant in value">
          <i>restaurant: {{ restaurant.name }} </i>
      </li>
    </ul>
</div>

I've created JSFiddle for you with working example.

Sign up to request clarification or add additional context in comments.

1 Comment

perfect. Works just as expected

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.