Search code examples
javascriptangularjsangularjs-directiveng-showng-hide

Angularjs Directive to slide show and hide content


I have used Slide up/down effect with ng-show and ng-animate as a base for my issue. However, the directive only allow for one element to be hidden/displayed. When there are 2, only the first shows:

Here's a plunker: http://plnkr.co/edit/YtPgcUcnapiQfAR5hxiE?p=preview

If you click on Link 2, it'll show the first content.

angular.module('app', [])
.directive('sliderToggle', function() {
    return {
        restrict: 'AE',
        link: function(scope, element, attrs) {
            var target = element.parent()[0].querySelector('[slider]');
            attrs.expanded = false;
            element.bind('click', function() {
                var content = target.querySelector('.slideable_content');
                if(!attrs.expanded) {
                    content.style.border = '1px solid rgba(0,0,0,0)';
                    var y = content.clientHeight;
                    content.style.border = 0;
                    target.style.height = y + 'px';
                } else {
                    target.style.height = '0px';
                }
                attrs.expanded = !attrs.expanded;
            });
        }
    }
})
.directive('slider', function () {
    return {
        restrict:'A',
        compile: function (element, attr) {
            // wrap tag
            var contents = element.html();
            element.html('<div class="slideable_content" style="margin:0 !important; padding:0 !important" >' + contents + '</div>');

            return function postLink(scope, element, attrs) {
                // default properties
                attrs.duration = (!attrs.duration) ? '1s' : attrs.duration;
                attrs.easing = (!attrs.easing) ? 'ease-in-out' : attrs.easing;
                element.css({
                    'overflow': 'hidden',
                    'height': '0px',
                    'transitionProperty': 'height',
                    'transitionDuration': attrs.duration,
                    'transitionTimingFunction': attrs.easing
                });
            };
        }
    };
});

Solution

  • The flaw occurs here:var target = element.parent()[0].querySelector('[slider]');. This statement element.parent()[0] will return the parent of the current element which will always be <article>.

    Further more: I assume the element.parent()[0].querySelector('[slider]') will select the first child of article according to the doc for 'querySelector':

    Returns the first element within the document (using depth-first pre-order traversal of the document's nodes) that matches the specified group of selectors

    You should use var target = element.next()[0]; if you want to select a slider exactly after your button. Or var target = element.next('[slider]')[0]; if it is not directly after;

    Here is a plunker

    Hope this helps!