Angularjs ul 内的中继器 - 如何在不中断的情况下添加 ng-show html

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

检查下面的例子。在这种情况下,为 myList

中的每个项目调用 'expensiveFunction'
<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>

关于如何防止这种情况的任何想法?

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

感谢任何建议

拉尔西

您可以尝试通过添加新的 display 属性来在单独的函数中进行所有计算,以存储 ng-show 的状态。 尝试通过一次调用函数来一次完成所有计算。

例如

/**
 * Expensive function
 * @param {string} lists
 * @returns {object}
 */
function expensiveFunction(lists){
    angular.forEach(lists, function (key, value) {
       lists.display = true; // here goes your logic
    });
    return lists;
}

var myList = expensiveFunction(myList);

<ul>
   <li ng-show="a.dispaly" 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>

如果 period 的值是静态的或者至少不会随着每次迭代而改变,我会在加载相应的控制器时只计算一次 expensiveFunction(period)

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

在您看来:

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