KGolbang
KGolbang

Reputation: 445

AngularJS - cannot access directive controller in another directive

I have two angularjs directives (extWindow and taskBar) and want to inject taskBar's controller into extWindow in order to access it's scope. Because they don't share the same scope I used

require : '^$directive'

syntax to include it. Doing so I could get rid of the error 'Controller 'taskBar', required by directive 'extWindow', can't be found!' but TaskBarCtrl is still undefined in link(..) method of the extWindow directive.

Any suggestions how to fix it?

var mod = angular.module('ui', [])
.directive('taskBar', function() {

    var link = function(scope, el, attrs) { 
        $(el).css('display', 'block');
        $(scope.titles).each(function(i,t) {
            el.append('<span>' + t + '</span>')
        });
    };

    return {
        scope: {},
        restrict : 'E',
        controller: function($scope, $element, $attrs) {

            $scope.titles = [];

            this.addTitle = function(title) {               
                $scope.titles.push(w);
            };

            this.removeTitle = function(title) {
                $scope.titles = jQuery.grep(function(n,i) {
                    return title != n;
                });
            }
        },
        link: link
    };
}).directive('extWindow', function() {  

    return {
        scope: {},
        require: '^?taskBar',
        restrict: 'E',
        transclude: true,
        template: '<div class="ui-window">\
            <div class="ui-window-header"><span>{{windowTitle}}</span><div class="ui-window-close" ng-click="close()">X</div></div>\
            <div class="ui-window-content" ng-transclude></div>\
            </div>',
        link: function(scope, element, attrs, taskBarCtrl) {
            scope.windowTitle = attrs['windowTitle'];   
            scope.close = function() {
                $(element).css('display', 'none');
            }
            //taskBarCtrl is not recognized!!!
            taskBarCtrl.addTitle(scope.windowTitle);
        }
    }
});

http://jsfiddle.net/wa9fs2nm/

Thank you. golbie.

Upvotes: 0

Views: 903

Answers (1)

Dylan
Dylan

Reputation: 4773

If you have a controller for your parent directive and you need something like.

this.scope = $scope;
this.attrs = $attrs;

And in your in you link function for the child you need something like

var Ctrl = ctrl || scope.$parent.tBarCtrl;

Here's a Plunker

Upvotes: 1

Related Questions