我有一个模板,在该模板中,我在$ scope.trailers中重复了预告片对象,并添加了一个有角度的指令,该指令在模板中创建了嵌入的youtube播放器,

.container-info
  .trailers
  %ul.trailers
    %li{"ng-repeat" => "trailer in trailers | filter: { movie_id: movie.movie_id}"}
      {{ trailer.link }}

  .container-trailers
    %youtube{:videoid => "M7lc1UVf-VE"}


如您现在所见,我将M7lc1UVf-VE的值设置为videoid。我想做的就是获取第一个{{ trailer.link }}的结果并将其插入videoid中。

所需的结果看起来像这样,

<div class="container-info">
  <ul class="trailers">
    <li>ePbKGoIGAXY</li>
    <li>KlyknsTJk0w</li>
    <li>nyc6RJEEe0U</li>
    <li>zSWdZVtXT7E</li>
    <li>Lm8p5rlrSkY</li>
  </ul>
  <div class="container-trailers">
    <youtube videoid="ePbKGoIGAXY"></youtube
  </div>
</div>


我如何获得这样的结果?

这是youtube指令,

app.directive('youtube', function($window, youTubeApiService) {
  return {
    restrict: "E",
    scope: {
      videoid: "@"
    },
    template: '<div></div>',
    link: function(scope, element, attrs, $rootScope) {
      var tag = document.createElement('script');
      tag.src = "https://www.youtube.com/iframe_api";
      var firstScriptTag = document.getElementsByTagName('script')[0];
      firstScriptTag.parentNode.insertBefore(tag, firstScriptTag);

      var player;

      youTubeApiService.onReady(function() {
        player = setupPlayer(scope, element);
      });

      function setupPlayer(scope, element) {
        return new YT.Player(element.children()[0], {
          playerVars: {
            autoplay: 0,
            html5: 1,
            theme: "light",
            modesbranding: 0,
            color: "white",
            iv_load_policy: 3,
            showinfo: 1,
            controls: 1
          },
          videoId: scope.videoid,
        });
      }

      scope.$watch('videoid', function(newValue, oldValue) {
        if (newValue == oldValue) {
          return;
        }
        player.cueVideoById(scope.videoid);

      });
      console.log ('youtube player directive')
    }
  };
});


它使用videoid作为变量。

*其他但相关的问题*

是否可以单击a或其他元素以获取该元素的值,然后将其传递给videoid范围,以便更新YouTube videoid?

<div class="container-info">
  <ul class="trailers">
    <li><a href="#">ePbKGoIGAXY</a></li>
    <li><a href="#">KlyknsTJk0w</a></li>
    <li><a href="#">nyc6RJEEe0U</a></li> <-- clicked element
    <li><a href="#">zSWdZVtXT7E</a></li>
    <li><a href="#">Lm8p5rlrSkY</a></li>
  </ul>
  <div class="container-trailers">
    <youtube videoid="nyc6RJEEe0U"></youtube> <-- updated value of videoid
  </div>
</div>

最佳答案

通过按li过滤呈现movie.movie_id时,我们将创建一个新数组,该数组将仅具有名为filteredTrailers的过滤值。然后我们通过执行filteredTrailers[0].link从该过滤后的数组中获取第一个值,这将为您提供第一个对象的链接,并且该值将通过videoid(interpolation)传递给{{}}属性,因为伪指令具有对@(一种方式绑定)。

标记

.container-info
  .trailers
  %ul.trailers
    %li{"ng-repeat" => "trailer in filteredTrailers = (trailers | filter: { movie_id: movie.movie_id})"}
      {{ trailer.link }}

  .container-trailers
    %youtube{:videoid => "{{filteredTrailers[0].link}}"}

10-06 00:44