Search code examples
javascriptangularjsangular-bootstrap

Can the controller of a modal window access functions in parent controller


Suppose you launch a modal window using $modal.open from within an angular directive.

Does the modal window have access to functions defined with the parent directive?

Directive controller code

..
function parentFunction()
{
     return 5;
}

$scope.showDialog = function()
{
     var dialog = $modal.open({
     controller: 'modalController',
     ...
}

'modalController' code

var val = parentFunction();


Solution

  • It won't have lexical scope access, but there are 2 ways (that I know of) to "pass data" to the controller, depending on what makes more sense to you:

    1) via $scope:

    $scope.parentFn = function parentFn(){
    };
    
    var dialog = $modal.open({
         controller: 'modalController',
         scope: $scope,
         //...
    });
    

    2) via resolve:

    function parentFn(){
    }
    
    var dialog = $modal.open({
         controller: 'modalController',
         resolve: {
           parentFn: function(){
             return parentFn;
           }
         },
         // ...
    });
    

    then you could get parentFn as a local injectable into the modalController:

    .controller("modalController", function(parentFn){
       parentFn();
    });
    

    Or...

    if you defined your controller inline, then it would have lexical scope access:

    function parentFn(){
    }
    
    var dialog = $modal.open({
         controller: function modalController(){
            parentFn();
         },
         // ...
    });