0

I am using ngRepeat and ngIf to filter/sort(?) some data. I originally considered using ngSwitch instead of ngIf for this, but couldn't find a good example. After fumbling around with the slightly more complex ngSwitch, I decided to give it a go with ngIf. It only took about 5 minutes to figure out how to implement what I wanted with ngIf, so that's a big plus! However, I am needing to use ngRepeat and ngIf twice to achieve my desired output. I would like to get it down to one ngRepeat if possible, since I think that is the more expensive directive.

The main html is as follows:

<body ng-app="app">
    <div ng-controller="Controller2 as ctrl2">
        <h4>City1</h4>
        <div ng-repeat="place in ctrl2.places">
            <div ng-if="place.city1 === true">
                {{place.name}}
            </div>
        </div>
        <h4>City2</h4>
        <div ng-repeat="place in ctrl2.places">
            <div ng-if="place.city1 === false">
                {{place.name}}
            </div>
        </div>
    </div>
</body>

The output looks like:

City1

Place1
Place3

City2

Place2

You can see that I am using a boolean property for each element of the places variable. I can provide more code if needed.

Is there a way to get the desired output without using two ng-repeat directives? Would ngSwitch be better than ngIf?

EDIT:

Controller code:

(function() {

    'use strict';

    angular
        .module('app')
        .controller('Controller2', Controller2);

    function Controller2() {

        this.places = places;
    }

    var places = [
        {
            name: 'Place1',
            city1: true,
        },
        {
            name: 'Place2',
            city1: false,
        },
        {
            name: 'Place3',
            city1: true,
        }
    ];
})();
UltraSonja
  • 881
  • 1
  • 20
  • 33

1 Answers1

2

You could use filters in your ng-repeats and get rid of the ng-ifs:

<div ng-controller="Controller2 as ctrl2">
    <h4>City1</h4>
    <div ng-repeat="place in ctrl2.places | filter: {city1: true}">        
        {{place.name}}
    </div>
    <h4>City2</h4>
    <div ng-repeat="place in ctrl2.places | filter: {city1: false}">        
        {{place.name}}        
    </div>
</div>
yvesmancera
  • 2,915
  • 5
  • 24
  • 33