【问题标题】:Most sensible way to insert DOM element at specific point within ng-repeat?在 ng-repeat 中的特定点插入 DOM 元素的最明智方法?
【发布时间】:2018-01-04 17:33:50
【问题描述】:

我希望使用 AngularJS 创建一个播客播放器应用程序。

到目前为止,我已经使用 ng-repeat 获得了可以播放的播客列表,如下所示。

<ul ng-controller="list">
  <li ng-repeat="podcast in podcasts" ng-click="startPlaying()">
    <p>{{podcast.created_time | date}}</p>
    <div class="podcast-icon" style="background-image:url('{{podcast.icon}}')">
      <i class="fa fa-play"></i>
    </div>
    <h3>{{podcast.name}}</h3>
    <p>{{podcast.duration}}m</p>
  </li>
</ul>

这些显示在响应式弹性框网格中,我希望函数 startPlaying 触发播放器出现在被点击项目 similar to Netflix 正下方的行上。

我很困惑如何:

  1. 获取被点击元素行尾&lt;li&gt;元素的索引,假设网格是响应式的并且每行上&lt;li&gt;s的数量随着视口。
  2. 告诉 Angular 在 ng-repeat 中的特定索引之后插入一个新的 DOM 元素。

我想我可以用window.getComputedStyle(ul).width 从父级的宽度推断出每行&lt;li&gt;s 的数量,但这似乎是迂回的。有没有更好的办法?

谢谢!

【问题讨论】:

    标签: javascript css angularjs flexbox


    【解决方案1】:

    您可以通过以下方式访问 li 的索引:

    {{$index}}
    

    甚至:

    {{podcasts.indexOf(podcast)}}
    

    如果你将它输入到你的点击事件中,你可以在相应的函数中添加一个元素,如下所示:

    <li ng-repeat="podcast in podcasts" ng-click="startPlaying($index)">
    

    但是你需要选择正确的元素,所以给 li 一个类:

    <li class="podcast" ng-repeat="podcast in podcasts" ng-click="startPlaying($index)">
    

    然后在你的 startPlaying 函数中按索引选择元素并附加你的元素:

    $scope.startPlaying = function(index) {
      var podcasts = document.getElementsByClassName('podcast')
      var currentPodcast = podcasts[index]
      angular.element(currentPodcast).append('<html></html>');
    }
    

    只需将&lt;html&gt;&lt;/html&gt; 替换为您要附加的元素即可。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-03-03
      • 2015-06-08
      • 2019-05-09
      • 1970-01-01
      • 1970-01-01
      • 2021-12-09
      相关资源
      最近更新 更多