AngularJS and DOM Manipulation

This is an example of how to manipulate the DOM in AngularJS.

by luchaninov

HTML

<script src="http://code.angularjs.org/angular-1.0.0rc10.js"></script>
<expandable header="Click">
    <ul>
        <li>lkj;lksdf</li>
        <li>lkj;lksdf</li>
        <li>lkj;lksdf</li>
        <li>lkj;lksdf</li>
        <li>lkj;lksdf</li>
    </ul>
</expandable>

CSS

.content {
    background-color: #abc;
    height: 0;
    overflow: hidden;
    
    -webkit-transition: all 1s ease;
    -moz-transition: all 1s ease;
    -o-transition: all 1s ease;
    -ms-transition: all 1s ease;
    transition: all 1s ease;
}
.inner{
    padding: 5px;
}

JavaScript

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

    myApp.directive('expandable', function() {
        return {
            restrict: 'E',
            template: '<div><div class="header"></div><div class="content"><div ng-transclude class="inner"></div></div></div>',
            replace: true,
            transclude: true,
            link: function(scope, element, attrs) {
                var $header = $(element).find('.header');

                $header.html(attrs.header);
                $header.on('click', function(e){
                    var $element = $(element);
                        height = $element.find('.inner').outerHeight(true);
                        $container = $element.find('.content');
                    
                    $container.toggleClass('show');
                    if($container.hasClass('show')){
                        $container.height(height);
                    } else {
                        $container.height(0);
                    }
                });
            }
        };
    });