ps0604 ps0604 - 2 months ago 14
Javascript Question

AngularJS: element.show() in directive not working

I have a directive (see plunk) that wraps a DIV with style

display:none
and after one second shows its content. I tried to make it display with element.show() and $(element).show() (including jQuery) but it never worked. The timeout works, what's wrong with this code?

This is the HTML:



<hideme>
Show this after one second
</hideme>




and this is the javascript:

angular.module("app", []);

function MyCtrl($scope) {}

angular.module("app").directive('hideme', function($timeout) {

return {

restrict: 'E',
template: '<div style="display: none !important"></div>',
link: function(scope, element, attrs) {
$timeout(function() {
element.show();
}, 1000);
}
};
});

Answer

Plunker: http://plnkr.co/edit/bzhCwjXdll3ibxc7qsMY?p=preview

Try using transclude:true and then ng-transclude to display the markup between custom element tags. Also, I'm not familiar with using show(), so instead set html ng-show='showEl' and define showEl = true in the timeout.

angular.module("app", []);

function MyCtrl($scope) {}

angular.module("app").directive('hideme', function($timeout) {

    return {
          transclude: true,
        restrict: 'E',
        template: '<div ng-show="showEl"><div ng-transclude></div></div>',
        link: function(scope, element, attrs) { 
            $timeout(function() {
                  scope.showEl = true;
              }, 1000);
        }
    };
});