[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);
            }
        }
    };
});


[AngularJS] How to create Directives?

上一篇:Web开发从零开始


下一篇:VC与JavaScript交互(一) ———— 如何实现