Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

AngularJS - single controller for ng-repeat-start and ng-repeat-end

I have this 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>

And this JS:

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

For each repeated element, I want the same instance of ClientCtrl to apply to both ng-repeat-start and ng-repeat-end, so that isExpanded can be toggled from inside of ng-repeat-start and be accessible via ng-repeat-end.

Is it possible?

EDIT:

I'm not looking for workarounds to make the toggle work, what I really want is to be able to share a scope across ng-repeat-start and ng-repeat-end, and the functionality of the toggle is just an example.

like image 481
Max Avatar asked Mar 14 '26 18:03

Max


2 Answers

Yes it is. You will need to use the $index of the item in order to be able to toggle each individually.

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>

And update the toggleExpand function accordingly.

like image 140
Muhammad Reda Avatar answered Mar 17 '26 07:03

Muhammad Reda


Figured out a way do do it:

<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;
});
like image 28
Max Avatar answered Mar 17 '26 06:03

Max