Angularjs ng-switch

时间:2014-03-21 15:01:10

标签: angularjs if-statement

在我的angularjs应用程序循环中,我尝试验证一些json字段和检索值的函数在表行中显示主题或忽略它。我一直在阅读关于ngswitch但我不知道如何正确使用它。这是我试过的

<div ng-repeat="product in products">
<table>
<div ng-switch="product.display_res">{{product.display_res}}</div>
     <div ng-switch on="isExists(product)">
      <span ng-show="isExists(product)"> 
          <tr><th>Display</th> <td>{{product.display_res}}</td></tr></span>
      <span ng-show="!isExists(product)"></span>
     </div>
</table>

</div>

2 个答案:

答案 0 :(得分:0)

我认为你会更好地理解。

<div ng-switch on="product">
  <span ng-switch-when="Apple">Apple<span>
  <span ng-switch-when="Banana">Banana</span>
  <span ng-switch-default>Default</span>
</div>
// ngSwitch is eval base on expression == "something"
// if product == "Apple" then span Apple will render
// if product == "Banana" then span Apple will render
// you don't need ngShow to work with ngSwitch
// product is $scope.product in your controller


<span ng-if="isExists(product)">
// this will be render if function isExists(product) return true


<span ng-show="isExists(product)">
// ngShow will show the span if function isExists(product) return true
// the span is always render, so it is different from ngIf ngSwitch

答案 1 :(得分:0)

您应该使用angular API查看其工作原理。

如果我理解你要做什么,这是正确的版本。

根据评论进行编辑

    <div ng-repeat="product in products">
    <table>
      <div ng-if="product.display_res && isExists(product)">{{product.display_res}}</div> <!-- Show if product.display_res have a value (exept false or null) and product exist -->
         <div>
              <tr><th>Display<th></tr>
              <tr><td>{{product.display_res}}</td></tr>
         </div>
       </div>
    </table>

</div>