What are directives? How to create and use custom Directive in AngularJS .

devquora
devquora

Posted On: Feb 22, 2018

 

In angular Directives are used to extend the attributes of Html elements.
Creating custom directive in Angular js.
Angular js Directives are restricted to element and attribute and created using a directive function.Here is sample code to create a directive in Angular js.


var app = angular.module("myApp", []);
app.controller('AppController', function($scope) {
    var users=[];
    var user1={};
    user1.firstName="Satyam";
    user1.lastName="Kumar";
    users.push(user1);
    var user2={};
    user2.firstName="Ravi";
    user2.lastName="Sankar";
    user2.push(user2);
    $scope.users=students;
});
app.directive('user', function() {
    //define the directive object
    var directive = {};
    //restrict = E, implies that directive is Element directive
    directive.restrict = 'E';
    //element will be replaced by this text/html
    directive.template = "First Name: {{user.firstName}} , Last Name: {{user.lastName}}";
    var linkFunction = function($scope, element, attributes) {
        element.css("background-color", "#e1e1e1");
    }
    directive.link=linkFunction;
    return directive;
});

As Above directive is restricted to Element directive, so you can use this directive as an element only.
Usage:


<div ng-app="app">
 <h1>Custom Directive Demo</h1>
 <div ng-controller="UserController">
 <div ng-repeat="user in users">
 <user></user>
 </div>
 </div>
</div>

    Related Questions

    Please Login or Register to leave a response.

    Related Questions