Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/javascript/453.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Javascript 将参数传递给不带控制器的指令_Javascript_Angularjs - Fatal编程技术网

Javascript 将参数传递给不带控制器的指令

Javascript 将参数传递给不带控制器的指令,javascript,angularjs,Javascript,Angularjs,我有一个非常基本的指令,该指令包括一个模板。模板中有一个color变量,用于设置加载内容的背景色 app.directive('percentageSquare', function(){ return { restrict: 'E', templateUrl: '/templates/dashboard/charts/PercentageChart.html' }; }); 我有没有办法在指令中设置颜色?我在想可能是这样的: <perce

我有一个非常基本的指令,该指令包括一个模板。模板中有一个
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>

模板如下所示:

<percentage-square color="red"></percentage-square>
<div style="background-color: {{color}}">
    <h1>I am a cool color!</h1>
</div>

我是一个很酷的颜色!
当我在查看控制器中设置的值时(在指令之外),是否有一种方法可以通过HTML传递一个值来实现这一点?

使用。指令的
scope
属性意味着您正在从指令外部绑定一些值。或者,您可以将其视为传递给指令的
参数

检查JSFIDLE工作演示:

HTML:


如果访问指令的颜色属性,请使用范围

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>"
    };
});
app.directive('percentageSquare',function(){
返回{
限制:'E',
范围:{
颜色:“@”
},
/*templateUrl:“/templates/dashboard/charts/PercentageChart.html”*/
模板:“我是一个很酷的颜色!”
};
});
使用相同的方法使用templateUrl文件

这里是您的自定义指令定义

<percentage-square color="red"></percentage-square>


您正在查找。在模板中,我有来自另一个作用域的数据,添加该作用域似乎覆盖了另一个作用域…是的。您也可以通过
@
=
&
另一个作用域中的数据绑定到此指令。在我看来,指令通过其隔离范围更好地与其他指令交互。它使该指令在不同的页面上可重用。