Angular Owl轮播与循环克隆项目超出范围

时间:2016-01-21 11:23:05

标签: javascript angularjs angularjs-directive owl-carousel owl-carousel-2

我有一个指令,将loop选项设置为true的猫头鹰轮播呈现。轮播中的每个项目都链接到ng-click事件。但是,由于loop选项为true,轮播会将每个项目克隆到轮播中以产生循环错觉。这些克隆的项目未附加到控制器范围。

这就是我正在使用的

JS

var app = angular.module('plunker', []);

app.controller('MainCtrl', function($scope) {
  $scope.items1 = [1,2,3,4,5];
  $scope.items2 = [1,2,3,4,5,6,7,8,9,10];
  $scope.a = function(i){
    alert(i);
  }
}).directive("owlCarousel", function() {
    return {
        restrict: 'E',
        transclude: false,
        link: function (scope) {
            scope.initCarousel = function(element) {
              // provide any default options you want
                var defaultOptions = {
                };
                var customOptions = scope.$eval($(element).attr('data-options'));
                // combine the two options objects
                for(var key in customOptions) {
                    defaultOptions[key] = customOptions[key];
                }
                // init carousel
                $(element).owlCarousel(defaultOptions);
            };
        }
    };
})
.directive('owlCarouselItem', [function() {
    return {
        restrict: 'A',
        transclude: false,
        link: function(scope, element) {
          // wait for the last item in the ng-repeat then call init
            if(scope.$last) {
                scope.initCarousel(element.parent());
            }
        }
    };
}]);

HTML

<body ng-controller="MainCtrl">
    <data-owl-carousel class="owl-carousel" data-options="{loop:true}">
      <div owl-carousel-item="" ng-repeat="item in ::items1" class="item">
        <a ng-click="a($index)">{{::item}}</a>
      </div>
    </data-owl-carousel>
  </body>

这是plunker代码

如何重新渲染或将范围链接到新的克隆项?

1 个答案:

答案 0 :(得分:1)

唯一可行的方法是在scope.initCarousel函数中使用$ timeout。我知道这不是最好的解决方案。

以下是plunker已解决的

.directive("owlCarousel", ['$timeout',function($timeout) {
return {
    restrict: 'E',
    transclude: false,
    link: function (scope) {
        scope.initCarousel = function(element) {
           $timeout(function () {
              // provide any default options you want
                var defaultOptions = {
                };
                var customOptions = scope.$eval($(element).attr('data-options'));
                // combine the two options objects
                for(var key in customOptions) {
                    defaultOptions[key] = customOptions[key];
                }
                // init carousel
                $(element).owlCarousel(defaultOptions);
           },50);
    };
    }
};

}])