javascript - 将参数传递给没有 Controller 的指令

标签 javascript angularjs

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

正如我所寻找的那样,我所能找到的只是在 Controller 中设置的值(在指令之外),有没有一种方法可以通过 HTML 传递一个值来做到这一点?

最佳答案

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

检查 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>

关于javascript - 将参数传递给没有 Controller 的指令,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31437366/

相关文章:

javascript - AngularJS 中的 $scope 不起作用

javascript - 按值获取数组索引

javascript - Phonegap/AngularJS : Get lat/long from inside function

javascript - 鼠标悬停时jQuery透明图片描述幻灯片动画

javascript - JavaScript 中的 Gridview 行验证

javascript - 在 KnockoutJs 中对可观察数组进行排序时 UI 未更新

javascript - 如何通过javascript动态添加新按钮

javascript - 将多个库注入(inject) Angular 时出错

html - angular ng-options 指令最终选择了多个项目

javascript - 更改 angularJS 中指令的作用域变量