Search code examples
angularjsangularjs-ng-repeatangular-ng-if

Angularjs repeater inside ul - how to add ng-show without breaking html


Check example below. In this case the 'expensiveFunction' is called for every item in myList

<ul>
   <li ng-show="expensiveFunction(period)" ng-repeat="a in myList">
      <a ng-click="onMove(period)">Move here </a>
   </li>
   <li ng-hide="!canBook">
      <small>No free resources</small>
   </li>
</ul>

Any ideas on how to prevent that?

<ul>
   <!-- Possible, but creates invalid html -->
   <div ng-show="expensiveFunction(period)">
      <li  ng-repeat="a in myList">
         <a ng-click="onMove(period)">Move here </a>
      </li>
   </div>
   <li ng-hide="!canBook">
      <small>No free resources</small>
   </li>
</ul>

Thanks for any suggestion

Larsi


Solution

  • If the value of period is static or at least does not change with every iteration I would calculate the expensiveFunction(period) only once when the corresponding controller is loaded:

    $scope.period = whatEverItIs
    $scope.isExpensive = expensiveFunction(period);
    

    And in your view:

    <ul>
       <li ng-show="isExpensive" ng-repeat="a in myList">
          <a ng-click="onMove(period)">Move here </a>
       </li>
       <li ng-hide="!canBook">
          <small>No free resources</small>
       </li>
    </ul>