loveprogramming
loveprogramming

Reputation: 578

Call function in *ngIf

I have this situation where I want to call a function to display the correct html mark up. Here is my current code:

<li ng-repeat="data in myBlock.myData">
    <div ng-if="data.type=='Jonh'">
       <div class='row'>
          <div class='col'>
           this is text for Jonh
          </div>
      </div>
    </div>
    <div ng-if="data.type=='Roy'">
      <div class='row'>
         <div class='col'>
           Roy will have a different text
        </div>
      </div>
    </div>
    <div ng-if="data.type=='Kevin'" > 
       <div class='row'>
          <div class='col'>
            Kevin text is also different
          </div>
       </div>
    </div>
</li>

I would like to combine all the ngif into a function called "showField(name)" that will check and return the right html mark up. How could that be done? My final html mark up should look something like this:

<li ng-repeat="data in myBlock.myData">
   <div *ngIf="showField(data.type)">
      //Not sure how to implement this part
   </div>                       
</li>

Upvotes: 4

Views: 59680

Answers (2)

Sachet Gupta
Sachet Gupta

Reputation: 837

HTML:

<li ng-repeat="data in myBlock.myData">
   <div ng-if="checkValidDataType(data.type)">
       <div class='row'>
          <div class='col'>
             <label class='title' for="{{data.name}}">{{data.label}}</label>
             <span class="{{data.type.toLowerCase() + 'Class'}}">This is {{data.type}}</span>                 
          </div>
      </div>
   </div>                       
</li>

JS:

$scope.checkValidDataType = function(type) {
    return type === "Roy" || type === "Kevin" || type === "Jonh";
}

Upvotes: 4

Sajeetharan
Sajeetharan

Reputation: 222582

What you are trying to achieve is right way, just declare the method inside a controller and return boolean value

$scope.showField = function(yourdata){
   //put the logic
   return true/false;
}

Upvotes: 1

Related Questions