Search code examples
javascriptangularjsangularjs-ng-repeatng-switch

AngularJs. Render table with ng repeat and ng switch


I'm trying render table with two columns using angularjs directives.

<table>
<tr ng-repeat="message in messages" >
    <td ng-switch-on="message.network" ng-switch when="twitter" ng-controller="TweetController">
        <span>
            <input type="checkbox" name="active" ng-checked="{{message.isPublished}}" data-id="{{message.socialId}}" ng-click="publishMessage($event)" />
        </span>
        <span>
            <img src="{{message.authorPicture}}" />
        </span>
        <span>{{message.createdAt}}</span>
        <span>{{message.network}}</span>
        <span>{{message.text}}</span>
    </td>
    <td ng-switch-on="message.network" ng-switch when="facebook" ng-controller="FacebookController">
        <span>
            <input type="checkbox" name="active" ng-checked="{{message.isPublished}}" data-id="{{message.socialId}}" data-createdAt="{{message.createdAt}}" ng-click="publishMessage($event)" />
        </span>
        <span>
            <img src="{{message.authorPicture}}" />
        </span>
        <span>{{message.createdAt}}</span>
        <span>{{message.network}}</span>
        <span>{{message.text}}</span>
    </td>
</tr>
</table>

There are should be 2 columns - in first should be twitter messages, in second should be facebook posts. But in my case the same message renders in both columns(Like this http://puu.sh/5oHT7.png). What i'm doing wrong ?


Solution

  • To keep things simple just restructure the model:

    $scope.messages = [
        [
            {
                "network": "twitter",
                ...
            },
            {
                "network": "facebook",
                ...
            }
        ],
        [
            {
                "network": "twitter",
                ...
            },
            {
                "network": "facebook",
                ...
            }
        ]       
    ]
    

    HTML:

    <table>
        <tr ng-repeat="message in messages" >
            <td ng-repeat="msg in message">
                <div ng-if="msg.network == 'twitter'">
                    <div ng-controller="TweetController">
                        ...
                        <span>{{msg.createdAt}}</span>
                        <span>{{msg.network}}</span>
                        <span>{{msg.text}}</span>
                    </div>
                </div>
                <div ng-if="msg.network == 'facebook'">
                    <div ng-controller="FacebookController">
                        ...
                        <span>{{msg.createdAt}}</span>
                        <span>{{msg.network}}</span>
                        <span>{{msg.text}}</span>
                    </div>
                </div>
            </td>       
        </tr>
    </table>