All:
I am new to AngularJS directive template, right now one thing confuses me is how to get the DOM element which decided by ng-if in directive template.
For example:
app.directive("dir", function(){
return {
restrict:"AE",
scope: {},
controller: function(){},
templateUrl: "templates/testpostlink.html",
compile: function(){
return {
pre: function(){
},
post:function(scope, EL, attrs){
// Here I am wondering how to get that div (let say scope.show is true)
}
};
}// end of compile
};
});
And template testpostlink.html is:
<div ng-if="show">Show Content</div>
What I want to do is get this div element and adjust style to it. But in post function, there is still no that element generated.
Could anyone help with this?
Thanks
The first thing you are doing wrong is you are not passing in a show variable so the ng-if is not showing. Secondly, use the post link function to add styles to your element.
http://plnkr.co/edit/PqXg6e?p=preview
<!-- pass in show variable -->
<div dir show="showFromCtrl"></div>
app.directive("dir", function($compile) {
return {
restrict:"AE",
// needed to pass in show variable
scope: { show: "=" },
templateUrl: 'testpostlink.html',
compile: function compile(tElement, tAttrs, transclude) {
return {
post: function postLink(scope, iElement, iAttrs, controller) {
// access element and add styles in post link fn
iElement.css('color', 'red');
}
}
}
}
});