AngularJS Directive Value

浪子不回头ぞ 提交于 2019-12-05 13:06:47

问题


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?

Thank you!


回答1:


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);
                }
            }
        };
    });


来源:https://stackoverflow.com/questions/20710678/angularjs-directive-value

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!