Sunday 28 January 2018

custom directive in angularjs

step 1 : Controller

var myapp = angular.module("myapp", []);

myapp.controller('EmployeeCtrl', function ($scope) {
    $scope.Hamid = {};
    $scope.Hamid.Fname = "Hamid";
    $scope.Hamid.Lname = "Ali";

    $scope.Noor = {};
    $scope.Noor.Fname = "Noorul Huda";
    $scope.Noor.Lname = "Khan";
});

step 2 : custom directive


myapp.directive('EmployeeDir', function () {
    var directive = {};
    directive.restrict = 'E';
    directive.template = "{{student.Fname}}{{student.Lname}}";

    directive.scope = {
        student: "=name"
    }

    directive.compile = function (element, attributes) {
        element.css("border", "2px solid #ccccdd");

        var linkFunction = function ($scope, element, attributes) {
            element.html("Student First Name: <b>" + $scope.student.Fname + "</b> , Last Name: <b>" + $scope.student.Lname + "</b><br/>");
            element.css("background-color", "#gg00cc");
        }
        return linkFunction;
    }

    return directive;
});


Step 3 : apply on html


            <div ng-controller="EmployeeCtrl">
                <student name="Hamid"></student><br />
                <student name="Noor"></student>
            </div>






No comments:

Post a Comment