将参数传递给没有控制器的指令

Pass parameters to a directive without a controller

本文关键字:控制器 指令 参数传递      更新时间:2023-09-26

我有一个非常基本的指令,该指令包含一个模板。在模板中有一个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属性,请使用scope。

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>