Bootstrap手风琴折叠按钮

时间:2014-05-14 08:50:20

标签: javascript jquery angularjs twitter-bootstrap bootstrap-accordion

我正在尝试制作带有内部按钮的自举手风琴,该按钮将折叠当前的手风琴乐段并打开下一个手风琴乐段,这由于某种原因无效。

HTML:

<div ng-controller="AccordionDemoCtrl">  
    <accordion>
       <accordion-group id="firstpanel" heading="Static Header 1"  is-open="status.isFirstOpen">
          <span id="span1">This content is straight in the template.</span><br> 
          <button id="nextpanel">Next</button>
       </accordion-group>
       <accordion-group heading="Static Header 2">
          <span id="span1">This content is straight in the template.</span>
       </accordion-group>
    </accordion>
</div>

JAVASCRIPT:

angular.module('plunker', ['ui.bootstrap']);
function AccordionDemoCtrl($scope) {
  $scope.status = {
    isFirstOpen: true,
    isFirstDisabled: false
  };

  $("#nextpanel").on("click", function() {   
   $(firstpanel).click();
  });
}

我在这里做了一个有关的例子:Plunker

1 个答案:

答案 0 :(得分:0)

您不能在控制器构造函数中使用jquery选择器。像#nextpanel这样的DOM元素在该阶段甚至不在DOM树中,因此$("#nextpanel")本质上是一个空数组。

我建议你完全忘掉jquery。 jquery的唯一情况是,当你需要使用你已经熟悉的插件时(比如日历)。在任何情况下,jquery代码(具有$()的代码)应该严格地驻留在包装插件的指令的链接函数中。

MVC方式,就是要有一个“模型”(JS对象)驱动UI。 Angular将发挥其魔力,使两者保持同步。

存储手风琴打开的模型可能只是一组布尔值:

$scope.status = [true, false, false, false];

打开下一个手风琴只是找到哪一个被打开,并在下一个手风琴时设置为true(或环绕到第一个)。

$scope.next = function() {
    var indx = $scope.status.indexOf(true);
    $scope.status[(++indx) % $scope.status.length] = true;
};

手风琴组件将确保在任何给定时间只有其中一个true

现在,您的模板类似于:

<accordion>

    <accordion-group heading="Static Header 1"  is-open="status[0]">
      <span>This content is straight in the template.</span><br>
      <button ng-click="next()">Next</button>
    </accordion-group>

    <accordion-group heading="Static Header 2"  is-open="status[1]">
      <span>This content is straight in the template.</span><br>
      <button ng-click="next()">Next</button>
    </accordion-group>

    <accordion-group heading="Static Header 3"  is-open="status[2]">
      <span>This content is straight in the template.</span><br>
      <button ng-click="next()">Next</button>
    </accordion-group>

    <accordion-group heading="Static Header 4" is-open="status[3]">
      <span>This content is straight in the template.</span><br>
      <button ng-click="next()">Start over</button>
    </accordion-group>

</accordion>

这是固定的plunker