Wednesday, November 4, 2015

AngularJS - Directives

What are Directives?

At a high level, directives are markers on a DOM element (such as an attribute, element name, comment or CSS class) that tell AngularJS's HTML compiler ($compile) to attach a specified behavior to that DOM element (e.g. via event listeners), or even to transform the DOM element and its children.
Angular comes with a set of these directives built-in, like ngBind, ngModel, and ngClass. Much like you create controllers and services, you can create your own directives for Angular to use. When Angular bootstraps your application, the HTML compiler traverses the DOM matching directives against the DOM elements.

Matching Directives

Before we can write a directive, we need to know how Angular's HTML compiler determines when to use a given directive.
Similar to the terminology used when an element matches a selector, we say an element matches a directive when the directive is part of its declaration.

In the following example, we say that the <input> element matches the ngModel directive
<input ng-model="foo">
 
The following <input> element also matches ngModel:
<input data-ng-model="foo">

And the following element matches the person directive:
<person>{{name}}</person>
 
 

Normalization

Angular normalizes an element's tag and attribute name to determine which elements match which directives. We typically refer to directives by their case-sensitive camelCase normalized name (e.g. ngModel). However, since HTML is case-insensitive, we refer to directives in the DOM by lower-case forms, typically using dash-delimited attributes on DOM elements (e.g. ng-model).
The normalization process is as follows:
  1. Strip x- and data- from the front of the element/attributes.
  2. Convert the :, -, or _-delimited name to camelCase.


For example, the following forms are all equivalent and match the ngBind directive:

-----------------------------------
index.html
------------------------------------
<!doctype html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <title>Example - example-example10-production</title>
 

  <script src="//ajax.googleapis.com/ajax/libs/angularjs/1.5.0-beta.1/angular.min.js"></script>
  <script src="script.js"></script>
   
</head>
<body ng-app="docsBindExample">
  <div ng-controller="Controller">
  Hello <input ng-model='name'> <hr/>
  <span ng-bind="name"></span> <br/>
  <span ng:bind="name"></span> <br/>
  <span ng_bind="name"></span> <br/>
  <span data-ng-bind="name"></span> <br/>
  <span x-ng-bind="name"></span> <br/>
</div>
</body>
</html>

 ------------------
 script.js
----------------------


(function(angular) {
  'use strict';
angular.module('docsBindExample', [])
  .controller('Controller', ['$scope', function($scope) {
    $scope.name = 'Max Karl Ernst Ludwig Planck (April 23, 1858 – October 4, 1947)';
  }]);
})(window.angular);











 

No comments:

Post a Comment