$ compile打破了ng-repeat

时间:2014-08-27 22:01:50

标签: javascript angularjs

所以我试图遍历ng-repeat生成的元素列表,用指令标记它们(在本例中为ng-show),然后使用$ compile重新编译。我遇到的问题是$ compile会破坏ng-repeat指令,只会破坏repeat get输出的注释。我在这里缺少什么?

编辑:如果我在运行ng-repeat之前删除$compile指令,则此方法有效。这是正确的方法,还是我还缺少什么?

我的指示:

.directive("imageSlider", [ '$timeout', '$compile', '$rootScope', function($timeout, $compile, $rootScope) {
    return function(scope, element, attrs)
    {
        // Remove image slider attribute from element to prevent infinite loop
        element.removeAttr("image-slider");

        // Set the current slide
        scope.currentSlide = 0;

        // Wait for all other first-round directives to finish
        $rootScope.$on("initialised", function(){
            // Get the slides
            var slides = $("[slide]");

            // Loop over all the slides
            for (var i=0, j=slides.length; i<j; i++) {
                $(slides[i]).attr("ng-show", "currentSlide == " + i);
            };

            // Re-compile the template with the new ng-show attributes
            $compile(element)(scope);
        });
    }
}])

这是标记的样子:

<div class="image-slider" image-slider>
    <div class="slider-items">
        <a class="slider-item" ng-repeat="slide in page.slides" href="{{slide.link}}" slide>
            <div class="image-container">
                <img ng-src="{{slide.image}}" alt="{{slide.title}}">
            </div>
            <div class="excerpt">
                <h1>{{slide.title}}</h1>
                <h2>{{slide.excerpt}}</h2>
                <p class="cta">Learn More &rsaquo;</p>
            </div>
        </a>
    </div>
</div>

产生的标记块:

<div class="image-slider ng-scope">
    <div class="slider-items">
        <!-- ngRepeat: slide in page.slides --><!-- ngRepeat: slide in page.slides --><!-- end ngRepeat: slide in page.slides --><!-- ngRepeat: slide in page.slides --><!-- end ngRepeat: slide in page.slides --><!-- ngRepeat: slide in page.slides --><!-- end ngRepeat: slide in page.slides --><!-- ngRepeat: slide in page.slides --><!-- end ngRepeat: slide in page.slides --><!-- ngRepeat: slide in page.slides --><!-- end ngRepeat: slide in page.slides -->
    </div>
</div>

如果您想知道"initialised"活动的来源,请点击此处:

.directive('initialised', ['$rootScope',function($rootScope) {
    return {
        //restrict: 'A',
        link: function ($scope) {
            var to;
            var listener = $scope.$watch(function(){
                clearTimeout(to);
                to = setTimeout(function() {
                    App.init();
                    listener();
                    $rootScope.$broadcast('initialised');
                }, 150);
            });
        }
    };
}])

0 个答案:

没有答案