Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

AngularJS Directive Value

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!

like image 901
user2871401 Avatar asked Dec 20 '13 19:12

user2871401


People also ask

What is @? In Angular directive scope?

These prefixes are used to bind the parent scope's methods and properties to the directive scope. There are 3 types of prefixes in AngularJS: '@' – Text binding / one-way binding. '=' – Direct model binding / two-way binding.

What are the directives of AngularJS?

AngularJS directives are extended HTML attributes with the prefix ng- . The ng-app directive initializes an AngularJS application. The ng-init directive initializes application data. The ng-model directive binds the value of HTML controls (input, select, textarea) to application data.

What is $$ in AngularJS?

The $ in AngularJs is a built-in object.It contains application data and methods.

What is Ng ATTR?

ng-attr is used for add or not the attribute in context. If the expression {{undefined || null}} , the attribute is not added otherwise if has a value then attribute is added with the value {{ value }} . The most common cases is in interpolation.


1 Answers

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);
                }
            }
        };
    });
like image 141
Austin Greco Avatar answered Oct 21 '22 22:10

Austin Greco