Skip to content

Instantly share code, notes, and snippets.

@kasajian
Last active August 29, 2015 14:01
Show Gist options
  • Save kasajian/0e9c6ec44a29ca001595 to your computer and use it in GitHub Desktop.
Save kasajian/0e9c6ec44a29ca001595 to your computer and use it in GitHub Desktop.
Angular directive with shared controllers and nesting

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('नमस्ते');
        }
    };
}]);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment