Reputation: 34800
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
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.
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.
attrs.$attr
like so: angular.forEach(attrs.$attr, function (value, key) {
attrs[key] // <---
Upvotes: 3