2017-05-19 65 views
0

我是angular的新手,我刚刚创建了一个带有javascript的动画手风琴来获取并显示一些信息。我决定使用ng-repeat,所以我不必重复编写代码。在使用ng-repeat时无法打开或关闭手风琴

但是,无法显示内容的动画。为什么当我使用ng-repeat时它不起作用?这是否与棱角分明的方式有关?

请帮帮忙,谢谢

这里是

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

+0

你已经调查'NG-click'作为替代?它可能被认为是不好的做法,像这样混合angularjs和原生javascript。 – axlj

回答

0

当以这种方式使用角,角产生的DOM不填充直到代码运行之后的示例,这样你就不会放置DOM元素上的事件侦听器。您不应该使用查询选择器来修改DOM,而应该为ng-repeated元素添加ng-click指令。

的快捷方式做你想要做看起来是这样的:

var app = angular.module("myApp", []); 
 
app.controller("myCtrl", function($scope) { 
 
    $scope.records = [ 
 
    "John", 
 
    "Tyrion", 
 
    "Khaleesi", 
 
    ]; 
 
    
 
    $scope.toggleText= function(e) { 
 
    \t var btn = angular.element(e.target); 
 
    var panel = btn.next(); 
 
    
 
    \t 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>