Skip to content Skip to sidebar Skip to footer

Using The Angularjs Require Option To Call Into Another Directive

I was just reading here about accessing one directive's controller from within another directive via the require option: http://jasonmore.net/angular-js-directives-difference-con

Solution 1:

Here is an example of "parent" directive dashboard requiring droppable, and communication between the two making use of require and passing dashboardCtrl

Here is a good article to see directive to directive communication

Fiddle example also built from your previous question

JSFiddle

app.directive('droppable', [function () {
    return {
        restrict: 'A',
        require: 'dashboard',
        link: function (scope, elem, attrs, dashboardCtrl) {

            dashboardCtrl.controllerSpecificFunction('hello from child directive!');

            scope.addWidgetInternal = function(message) {
                console.log(message);
            }
        }
    }
}]);

app.directive('dashboard', [function () {
    return {
        restrict: 'A',
        controller: function ($scope) {
            $scope.handleDrop = function(message) {
                $scope.addWidgetInternal(message)
            }

            this.controllerSpecificFunction = function(message) {
                console.log(message);
           }
        }
    }
}]);

Edit

Based on discussion, here is a solution for what I currently understand the problem to be

Parent directive dashboard optionally requires child directive droppable and there needs to be communication between the two

<div dashboard>
    <button id="dash" droppable ng-click="handleDrop($event)">Handle Drop</button>
</div>

app.directive('droppable', [function () {
    return {
        restrict: 'A',
        require: '^?dashboard',
        link: function (scope, elem, attrs, dashboardCtrl) {
            scope.handleDrop = function($event) {
                dashboardCtrl.addWidgetInternal($event);
            }
        }
    }
}]);

app.directive('dashboard', [function () {
    return {
        restrict: 'A',
        controller: function ($scope) {
            this.addWidgetInternal = function($event) {
                console.log($event);
           }
        }
    }
}]);

Updated JSFiddle

Post a Comment for "Using The Angularjs Require Option To Call Into Another Directive"