几个要素的一个指令

时间:2013-02-21 06:41:25

标签: angularjs angularjs-directive angularjs-scope

例如我有这样的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

1 个答案:

答案 0 :(得分:0)

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

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