user3483385
user3483385

Reputation: 31

AngularJS ng-switch rendering order

I have a question about ng-switch rendering order.

Code(HTML):

<div ng-controller="testCtrl">
<button ng-click="v1 = !v1">toggle v1</button>
<table class="table table-bordered">
    <tbody>
        <tr ng-switch on="v1">
            <th ng-switch-when="true">V1</th>
            <th ng-repeat="item in datas">{{item}}</th>
        </tr>
    </tbody>
</table>

Code(Javascript):

var myApp = angular.module('myApp',[]);
function testCtrl($scope) {
    $scope.datas = ['A', 'B'];
}

I expected a result by the order :

V1 A B

But instead, the output shows ng-repeat items first, followed by ng-switch-when statement.

Why's that?

Is there an alternative solution to do such thing in my expected order?

JSFiddle sample here.

============================

Update (2014/04/02) :

Here's the explanation for why ng-show is not an option.

I write a directive table like this :

<table class="table table-bordered">
    <thead>
        <tr>
            <th ng-show="checkbox"><input type="checkbox" /></th>
            <th ng-repeat="col in columns">{{col.text}}</th>
        </td>
    </thead>
    <!-- body is ignored -->
</table>

The checkbox variable is for controlling whether the checkbox input should be showed.

This works fine until I apply JQuery ColResize.

When the checkbox variable is false, the ng-show hides the first th element.

And somehow the hidden th element causes JQuery ColResize to malfunction.

Therefore ng-show is not suitable for this situation.

========================

Current Solution :

My current solution is using ng-switch to separate two table element.

And use one variable to decide which table to draw.

Like this :

<div ng-switch on="checkbox">
    <table ng-switch-when="true">
        <tr>
            <th><input type="checkbox" /></th>
            <th ng-repeat="col in columns">{{col.text}}</th>
        </tr>
        <!-- body is ignored -->
    </table>
    <table ng-switch-default>
        <tr>
            <th ng-repeat="col in columns">{{col.text}}</th>
        </tr>
        <!-- body is ignored -->
    </table>
</div>

Although this solve the problem, it is not a good solution.

But until I find an alternative solution.

I think I will have to settle for this.

Upvotes: 3

Views: 933

Answers (1)

dmahapatro
dmahapatro

Reputation: 50245

You can use ng-show instead of ng-switch as shown in this modified JSFIDDLE

<tr>
    <th ng-show="v1">V1</th>
    <th ng-repeat="item in datas">{{item}}</th>
</tr>

ng-show applies style around the DOM element where the directive is used to show/hide respectively. In your case the header is compiled appropriately but will only be shown based on the condition that is provided to ng-show.

Upvotes: 1

Related Questions