AngularJS 指令值 [英] AngularJS Directive Value

查看:24
本文介绍了AngularJS 指令值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I have an AngularJS directive. My directive is restricted to be used as an attribute. However, I want to get the value of the attribute. Currently, I have my attribute defined as:

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

我以下列方式使用该属性:

I use the attribute in the following manner:

<button type="button" set-color="blue">Blue</button>
<button type="button" set-color="yellow">Yellow</button>

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

I know that my directive is being used because I see 'color is: ' However, I can't figure out how to make it display 'blue' or 'yellow' at the end of that console statement. I want to get that value so I can do a conditional processing. How do I get the value of the attribute?

谢谢!

推荐答案

可以使用链接函数的attributes参数:

You can use the attributes argument of the link function:

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

或者你可以像这样创建一个隔离范围:

or you could create an isolate scope like this:

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

这篇关于AngularJS 指令值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆