Search code examples
javascriptangularjsangularjs-scopemodal-dialog

using a modal to invoke a function from the parent scope (angular)


I have a main.controller.js and within that controller, i have a modal that i want to use to notify the user of a warning before continuing to the rest of the application.

so for example...i want to invoke my fileNew function from the modal

main.controller.js:

    $scope.warningModal = function() {
                $modal.open({
                  animation: true,
                  templateUrl: "./modal.html",
                  controller: "modalController",
                });
          };
    $scope.fileNew = function(type, subject, application) {
        newApplication(type, subject, application)
          $state.go('submissions');
        });
      };

main.html:

<li><a ng-click="warningModal()">New app</a></li>

modal.html:

<div class="modal-body">
  <p>warning message</p>
</div>
<div class="modal-footer clearfix">
  <button class="pull-right btn btn-primary" ng-click="$parent.fileNew()">Continue</button>
</div>

modalController:

$scope.$parent.fileNew();

giving me a warning message in the console saying..$scope.$parent.fileNew is not a function.

any ideas?

EDIT:

one more quick question around this idea...

i have 3 different types of fileNew applications that i want to file...

so in my main controller.js:

$scope.fileNew = function(type, subject, application) {
        newApplication(type, subject, application)
          $state.go('submissions');
        });
      };
$scope.fileOld = function(type, subject, application) {
        newApplication(type, subject, application)
          $state.go('submissions');
        });
      };
$scope.fileEdit = function(type, subject, application) {
        newApplication(type, subject, application)
          $state.go('submissions');
        });
      };

is there any way that i can pass which one im clicking on for the same continue button on the modal?


Solution

  • In recent versions of Angular UI Bootstrap, you can include a scope option where you can pass a scope you want to be available inside your modal controller:

    $scope.warningModal = function() {
      $modal.open({
         animation: true,
         scope: $scope,
         templateUrl: "./modal.html",
         controller: "modalController",
      });
    };
    

    So now you can just call your function from within modalController:

    $scope.fileNew(type, subject, application);