Friday, 30 September 2016

How to create Directives in AngularJs

AngularJS: Directives are the most important components of any AngularJS application.It can help you to manage your code elegantly. If you already use Angular for a while, you must be familiar with ng-model, ng-click, ng-repeat and ng-show. All these directives attach special behavior to DOM elements. For example, ng-repeat repeats a specific element and ng-show conditionally shows an element.

AngularJS Directives


AngularJS directives are extended HTML attributes with the prefix ng-.

ng-app : It is initializes an AngularJS application.

ng-init: It is initializes application data.

ng-model: It is binds the value of HTML controls (input, select, textarea) to application data.

<div ng-app="" ng-init="firstName='John'">

<p>Name: <input type="text" ng-model="firstName"></p>
<p>You wrote: {{ firstName }}</p>

</div>

How to Specify Directive in HTML: In AngularJS you can create directive as an element, class names, attribute and even comment. In below example teach you how directive can be initialised in html. I use “want-code” as my directive name.

<want-code></want-code> 
<div want-code></div>
<div class="want-code"></div>
<!-- directive: want-code -->

You can also use the directive like this.We use dash delimited for attribute directive because it is good practise.

<div want:code></div>
<div want_code></div>
<div want-code></div>
<div x-want-code></div>

How to create custom Directive in AngularJS:

// yourscript.js
...
.directive('userProfile', function() {
  return {
    template: 'Name: {{ user.name }} <br /> Gender: {{ user.gender }}   <br /> Phone: {{ user.phone }}'
  };
});

We define the user model inside the controller below.

// yourscript.js
...
.controller('MainCtrl', ['$scope', function($scope) {
  $scope.user = {
    name: 'John',
    gender: 'Male',
    phone: '919999999999'
  };
}])
...

Basically, it will display a template that contains user information using Angular binding.For Html it will defined as.

<user-profile></user-profile>

You may notice that we use dash delimited instead of camel cased (userProfile) for directive name in HTML. It is because HTML is not case sensitive so it doesn’t recognize camel cased.


Featured post

How to create dynamic schema in mongodb

Sometime what we need in our application is to create mongodb schema for collection and some of our collection schema are same but names are...

Popular Posts