Question

I'm trying to close a modal when a promise is accepted from a Service, i can't figure it out: this is throwing an 'Can't read property value of undefined' ....

Change code for a plunker, I took this plunker from the angular.iu site, and added the dismiss line, you can see the error there

CHECK THE CONSOLE

Plunker Modal Dismiss Example

Was it helpful?

Solution

dismiss() can't be called on the modal instance until the modal is fully instantiated and opened. The error you're seeing is happening inside ui-bootstrap where it's trying to locate the opened modal in its internal collection but it's not in there yet.

open() returns a promise that is resolved when the modal has finished opening...

var modalInstance = $modal.open({ /* ... */ });

modalInstance.opened.then(function () {
    modalInstance.dismiss('dismiss');
});

Plunker

OTHER TIPS

In angular 1.6, if you don't handle the closing properly you will get an error like so "Possibly unhandled rejection: undefined". $uibModal.open returns a promise and if callbacks are not explicitly defined, the error will pop up in the console. In your case, you would want to handle the closing properly in the calling service or controller. For instance, if you have a button to emit an event and another controller has a listener, and in that listener should watch for that event. This is what you should do:

In the modal service:

.service('serviceModalName', function ($uibModal) {
      this.open = function () {
           var modalInstance = $uibModal.open({
                templateUrl: '',
                controller: 'serviceNameController'
           });
      };

      modal.result.then(function () {
          modal.dismiss();
      }, angular.noop);

});

In your Other Controller (where ever in your app), again, I presume the controller to the Modal Service, where $uibModalInstance is injected, will not call the close or dismiss functions. Rather could emit an event.

.controller('modalController', function ($scope) {
      $scope.close = function () {
          $scope.$emit('modal.closed.somewhere');
      }
});


.controller('someOtherController', function ($scope, serviceModalName) {

      var modalService = serviceModalName.open();

      $scope.$on('modal.closed.somewhere', function (e, args) {
             if (modalService) {
                  modalService.opened.then(function () {
                      modalService.close();
                  }, angular.noop);
             }
      };

}); 
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top