kliukovking
kliukovking

Reputation: 590

angularjs: ng-repeat using only table tags(tr and td)

I need to make ng-repeat and switch tags depending on object attributes. Only table elements, so I can't put <div ng-repeat> between <tr> and <td>. Like this:

 <tr>
    <td ng-repeat="value in param.values" ng-switch on="value.type">
       <a ng-switch-when="text">{{value.name}}</a>
       <input ng-switch-when="input" type="text" placeholder="{{value.name}}">
       <a ng-switch-when="relocate_here" ng-click="relocate(value.urlTo)">{{value.name}}</a>
    </td>
 </tr>

but without <a> tag. Something like that

<tr>
    <td ng-repeat="value in param.values" ng-switch on="value.type">
       {{value.name}}//if value=="text"
       <input ng-switch-when="input" type="text" placeholder="{{value.name}}">//if value=="input"
       {{value.name}}//like the first one if value=="relocate_here" but <td> must have directive ng-click="relocate(value.urlTo)"
    </td>
 </tr>

Please, give me some advice about that and sorry for my english.

Upvotes: 2

Views: 756

Answers (2)

adashrod
adashrod

Reputation: 476

I believe this accomplishes what you're trying to do without adding any extra nested elements inside the table.

    <tr>
        <td ng-repeat="value in param.values" ng-click="value.type == 'relocate_here' ? relocate(value.urlTo) : null">
            {{value.type == "text" || value.type == "relocate_here" ? value.name : ""}}
            <input ng-if="value.type == 'input'" type="text" placeholder="{{value.name}}">
        </td>
    </tr>

and the data that I used with it:

    $scope.param = {
        values: [{
            type: "text",
            name: "a text value"
        }, {
            type: "input",
            name: "an input value"
        }, {
            type: "relocate_here",
            name: "a url value",
            urlTo: "http://stackoverflow.com"
        }]
    };

The first line inside the <td> prints the name when you need it or empty string otherwise to avoid using an ng-if or ng-switch and having nested elements. The <td> will always have an ng-click attribute, but when not a url type, it will be a no-op.

Upvotes: 0

Anvay
Anvay

Reputation: 345

You can do this by using a ternary operator inside the Angular expression such as the following:

<tr>
    <td ng-repeat="value in param.values" ng-switch on="value.type">
       {{ value.type == "text" ? value.name: "" }}//if value=="text"
       <input ng-switch-when="input" type="text" placeholder="{{value.name}}">//if value=="input"
       {{ value.type == "relocate_here" ? value.name: ""}}//like the first one if value=="relocate_here" but <td> must have directive ng-click="relocate(value.urlTo)"
    </td>
 </tr>

Upvotes: 1

Related Questions