简体   繁体   中英

AngularJS directive template class not rendering

I have a simple directive which returns a template. The issue is that the class used in the template isn't working. Here is the HTML code:

 <div ng-app="mapp">
    <div ng-controller="ctrl">
        <div class="panel">
            <check-list></check-list>
        </div>
    </div>
</div>

Here is the directive:

.directive('checkList',function(){
    return {
        restrict:'E',
        template: function(elem,attrs){
            return '<div class="inner">Hello</div>'
        }
    };
});

And here is a DEMO

Your CSS rule doesn't work because .inner div is not a direct child of the .panel , since Angular inserts template into check-list element.

You have two options.

The first is to use replace: true configuration of the directive:

.directive('checkList',function() {
    return {
        replace: true,
        restrict: 'E',
        template: function(elem, attrs) {
            return '<div class="inner">Hello</div>';
        }
    };
});

Demo 1: http://jsfiddle.net/zo9wk8gd/2/

And the second is to change CSS rule to be

.panel .inner {
    background-color:blue;
}

Demo 2: http://jsfiddle.net/zo9wk8gd/4/

CSS solution:

you have style

.panel > .inner{
    background-color:blue;
}

which defined a background-color blue to the direct child .inner of .panel , but what structure you have is:

<div class="panel">
        <check-list><div class="inner">Hello</div></check-list>
    </div>

So .inner is not direct child of .panel


Change your style to this: http://jsfiddle.net/zo9wk8gd/1/

 .panel .inner{ background-color:blue; } 

or this http://jsfiddle.net/zo9wk8gd/5/

  check-list >.inner{ background-color:blue; } 


If you want to dig into correct way of creating a replace template , see answer from dfsq

your directive outputs like below

    <check-list><div class="inner">Hello</div></check-list>

So you are getting final output like below.

<div class="panel">
    <check-list><div class="inner">Hello</div></check-list>
</div>

so the selector .panel > .inner would failed to apply css rules.

to take the effect just change directive like this:

.directive('checkList',function(){
    return {
        restrict:'E',
        template: function(elem,attrs){
            return '<div class="panel"><div class="inner">Hello</div></div>'
        }
    };
});

Here is working fiddle

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM