Angularjs - 手风琴不能按预期工作

时间:2016-05-26 10:55:39

标签: angularjs

使用angularjs,我创造了一个手风琴效果。一切都有效,而不是考虑其他小组。

我的手风琴有2个面板,当我点击第一个面板时,应该改变状态(正在发生)并且如果打开则需要关闭其他面板。怎么做?

var app = angular.module('myapp', []);
app.controller('MainCtrl', function($scope) {
    $scope.one = false;
    $scope.two = false;
    $scope.accordion = function( label ) {
        $scope[label] = !$scope[label];
    }
});
h1 {
    background: gray;
    cursor: pointer;
}
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<div ng-app="myapp" ng-controller="MainCtrl">
    <h1 ng-click="accordion('one')">Title One</h1>
    <div ng-show="one">Content one</div>
    <h1 ng-click="accordion('two')">Title Two</h1>
    <div ng-show="two">Content Two</div>
</div>

1 个答案:

答案 0 :(得分:2)

它只是分配单个变量,没有任何复杂的逻辑。因此,删除冗余功能并将分配移至HTML中的ng-click

&#13;
&#13;
var app = angular.module('myapp', []);

app.controller('MainCtrl', function($scope) {
  
  //$scope.one = false; // this is not required anymore
  //$scope.two = false; // this is not required anymore
  $scope.current = 'one';
  // toggle accordion state
  $scope.toggleAccordion = function(label){
        if($scope.current == label){
              $scope.current = '';
        } else {
              $scope.current = label;
        }
  }
  
});
&#13;
h1{
  background:gray;
  cursor:pointer;
}
&#13;
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
  <div ng-app="myapp" ng-controller="MainCtrl">
    <h1 ng-click="toggleAccordion('one')">Title One</h1>
    <div ng-show="current == 'one'">Content one</div>
    <h1 ng-click="toggleAccordion('two')">Title Two</h1>
    <div ng-show="current == 'two'">Content Two</div>
  </div>
&#13;
&#13;
&#13;