Search code examples
angularjsangular-uiangular-ui-bootstrap

angular-ui bootstrap accordion: How do I properly $watch the is-open attribute?


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.


Solution

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