简体   繁体   English

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

[英]Pass parameters to a directive without a controller

I have a very basic directive, and the directive includes a template. 我有一个非常基本的指令,该指令包括一个模板。 In the template there is a color variable to set the background color of what is loaded. 模板中有一个color变量,用于设置所加载内容的背景色。

app.directive('percentageSquare', function(){
    return {
        restrict: 'E',
        templateUrl: '/templates/dashboard/charts/PercentageChart.html'
    };
});

Is there a way for me to set the color in my directive? 我可以在指令中设置颜色吗? I was thinking maybe something like this: 我在想也许是这样的:

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

The template would look like this: 模板如下所示:

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

As I was looking all I could find was the values set in the controller (outside of the directive), is there a way I can do this by just passing a value through the HTML? 当我查看所有可以找到的是控制器中设置的值(在指令外部)时,是否可以通过仅通过HTML传递值来做到这一点?

Use isolate scope . 使用隔离范围 The scope attribute of the directive means that you are binding some value from outside the directive. 指令的scope属性表示您正在从指令外部绑定某些值。 Or you can treat it as the parameters passed to the directive. 或者,您可以将其视为传递给指令的parameters

Check the JSFiddle working demo: http://jsfiddle.net/0547gjzs/1/ . 查看JSFiddle工作演示: http : //jsfiddle.net/0547gjzs/1/

app.directive('percentageSquare', function(){
    return {
        restrict: 'E',
        scope: {
            color: '@'
        }
        templateUrl: '/templates/dashboard/charts/PercentageChart.html'
    };
});

HTML: HTML:

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

Use scope if you access color attribute of your directive. 如果访问指令的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>"
    };
});

use same way to use templateUrl file. 使用相同的方式来使用templateUrl文件。

here your Custom Directive Define 这是您的自定义指令定义

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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