Ben Foster
Ben Foster

Reputation: 34800

Angular Directive attributes contain additional properties

I've created a custom directive which uses the element's attributes to build a string. When I enumerate the link function's attrs parameter I found it also contains angular properties $$element and $attr. What is the purpose of these? Currently I'm having to filter these out like so:

var app = angular.module('demo', []);
app.directive('imgTransform', function () {
    return {
        restrict: 'E',
        template: '<img src="{{uri}}" alt="{{title}}" />',
        scope: {},
        link: function (scope, element, attrs) {


            angular.forEach(attrs, function (value, key) {
                if (key.charAt(0) !== '$') {
                }
            });

        }
    };
});

Upvotes: 2

Views: 738

Answers (1)

Ilan Frumer
Ilan Frumer

Reputation: 32377

From Attributes docs:

A shared object between directive compile / linking functions which contains normalized DOM element attributes

This object is more than just a key value hashmap, it also has methods that it inherits from the Attributes class through it's prototype. The reason why it has the $attrs and $$elements properties is to give the right context (element/attributes) to these methods :

this.$$elements
this.$attr

BTW, every property with a $$-prefix in angular.js is an undocumented private property, and should not be used externally. javascript doesn't support real private methods/properties so angular uses this convention.

See this example:

enter image description here

Looking further in the docs:

$attr

object: A map of DOM element attribute names to the normalized name. This is needed to do reverse lookup from normalized name back to actual name.

Fortunately, you can use attrs.$attr like so:

 angular.forEach(attrs.$attr, function (value, key) {
    attrs[key] // <---

Upvotes: 3

Related Questions