Sunday, June 15, 2014

Angular Directives Part 5 - Angular directive with shared controllers


HTML - Option 1:

<greeting hindi finnish />

HTML - Option 2:

<!--Can be nested--> <greeting> <div hindi finnish></div> </greeting>

JavaScript:


angular.module('app').directive('greeting', [function () {
    return {
        restrict: 'E',
        replace: true,
        transclude: true,
        template: "<div><button class='btn' ng-click='sayHello()'>Say Hello</button><div ng-transclude></div></div>",
        controller: function ($scope) {
            var greetings = ['hello'];
            $scope.sayHello = function () {
                alert(greetings.join());
            }

            // Let's add on this controller a way to add different greetings.
            this.addGreeting = function (greeting) {
                greetings.push(greeting);
            }
        }
    };
}]);


angular.module('app').directive('finnish', [function () {
    return {
        restrict: 'A',

        // The ^ tells Angular to support this direcitve being nested in the specified directive.
        require: '^greeting', // << require a name of a directive that has a controller in it.
                            // "In order to use this 'finnish' directive, i'm going require that there
                            // be another directive called 'greeting' and that 'greeting' controller needs
                            // to have a controller on it, which will become the shared controller for
                            // these directives.   Also, needs to be on the same element.
        // The link function gets called for every instance of this directive.
        link: function (scope, element, attrs, controller) { // The link function gets called for every instance of this directive.
            controller.addGreeting('hei');
        }
      };
}]);

angular.module('app').directive('hindi', [function () {
    return {
        restrict: 'A',
        // The ^ tells Angular to support this direcitve being nested in the specified directive.
        require: '^greeting', // << require a name of a directive that has a controller in it.
        link: function (scope, element, attrs, controller) { // The link function gets called for every instance of this directive.
            controller.addGreeting('%u0928%u092E%u0938%u094D%u0924%u0947');
        }
    };
}]);

No comments: