展开/折叠多选标签(optgroup)

时间:2017-03-07 19:27:26

标签: javascript jquery html angularjs select

我在这里做了一个例子plnkr:Plnkr

我想知道是否可以使粗体标签可扩展/可折叠?我问,因为我一直试图弄清楚如何才能做到这一点,我只能看到粗体标签,在展开时我会看到它们的内容。

下面是html代码,JS和CSS

HTML:

<!DOCTYPE html>
<html ng-app="test">

<head>
  <script data-require="angular.js@1.4.1" data-semver="1.4.1" src="https://code.angularjs.org/1.4.1/angular.js"></script>
  <link rel="stylesheet" href="style.css" />
  <script src="script.js"></script>
</head>

<body ng-controller="MainCtrl">


  <select multiple class="box">
    <optgroup ng-repeat="(key,value) in data" label="{{value.label}}">
      <option ng-repeat="id in value.ids">{{id}}</option>
    </optgroup>
  </select>

</body>

</html>

JAVASCRIPT:

// Code goes here

var app = angular.module('test',[]);

app.controller('MainCtrl',function ($scope) {

  $scope.data = [{
    label: "My Label", ids: [ "one id", "another id" ]
    },{ 
    label: "My Other Label", ids: [ "one id", "another id" ] 
    }];



});

CSS:

.box {
  height: 120px;
}

1 个答案:

答案 0 :(得分:1)

请参阅此fiddle

<强>代码:

<select multiple class="box">
    <optgroup ng-click="value.expanded = !value.expanded" ng-repeat="(key,value) in data" label="{{value.label}}">
      <option ng-click="$event.stopPropagation()" ng-if="value.expanded" ng-repeat="id in value.ids">{{id}}</option>
    </optgroup>
  </select>

$scope.data = [
 { label: "My Label", ids: [ "one id", "another id" ], expanded: true },
 { label: "My Other Label", ids: [ "one id", "another id" ], expanded: false }
];

<强>的变化:

  • 在每个子值中添加ng-if="value.expanded"(您也可以使用ng-show
  • 在标签级别添加了ng-click="value.expanded = !value.expanded",以切换可见性。
  • 在控制器(expanded: true
  • 中为每个标签添加了默认值
  • 添加ng-click="$event.stopPropagation()"以防止选择要折叠的子组(如果您在选择时需要自定义功能,则应将其移至某个功能)