0

例如我有这样的 HTML 页面:

<body  ng-app="MyApp">
<standart-slider class="slider-app" controls-value="{previous: '#previous', next: '#next', sliderWrap: '.wrapper', slidesName: '.slide', minSlides: '4', controls: '.control'}">
        <div class="control" id="previous">Prev</div>
        <div class="slide-add">Add</div>
        <div class="control" id="next">Next</div>
        <div class="wrapper">
            <div class="slide"></div>
            <div class="slide"></div>
            <div class="slide"></div>
            <div class="slide"></div>
            <div class="slide"></div>
            <div class="slide"></div>
        </div>
 </standart-slider>
 <standart-slider class="slider-app" controls-value="{previous: '#previous', next: '#next', sliderWrap: '.wrapper', slidesName: '.slide', minSlides: '4', controls: '.control'}">
        <div class="control" id="previous">Prev</div>
        <div class="slide-add">Add</div>
        <div class="control" id="next">Next</div>
        <div class="wrapper" data-my-attr="">
            <div class="slide"></div>
            <div class="slide"></div>
            <div class="slide"></div>
            <div class="slide"></div>
            <div class="slide"></div>
            <div class="slide"></div>
        </div>
 </standart-slider>
</body>

还有这样的指令:

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

MyApp.directive('standartSlider', function () {
var linkFn = function (scope, element, attrs) {
    console.log('Hello!');
    var controls = scope.contorls();
    console.log(controls.previous);
    var currentPosition = 0;
    var slideWidth = 70;
    var slides = angular.element(controls.slidesName);
    var wrapper = angular.element(controls.sliderWrap);
    var previous = angular.element(controls.previous);
    var next = angular.element(controls.next);
    var numberOfSlides = slides.length;
    console.log(numberOfSlides, slides, wrapper, previous, next);

    wrapper.css('overflow', 'hidden');
    slides.wrapAll('<div id="slideInner"></div>')
    $('#slideInner').css('width', slideWidth * numberOfSlides);

    angular.element(controls.controls).click(function () {
        currentPosition = ($(this).attr('id') == 'next') ? currentPosition + 1 : currentPosition - 1;
        console.log(currentPosition);
        attrs.myAttr = "100";

        $('#slideInner').animate({
            'marginLeft': slideWidth * (-currentPosition)
        });
        console.log($('#slideInner').css("marginLeft"))
    });


    }

    return {
        restrict: 'E',
        scope: {
            contorls: '&controlsValue'
        },
        link: linkFn
    }
});

问题是然后我单击“下一步”按钮,滑动第一个滑块而不是第二个。我如何看待它,范围不隔离 DOM 元素。如何隔离指令副本与 DOM 元素?小提琴示例:jsFiddle

4

1 回答 1

0

如我所见,您的指令使用 Ids 而不是类。不要忘记,在 DOM 文档中,即使有不同的父级,也不可能有两个具有相同 id 的元素。

因此,您需要重写指令以使用类并仅在链接元素的子元素处搜索。

于 2013-02-21T08:22:39.323 回答