Ashraf Fayad
Ashraf Fayad

Reputation: 1492

AngularJs directives - how to get attributes values from within directive

Any idea how to access attributes values from inside the directive?

    angular.module('portal.directives', [])
        .directive('languageFlag', ['$routeParams', function(params) {
            return function(scope, element, attrs) {
                console.log(attrs["data-key"]); // returns undefined
                console.log(element.attr('data-key')); // returns {{data-key}}
                angular.element(element).css('border', '1px solid red');
            };
        }]);

Html code is:

<ul>
    <li ng-repeat="lng in flags">
        <a class="lngFlag {{flag.Key}}" data-key="{{flag.Key}}" data-id="{{lng.Id}}" ng-click="changeLangHash({'lng':lng.Id })" language-flag></a>
    </li>
</ul>

Thanks

Upvotes: 16

Views: 53349

Answers (5)

Chris Lambrou
Chris Lambrou

Reputation: 356

Another issue I discovered is that $attr will convert attribute names to lower-casing.

<input myTest="test" />

Value can be obtained with this... attr["mytest"]

i.e.

...link: function (scope, element, attr) { console.log(attr["mytest"]); ...}

Upvotes: 0

MikeT
MikeT

Reputation: 2663

angular strips 'data-' off any attributes, so if your attribute is 'data-key', just use 'key', not 'dataKey'

Upvotes: 4

Mickey Puri
Mickey Puri

Reputation: 889

I would suggest using object notation if you are inside the link function of the directive, which gets the attrs parameter:

attrs.yourAttributeName

Upvotes: 1

Mark Rajcok
Mark Rajcok

Reputation: 364687

Use $observe:

Observing interpolated attributes: Use $observe to observe the value changes of attributes that contain interpolation (e.g. src="{{bar}}"). Not only is this very efficient but it's also the only way to easily get the actual value because during the linking phase the interpolation hasn't been evaluated yet and so the value is at this time set to undefined. -- directives doc

return function(scope, element, attrs) {
    attrs.$observe('key', function(value) {
        console.log('key=', value);
    });
}

As @FMM mentioned in a comment, data is stripped by Angular when it normalizes the attribute name, hence the use of key above, rather than dataKey.

Upvotes: 23

g00fy
g00fy

Reputation: 4737

try attrs["dataKey"] - this is the way that html parses attributes with dash (-). if you want the value from the scope instead of {{something}}, you can do two things:

scope[attrs['dataKey']] - will work but shouldn't do this

or use $parse but then don't use ``{{}}`

app.directive('languageFlag', ['$routeParams','$parse', function(params,$parse) {
  return function(scope, element, attrs) {
    var value =  $parse(attrs.dataKey)(scope);
    console.log(value);
    angular.element(element).css('border', '1px solid red');
  };
}]);

or you can use $interpolate the same way like $parse but with {{}}

Upvotes: 10

Related Questions