AngularJS > Directives

Custom directive in AngularJS

How to create custom directive in AngularJS?


To create custom directive in AngularJS, we can use module.directive method / API. It takes normalized directive name (in camelCase not separated by "-") followed by factory function that gets executed based on what parameter is passed to it.

<script>
    var app = angular.module("app", [])
    .controller("CustomDirectiveController", function ($scope) {
        $scope.username = "SheoNarayan";
        $scope.address = "Hyderabad, India";
    });

    app.directive('myCustom', function () {
        return {
            template: ' UserName: {{ username }}, Address: {{ address }}'
        };

    });    
</script>

<div ng-app="app" ng-controller="CustomDirectiveController">
    <p> <b>Using bind:</b> {{ username + ', ' + address }}</p>
    <p> <b>Using directive :</b> <span my-custom></span></p>
</div>

In above case, notice the highlighted code in <script> block that created a directive name "myCustom" (normalized name) "my-custom" ( "-" separated that is recommended) that returns a template with the value of Username and Address of the $scope property.

In the HTML block, we are using that directive (my-custom) that simply prints the data returned from the function attached to it in the directive function.

Output

Custom directive in AngularJS

 Views: 14033 | Post Order: 34




Write for us






Hosting Recommendations