0

I have a question concerning the visibility of function beween controllers and directives. I have a controller and a directive. The directive looks like this way

(function() {
'use strict';

angular
    .module('myproject.schedule')
    .directive('dirname', dirname);

function dirname() {
  var directive = {
        restrict: 'A',
        replace: true,
        scope: {
            currentDateScheduler: "=",
            ...
        },
        controller: DirnameController,
        controllerAs: 'vm',
        bindToController: true,
        templateUrl: ... directive.html

My controller looks like this:

(function() {
'use strict';

angular
    .module('myproject.schedule')
    .controller('MyController', MyController);
...

In the directive.html file I have a ng-click which invoked functions of my controller - and this works fine.

Actually now I am not sure why? I thought that a directive has its own namespace and the functions of my controller is not visible in ... directive.html.

Thanks a lot your help!

2
  • 2
    Show how you call functions in ngClick. Commented Sep 27, 2015 at 7:19
  • Post a complete minimal example. Commented Sep 27, 2015 at 7:19

1 Answer 1

0

Controller scope is available to any directive that appears as a child within the DOM element on which the controller is declared. E.g.

<div ng-controller="ctrl1">
    <dirname></dirnam> <!-- this has access to ctrl1 scope -->
</div>

So if you were to use the directive within another controller it would have access to that controllers scope. This means that if the function doesn't exist in the controller that the directive declared under then the ng-click will do nothing.

In the directive you can declare a controller, anything declared in this controller will override the controller function of the same name within the directive. E.g.

angular.module('myApp',[])
.controller('myController',function($scope){
    $scope.clickMe = function(){
       alert('clicked from the controller');
    }
})
.directive('dirname', function(){
    return {
        controller: function($scope){
            $scope.clickMe = function(){ alert('clicked from directive'); };
        },
    };
});

controllers can also be nested. In this case the scope again has a top down effect, whereby a function defined in the top most controller is available to the dom elements enclosed in a child controller. Also if this child controller has the same function declared then these will override the functionality of the parent controller.

Hope this helps

Sign up to request clarification or add additional context in comments.

1 Comment

Thanks a lot! This helps really a lot!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.