如何动态地在ng-click到父元素后添加类?

时间:2015-06-09 04:37:19

标签: javascript jquery html css angularjs

我在单页中有多个视频播放器。如果我使用jQuery,很容易动态找到父元素。但是在Angularjs它没有发生。

    <div class="item-media video-item" ng-class="{'active': isActive}">
         <iframe src="https://www.youtube.com/embed/gvI2ClWqHO0" frameborder="0" width="100%" height="250"></iframe>
         <img src="img/thomas-theatrics.jpg" alt="">
         <div class="play-icon" ng-click="isActive = !isActive"><img src="img/play-icon.png" alt="" class="custom-icon"></div>
    </div>

<div class="item-media video-item" ng-class="{'active': isActive}">
         <iframe src="https://www.youtube.com/embed/gvI2ClWqHO0" frameborder="0" width="100%" height="250"></iframe>
         <img src="img/thomas-theatrics.jpg" alt="">
         <div class="play-icon" ng-click="isActive = !isActive"><img src="img/play-icon.png" alt="" class="custom-icon"></div>
    </div>

1 个答案:

答案 0 :(得分:0)

因为您的元素结构非常类似,所以您可以使用隔离范围制作指令。

angular.module('media', [])
.directive('mediaVideo', function() {
  return {
    template: '<div class="item-media video-item" ng-class="{'active': isActive}">'+
         '<iframe ng-src="{{ iframeSrc }}" frameborder="0" width="100%" height="250"></iframe>'+
         '<img src="img/thomas-theatrics.jpg" alt="">'+
         '<div class="play-icon" ng-click="isActive = !isActive"><img src="img/play-icon.png" alt="" class="custom-icon"></div>'+
         '</div>',
    restrict: 'EA',
    replace: 'true',
    scope:{
        iframeSrc: '='
    },
    link: function(scope,element,attributes){
    },
    controller: function($scope){
        $scope.isActive = false;
    }
  };
});