javascriptangularjsbootstrap-ui

How to close $uibModal from a function if modal is attached to the same scope?


I receive close is not a function when trying to close a modal window created by $uibModal.open()

I have reduced the problem to minimal code:

    var app = angular.module('demoApp', ['ui.bootstrap']);

    app.controller('DemoContrller', function($scope, $uibModal) {
      var vm = this;
      var myModalInstance = null;

      vm.openModal = function() {

        myModalInstance = $uibModal.open({
                  animation: true,
                  templateUrl: 'modalTemplate.html',
                  scope: $scope // important - want to reuse current scope and controller and not create new
              }).result.then(function() {
                  console.log('fully closed with successful validation');
              });

      };


      vm.onApplyModal = function() {

          console.log('doing some validation and closing only if succeeded');

          // ??? close is not a function, myModalInstance is a Promise

          console.log(myModalInstance);
          myModalInstance.close();
      };

    })

Please see my Plunk here: Cannot close uibmodal from a function in the same scope


Solution

  •  myModalInstance = $uibModal.open({
                      animation: true,
                      templateUrl: 'modalTemplate.html',
                      scope: $scope // important - want to reuse current scope and controller and not create new
                  }).result.then(function() {
                      console.log('fully closed with successful validation');
                  });
    

    First assign variable, then chain:

     myModalInstance = $uibModal.open({
                      animation: true,
                      templateUrl: 'modalTemplate.html',
                      scope: $scope // important - want to reuse current scope and controller and not create new
                  });
    myModalInstance .result.then(function() {
                      console.log('fully closed with successful validation');
                  });