5

I'm trying to perform an action when a specific accordion-section is openend. My use-case is almost identical to this question here, only I'm using statically defined 's instead of ng-each.

Somehow I can't get the $watch to fire when the is-open state changes, can anybody tell me why this doesn't work:

View:

  <accordion close-others="false">
   <accordion-group heading="group1" is-open="acc1open">
    content 1
   </accordion-group>    
   <accordion-group heading="group2" is-open="acc2open">
    content 2
   </accordion-group>  
  </accordion>  

Controller:

  $scope.acc1open = false;
  $scope.acc2open = true;

  $scope.$watch('acc1open', function(){
      console.log("watch acc1:" +$scope.acc1open);
  }, true);

Here's a plunker:

https://plnkr.co/edit/Ycms81?p=preview

It prints "watch acc1:false" a single time when the page is loaded, but nothing when the accordion group is opened.

Syscall
  • 19,327
  • 10
  • 37
  • 52
C. Ramseyer
  • 2,322
  • 2
  • 18
  • 22

2 Answers2

11

Along with the plunker: plnkr.co/edit/1lnbTa?p=preview

I found this worked for an array:

JS

$scope.array = [object1,object2,object3,object4];
$scope.isOpen = [false,false,false,false];
$scope.$watch('isOpen', function() {
  console.log("watch isOpen:" + $scope.isOpen);
}, true);

HTML(JADE)

accordion-group(ng-repeat='object in array',is-open="$parent.isOpen[$index]")
  accordion-heading
    h4 My Heading {{$index}}
  p My content {{$index}}
dacopenhagen
  • 2,414
  • 2
  • 23
  • 29
  • 1
    I agree, at least put you in the right direction. You can set $scope.isOpen = [true]; so that the first panel is always open. And then it'll fill the rest of elements for you by is-open="isOpen[$index]" – windmaomao Jun 02 '15 at 20:39
  • In order to find the current open panel, you can do _.indexOf($scope.isOpen, true) if you are using underscore. – windmaomao Jun 02 '15 at 20:48
2

I added a <span> inside the AccordionDemoCtrl div and changed the is-open to bind to $parent.acc1open

<accordion-group heading="group1" is-open="$parent.acc1open">

...

<span ng-click="acc1open = true">Click me to open group 1</span>

Directives have their own scope, and the variables are their own.

Foo L
  • 10,977
  • 8
  • 40
  • 52
  • Thanks that was it! Updated Plunker for the record: http://plnkr.co/edit/1lnbTa?p=preview – C. Ramseyer May 18 '13 at 07:36
  • 1
    This description was iffy for me, so I'll add a comment with how I did this. The plunker was the solution for me. – dacopenhagen Jun 23 '13 at 19:45
  • this actually is a wrong answer, you should not associate a single value to multiple is-open. Take a look at the above plunker, it actually is not working. – windmaomao Jun 02 '15 at 20:37