dragonmnl
dragonmnl

Reputation: 15538

ng-repeat + ng-switch: how to use correctly?

Premise: I've seen several similar questions. But I can't really figure out how to solve my doubt.

I have an array of objects:

$scope.messages = [obj1, obj2, ...];

where each object has the following structure:

{
   id: <int>,
   printOnlyFirst: <boolean>,
   text1: <string>,
   text2: <string>
}

where text1 / text2 are conditionally printed (in real time through track by) according to printOnlyFirst.

<div id="container">
    <div ng-switch="printOnlyFirst" ng-repeat="message in messages track by message.id">
        <div ng-switch-when="true" class="text1"> <!-- case 1 -->
            {{message.text1}
        </div>
        <div ng-switch-when="false" class="text2"> <!-- case 2 -->
            {{message.text2}
        </div>
    </div>
</div>

I think this code is fine.

However I noticed that

<div ng-switch="printOnlyFirst" ng-repeat="message in messages track by message.id">

is printed for each single element of the ng-repeat loop, together with it's content (either case 1 or 2).

Is this normal? Is there a better solution to avoid such DOM overhead?

Upvotes: 0

Views: 1266

Answers (1)

sp00m
sp00m

Reputation: 48807

From https://docs.angularjs.org/api/ng/service/$compile#-priority-:

Directives with greater numerical priority are compiled first.

ngSwitch executes at priority 1200 while ngRepeat executes at priority 1000, which isn't the order you need.

You'll have to use a nested component (a div for example):

<div id="container">
    <div ng-repeat="message in messages track by message.id">
        <div ng-switch="message.printOnlyFirst">
            <div ng-switch-when="true" class="text1"> <!-- case 1 -->
                {{message.text1}
            </div>
            <div ng-switch-when="false" class="text2"> <!-- case 2 -->
                {{message.text2}
            </div>
        </div>
    </div>
</div>

Don't forget to switch on message.printOnlyFirst rather than printOnlyFirst.

Upvotes: 1

Related Questions