iLemming
iLemming

Reputation: 36166

rewiring directive within a directive

So in this example ng-hide doesn't hide the element. why and how to fix that?

<div ng-app='myApp'>
    <input type='text' foo/>
</div>

angular.module('myApp',[])
  .directive('foo',function(){
    return{
        link:function(scope,element,attrs){
            element.after('<div style="width:200px; height:200px;'
                    +' background-color:red" ng-hide="true"></div>')
        }
    }
});

http://jsfiddle.net/BL8h5/

Upvotes: 0

Views: 121

Answers (1)

Alex Osborn
Alex Osborn

Reputation: 9851

See this updated example:

http://jsfiddle.net/JxMTW/1/

angular.module('myApp',[])
.directive('foo',function($compile){
    return{
        link:function(scope,element,attrs){
            element.after($compile('<div style="width:200px; height:200px; background-color:red" ng-hide="true"></div>')(scope))
        }
    }
}); 

The reason is that this isn't the 'angular' way to do things - you should avoid 'messing with the DOM', and instead use a template and let angular handle it.

In your specific case, what you needed to do was run the new element through $compile, which parses the content and picks up any angular logic.

For more information see this question and answer: AngularJS and generated elements

Upvotes: 2

Related Questions