Saturday, June 14, 2014

Angular Directives Part 4 - Angular directives with Controllers


HTML

    <div>
        <greeting1 />
    </div>
    <div>
        <greeting2 />
    </div>
    <div>
        <greeting3 greeting-controller="greetingController3" />
    </div>

JavaScript

// Controller's built-in to the directive.
angular.module('app').directive('greeting1', [function () {
    return {
        restrict: 'E',
        replace: true,
        template: "<button class='btn' ng-click='sayHello1()'>Say Hello</button>",
        controller: function($scope) {
            $scope.sayHello1 = function() {
                alert('Hello1');
            }
        }
    };
}]);

// Controller's specified externally.
angular.module('app').directive('greeting2', [function () {
    return {
        restrict: 'E',
        replace: true,
        template: "<button class='btn' ng-click='sayHello2()'>Say Hello2</button>",
        controller: 'greetingController2'
    };
}]);

angular.module('app').controller('greetingController2', ['$scope', function ($scope) {
    $scope.sayHello2 = function() {
        alert('Hello2');
    };
}]);

// Controller's specified explictly via attribute.
angular.module('app').directive('greeting3', [function () {
    return {
        restrict: 'E',
        replace: true,
        template: "<button class='btn' ng-click='sayHello3()'>Say Hello3</button>",
        controller: '@', // This means the controller is specified via HTML
                         // in the attribute whose name is indicated in the name property of this object
        name: 'greetingController' // The attribute name that contains the name of the controller.
    };
}]);

angular.module('app').controller('greetingController3', ['$scope', function ($scope) {
    $scope.sayHello3 = function () {
        alert('Hello3');
    };
}]);

No comments: