Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

AngularJs directives - how to get attributes values from within directive

Tags:

angularjs

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

like image 532
Ashraf Fayad Avatar asked Apr 30 '13 12:04

Ashraf Fayad


2 Answers

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.

like image 162
Mark Rajcok Avatar answered Sep 20 '22 17:09

Mark Rajcok


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 {{}}

like image 22
g00fy Avatar answered Sep 20 '22 17:09

g00fy