AngularJS: Custom Directives

by Raul Bojalil

HTML

<h4>Custom directives test</h4>
<div ng-app="testapp" ng-controller="CustomersController">
  <div my-directive></div>
  <div my-other-directive title="Click me!"></div>
</div>

JavaScript

var app = angular.module('testapp', []); 

app.controller('CustomersController', ['$scope', function ($scope) {

    $scope.customer = {
        name: 'Raúl',
        age: 25
    };

}]);

app.directive('myDirective', function () {
    return {
        template: 'Name: {{customer.name}}<br/> Age: {{customer.age}}'
    };
});

app.directive('myOtherDirective', function () {
    return {
        restrict: 'EA', //E = element, A = attribute, C = class, M = comment         
        //scope: false (Directive uses its parent scope)
        //scope: true (Directive gets a new scope)
        //scope: { } (Directive gets a new isolated scope)
        scope: {
            //@ (Text binding / one-way binding)
            //= (Direct model binding / two-way binding)
	          //& (Behaviour binding / Method binding)
            title: '@' 
        },
        template: '<div>{{ title }}</div>',
        //templateUrl: 'template.html', //To specify an HTML document with the template contents
        //controller: ['$scope', function ($scope) { $scope.test = "Hello";  }], //To embed a custom controller in the directive
        link: function ($scope, element, attrs) {  //To manipulate the DOM
        	element.bind('click', function () {
                element.html('You clicked me!');
            });
        } 
    }
});