AngularJS指令值 [英] AngularJS Directive Value

查看:133
本文介绍了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?

感谢您!

推荐答案

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

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天全站免登陆