3
votes

In my ui-bootstrap modal controller I $watch variable. It looks something like this:

main.controller('modalCtrl', ['$scope', '$rootScope', '$modalInstance', 
    function ($scope, $rootScope, $modalInstance) {

        var unregister = $rootScope.$watch(function () { return $rootScope.someVariable; },
                          function (newVal) {
                              if (newVal == false) {
                                  $scope.closeModal();
                              }

                          });
        $scope.closeModal = function () {
            unregister();
            $modalInstance.dismiss('cancel');
        };
}]);

When i dismiss modal I want to unregister $watch and when I do that on ng-click="closeModal()" in HTML it works fine. But when I dismiss modal on ESC on click outside of modal it isn't working. So is there any way to call my unregister function on dismiss. I know for modal.result.then(close(),dismiss()); but if it's not necessary I don't want to put that func into parent $scope.

2

2 Answers

2
votes

Just add one more then callback to the result promise with unregister:

main.controller('modalCtrl', ['$scope', '$rootScope', '$modalInstance', function ($scope, $rootScope, $modalInstance) {

    var unregister = $rootScope.$watch(function () {
        return $rootScope.someVariable;
    }, function (newVal) {
        if (newVal == false) {
            $scope.closeModal();
        }
    });

    $scope.closeModal = function () {
        $modalInstance.dismiss('cancel');
    };

    $modalInstance.result.then(null, unregister);
}]);

In this case unregister will be called on both closeModal and on escape key. By the way, you can get rid of $scope.closeModal all together and use ng-click="$dismiss('cancel')" in template instead.

0
votes

First off, you really shouldn't be storing anything on $rootScope - ESPECIALLY a watched variable used to close your modal. What problem are you trying to solve (and what UX are you trying to accomplish) by wanting to close your modal via some watched variable? This does not pass the smell test for me and something is odd in your intended design.

Secondly, your line about not wanting to use the resolved promise doesn't make sense. When you call $modal.open(options), that returns an object, say modalInstance on which you then call your promise callback. Thus, the promise callback exists within the same context as your modalInstance and any data you may have passed via options.

See our documentation here for examples on how to properly use the $modal service.