AngularJS 指令值

标签 angularjs angularjs-directive

我有一个 AngularJS 指令。我的指令仅限用作属性。但是,我想获取属性的值。目前,我的属性定义为:

angular.module('myDirectives.color', [])
    .directive('setColor', function () {
        return {
            retrict: 'A',
            link: {
                pre: function () {
                    console.log('color is: ');
                }
            }
        };
    })
;

我按以下方式使用该属性:
<button type="button" set-color="blue">Blue</button>
<button type="button" set-color="yellow">Yellow</button>

我知道我的指令正在被使用,因为我看到“颜色是:”但是,我不知道如何让它在控制台语句的末尾显示“蓝色”或“黄色”。我想获得该值,以便我可以进行条件处理。如何获取属性的值?

谢谢!

最佳答案

您可以使用链接函数的属性参数:

angular.module('myDirectives.color', [])
    .directive('setColor', function () {
        return {
            restrict: 'A',
            link: {
                pre: function (scope, element, attrs) {
                    console.log('color is: ' + attrs.setColor);
                }
            }
        };
    });

或者你可以像这样创建一个隔离范围:
angular.module('myDirectives.color', [])
    .directive('setColor', function () {
        return {
            restrict: 'A',
            scope: {
              setColor: '@'
            },
            link: {
                pre: function (scope) {
                    console.log('color is: ' + scope.setColor);
                }
            }
        };
    });

关于AngularJS 指令值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20710678/

相关文章:

angularjs - 为什么我可以从浏览器发出 REST API 请求,但不能从 Angular 的资源发出请求?

angularjs - Angular 凹坑错误 TypeError : Cannot read property '_hasCategories' of null

angularjs-directive - Angular2 n - 获取无效参数 [object Object] ... 对于管道 'AsyncPipe'

angularjs - 如何将数据从父元素的指令传递到子元素?

javascript - 如何将自定义指令属性值绑定(bind)到 Angular 中的隔离范围

angularjs - ng-click 首先应用类,然后执行函数

javascript - 将 $watch 设置为作用域变量会导致监视代码立即执行,如何避免?

javascript - 使用 Angular Js 从 API 获取 Json 数据

javascript - 使用循环定义许多 Angular 指令

angularjs - 绑定(bind) Controller : Object in directives