* ngIf中的呼叫功能

时间:2017-08-21 05:28:51

标签: angularjs angular-ng-if

我有这种情况,我想调用一个函数来显示正确的html标记。这是我目前的代码:

<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>

我想将所有ngif组合成一个名为“showField(name)”的函数,该函数将检查并返回正确的html标记。怎么可能这样呢?我的最终html标记看起来应该是这样的:

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

2 个答案:

答案 0 :(得分:3)

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";
}

答案 1 :(得分:0)

你想要实现的是正确的方法,只需在控制器中声明方法并返回布尔值

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