0

I'm new to Angular so this is a question about best practices and separation of concerns.

Let's say I have the following setup

<div ng-controller='SomeCtrl'>
  <div ng-repeat="item in list">
    <div class='item'>
      {{ item.name }}
    </div>
  </div>
</div>

Let's say that each 'item' can be either expanded or collapsed in the view. So for each item there is a boolean for the state. Is it appropriate to have expanded = [...booleans...] in the controller and use ng-class="{ active: expanded[index] }" on each view?

I am not sure where to keep the expanded state of each item.

Sam Stern
  • 24,624
  • 13
  • 93
  • 124

1 Answers1

1

Use a directive:

app.directive('expandable', function() {
  return {
    restrict: 'A',
    link: function(scope, elem, attrs) {
      var expanded = false;

      var toggleExpansion = function() {
        // Do something with elem here based on expanded variable
      };

      elem.click(function(e) {
        toggleExpansion();
      });
    }
  }
});

Then in your html write:

<div ng-controller="SomeCtrl">
  <div ng-repeat="item in list" expandable></div>
</div>

This way, you don't have to keep your view logic in the controller, and the state of each expandable item is managed individually/apart from the scope.

Mike Quinlan
  • 2,873
  • 17
  • 25