[英]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: 这是HTML代码:
<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>'
}
};
});
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. 您的CSS规则不起作用,因为.inner
div不是.inner
的直接子.panel
,因为Angular将模板插入check-list
元素。
You have two options. 您有两个选择。
The first is to use replace: true
configuration of the directive: 第一种是使用replace: true
伪指令的replace: true
配置:
.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/ 演示1: http : //jsfiddle.net/zo9wk8gd/2/
And the second is to change CSS rule to be 其次是将CSS规则更改为
.panel .inner {
background-color:blue;
}
Demo 2: http://jsfiddle.net/zo9wk8gd/4/ 演示2: http : //jsfiddle.net/zo9wk8gd/4/
CSS solution: CSS解决方案:
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: 它为.panel
的直接子.inner
定义了背景色蓝色,但是您具有的结构是:
<div class="panel">
<check-list><div class="inner">Hello</div></check-list>
</div>
So .inner
is not direct child of .panel
因此, .inner
不是.inner
的直接.panel
.panel .inner{ background-color:blue; }
or this http://jsfiddle.net/zo9wk8gd/5/ 或这个http://jsfiddle.net/zo9wk8gd/5/
check-list >.inner{ background-color:blue; }
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. 因此选择器.panel > .inner
将无法应用CSS规则。
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>'
}
};
});
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.