d4rty
d4rty

Reputation: 4178

AngularJS if-then-else construction with nested expressions

I create dynamically a table and I want the two buttons in the last table cell of each row only if x.deviceID==="-" evaluates to false.

<tr class="contentRow" id="tableRow{{x.deviceID}}" ng-repeat="x in deviceData| filter:search">
  <td>{{x.deviceID}}</td>
  <td>{{x.otherID}}</td>
  <td>{{x.aaaa}}</td>
  <td>
    //this two buttons should only be there if x.deviceID==="-"
    <button type="button" class="btn btn-xs btn-default" data-deviceid="{{x.deviceID}}">
      <span class="glyphicon glyphicon-info-sign"></span>a
    </button>

    <button type="button" class="btn btn-primary btn-xs" data-deviceid="{{x.deviceID}}">
      <span class="glyphicon glyphicon-info-sign"></span>b
    </button>
  </td>
</tr>

My first approach was:

<td>{{x.deviceID}}</td>
<td>{{x.otherID}}</td>
<td>{{x.lastGpsDate}}</td>
<td>{{x.deviceID==="-" ? : '<button type"button" class="btn btn-xs btn-default" data-deviceid="{{x.deviceID}}"><span class="glyphicon glyphicon-info-sign"></span>a.....'}}

but this won't work. The last cell of the row will always look like this {{x.deviceID==="---"? : ' BUTTON BUTTON'}}. BUTTON is a real html button, not a string!

Upvotes: 0

Views: 38

Answers (2)

Keyur
Keyur

Reputation: 1

Wrap both inside a div and use ng-if or ng-hide to solve the problem

<tr class="contentRow" id="tableRow{{x.deviceID}}" ng-repeat="x in deviceData| filter:search">
  <td>{{x.deviceID}}</td>
  <td>{{x.otherID}}</td>
  <td>{{x.aaaa}}</td>
  <td>
      <div ng-if="x.deviceID === '-'">
          //this two buttons should only be there if x.deviceID==="-"
          <button type="button" class="btn btn-xs btn-default" data-deviceid="{{x.deviceID}}">
          <span class="glyphicon glyphicon-info-sign"></span>a
          </button>

          <button type="button" class="btn btn-primary btn-xs" data-deviceid="{{x.deviceID}}">
          <span class="glyphicon glyphicon-info-sign"></span>b
          </button>
      </div>
  </td>
</tr>

You could also use ng-hide with the same condition as well. ng-if removes it from DOM & ng-hide just sets its display to false, but the buttons would still be in the DOM.

Upvotes: 0

byteC0de
byteC0de

Reputation: 5273

Use ng-if to solve the problem

<button ng-if="x.deviceID == '-'" type="button" class="btn btn-xs btn-default" data-deviceid="{{x.deviceID}}">
      <span class="glyphicon glyphicon-info-sign"></span>a
</button>

Upvotes: 3

Related Questions