[英]Pass parameters to a directive without a controller
我有一个非常基本的指令,该指令包括一个模板。 模板中有一个color
变量,用于设置所加载内容的背景色。
app.directive('percentageSquare', function(){
return {
restrict: 'E',
templateUrl: '/templates/dashboard/charts/PercentageChart.html'
};
});
我可以在指令中设置颜色吗? 我在想也许是这样的:
<percentage-square color="red"></percentage-square>
模板如下所示:
<div style="background-color: {{color}}">
<h1>I am a cool color!</h1>
</div>
当我查看所有可以找到的是控制器中设置的值(在指令外部)时,是否可以通过仅通过HTML传递值来做到这一点?
使用隔离范围 。 指令的scope
属性表示您正在从指令外部绑定某些值。 或者,您可以将其视为传递给指令的parameters
。
查看JSFiddle工作演示: http : //jsfiddle.net/0547gjzs/1/ 。
app.directive('percentageSquare', function(){
return {
restrict: 'E',
scope: {
color: '@'
}
templateUrl: '/templates/dashboard/charts/PercentageChart.html'
};
});
HTML:
<percentage-square color="red"></percentage-square>
如果访问指令的color属性,请使用作用域。
app.directive('percentageSquare', function(){
return {
restrict: 'E',
scope : {
color : "@"
},
/*templateUrl: '/templates/dashboard/charts/PercentageChart.html'*/
template : "<div style='background-color : {{color}}'><h1>I am a cool color!</h1></div>"
};
});
使用相同的方式来使用templateUrl文件。
这是您的自定义指令定义
<percentage-square color="red"></percentage-square>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.