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

15,248

Solution 1

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.

Solution 2

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}}
Share:
15,248
C. Ramseyer
Author by

C. Ramseyer

Updated on June 10, 2022

Comments

  • C. Ramseyer
    C. Ramseyer almost 2 years

    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.

  • C. Ramseyer
    C. Ramseyer almost 11 years
    Thanks that was it! Updated Plunker for the record: plnkr.co/edit/1lnbTa?p=preview
  • dacopenhagen
    dacopenhagen almost 11 years
    This description was iffy for me, so I'll add a comment with how I did this. The plunker was the solution for me.
  • windmaomao
    windmaomao almost 9 years
    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
    windmaomao almost 9 years
    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
    windmaomao almost 9 years
    In order to find the current open panel, you can do _.indexOf($scope.isOpen, true) if you are using underscore.