AngularJS - 用于ng-repeat-start和ng-repeat-end的单一控制器

时间:2014-08-27 09:44:36

标签: angularjs angularjs-ng-repeat

我有这个HTML:

<table>
  <tr ng-repeat-start="client in clients" ng-controller="ClientCtrl">
     <td ng-click="toggleExpand()">
        Expand
     </td>
     <!-- some html -->
  </tr>
  <tr ng-show="isExpanded" ng-repeat-end>
     <!-- some html -->
  </tr>
</table>

这个JS:

angular.module('app').controller('ClientCtrl', function($scope){
   $scope.isExpanded= false;
   $scope.toggleExpand = function(){
       $scope.isExpanded = !$scope.isExpanded;
   }
});

对于每个重复的元素,我希望ClientCtrl的同一个实例同时应用于ng-repeat-startng-repeat-end,以便isExpanded可以从{{}内部切换1}}并可通过ng-repeat-start访问。

有可能吗?

修改

我不是在寻找解决方法来使切换工作,我真正想要的是能够在ng-repeat-endng-repeat-start之间共享一个范围,并且切换的功能只是一个示例

2 个答案:

答案 0 :(得分:1)

是的。您需要使用该项目的$index才能够单独切换每个项目。

HTML:

<table>
  <tr ng-repeat-start="client in clients" ng-controller="ClientCtrl">
     <td ng-click="toggleExpand($index)">
        Expand
     </td>
     <!-- some html -->
  </tr>
  <tr ng-show="isExpanded($index)" ng-repeat-end>
     <!-- some html -->
  </tr>
</table>

并相应地更新toggleExpand功能。

答案 1 :(得分:1)

想出办法:

<table>
  <tr ng-repeat-start="client in clients" ng-controller="ClientCtrl">
     <td ng-click="vm.toggleExpand()">
        Expand
     </td>
     <!-- some html -->
  </tr>
  <tr ng-show="vm.isExpanded" ng-repeat-end ng-controller="ClientEndCtrl">
     <!-- some html -->
  </tr>
</table>


angular.module('app').controller('ClientCtrl', function($scope){
   $scope.vm = {
       isExpanded: false,
       toggleExpand: function(){
           $scope.vm.isExpanded = !$scope.vm.isExpanded;
       }
   }
}).controller('ClientEndCtrl', function($scope){
    // vm is a shared view model across ng-repeat-start and ng-repeat-end
    $scope.vm = $scope.$$prevSibling.vm;
});