[AngularJS] How to create Directives?

Directives are the reusable UI components in AngularJS. In this blog, i will show you how to create custom directives in AngularJS.

var app = angular.module(‘App‘, []);

app.directive(‘hi‘, function() {
    return {
        template: ‘<h2>Hi There</h2>‘,
        replace: true
    };
});

app.directive(‘hello‘, function() {
    return {
        template: ‘<h2>Hello There</h2>‘,
        replace: true
    };
});

app.directive(‘customDirective‘, function($compile) {
    return {
        template: ‘<a ng-click="addType(\‘hi\‘)">Add Hi</a><br/><a ng-click="addType(\‘hello\‘)">Add Hello</a><div class="holder">‘,
        link: function(scope, element, attr) {
            scope.addType = function(type) {
                var el = $compile(‘<div ‘ + type + ‘></div>‘)(scope);
                $(‘.holder‘, element).append(el);
            }
        }
    };
});


郑重声明:本站内容如果来自互联网及其他传播媒体,其版权均属原媒体及文章作者所有。转载目的在于传递更多信息及用于网络分享,并不代表本站赞同其观点和对其真实性负责,也不构成任何其他建议。