Skip to main content
Ben Nadel
On User Experience (UX) Design, JavaScript, ColdFusion, Node.js, Life, and Love.

Inspecting Attribute-Normalization Within Directives In AngularJS

By Ben Nadel on

This is a small but rather important post. I never noticed this before, but the attributes collection, that gets injected into the compile and link functions in an AngularJS directive, contains an "$attr" object. This object maps the normalized attribute names onto the attribute names used in the HTML markup. This is super useful when it comes to stripping out attributes during compilation or selecting on attributes during linking.

To see what I mean, I've created several directives that get bound using the various attribute syntaxes that AngularJS supports:

  • bn-one
  • data-bn-two
  • x-bn-three
  • bn:four

When AngularJS goes to compile and link the directive, it will pass-in these attributes as normalized headless camel-case values. But, we can use the $attr map to see what was actually done in the HTML:

<!doctype html>
<html ng-app="Demo">
	<meta charset="utf-8" />

		Inspecting Attribute-Normalization Within Directives In AngularJS

		Inspecting Attribute-Normalization Within Directives In AngularJS

		bn-one="Some value."
		data-bn-two="Some value."
		x-bn-three="Some value."
		bn:four="Some value.">
		This is my directive!

	<!-- Load scripts. -->
	<script type="text/javascript" src="../../vendor/jquery/jquery-2.1.0.min.js"></script>
	<script type="text/javascript" src="../../vendor/angularjs/angular-1.2.16.min.js"></script>
	<script type="text/javascript">

		// Create an application module for our demo.
		var app = angular.module( "Demo", [] );

		// -------------------------------------------------- //
		// -------------------------------------------------- //

		// Define each of our directives - they all use the same logic.
			[ "bnOne", "bnTwo", "bnThree", "bnFour" ],
			function( hook ) {

					function() {

						function link( $scope, element, attributes ) {

							// The [attributes] collection is keyed on the normalized
							// value of the directive. But, it contains the $attr
							// collection, which maps the normalized value to the actual
							// attribute notation defined by the developer.
								"%s defined as %c %s ",
								"background-color: yellow; font-weight: bold ;",
								attributes.$attr[ hook ]


						// Return the directive configuration.
							link: link





When we run this code, we get the following output:

Inspecting the normalized attribute values within a directive in AngularJS.

As you can see, we can easily determine how our normalized attributes appear in the DOM (Document Object Model) tree. This means we can reference those attributes without having to worry about all the variations that the developer might use.

Reader Comments