使用ng-repeat时无法打开或关闭手风琴

时间:2017-05-19 02:40:57

标签: javascript html css angularjs

我是角色的新手,我刚刚用javascript创建了一个动画手风琴来获取并显示一些信息。我决定使用ng-repeat,所以我不必重复编写代码。

然而,手风琴未能动画显示内容。为什么当我使用ng-repeat时它不起作用?它与角度的工作方式有关吗?

请帮忙,谢谢

这是一个例子

https://fiddle.jshell.net/ppw2fag9/1/

1 个答案:

答案 0 :(得分:0)

以这种方式使用Angular时,直到代码运行后才会填充Angular生成的DOM,因此您不会在ng-repeat DOM元素上放置事件侦听器。您不应该使用查询选择器修改DOM,而应该向ng-click元素添加ng-repeated指令。

快速做你想做的事情会是这样的:

var app = angular.module("myApp", []);
app.controller("myCtrl", function($scope) {
  $scope.records = [
    "John",
    "Tyrion",
    "Khaleesi",
  ];
  
  $scope.toggleText= function(e) {
  	var btn = angular.element(e.target);
    var panel = btn.next();
    
  	btn.toggleClass("active");

    if (panel.css('maxHeight')){
      panel.css('maxHeight', null);
    } else {
      panel.css('maxHeight', panel.prop('scrollHeight') + 'px');
    } 
  }
});
button.accordion {
    background-color: #eee;
    color: #444;
    cursor: pointer;
    padding: 18px;
    width: 100%;
    border: none;
    text-align: left;
    outline: none;
    font-size: 15px;
    transition: 0.4s;
}

button.accordion.active, button.accordion:hover {
    background-color: #ddd;
}

div.panel {
    padding: 0 18px;
    background-color: white;
    max-height: 0;
    overflow: hidden;
    transition: max-height 0.2s ease-out;
}
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<body ng-app="myApp" ng-controller="myCtrl">

<h2>With ng-repeat</h2>
<div ng-repeat="y in records">
<button class="accordion" ng-click="toggleText($event)">{{y}}</button>
<div class="panel">
  <p>Some explaination...bla bla blah</p>
</div>

相关问题