Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Calling parent scope function from directive

I am creating a directive that opens an angular bootstrap UI modal window. When closing the modal i would like to have a function executed that is passed from the attribute on the directive.. Here is what i have so far:

This is on the index.tpl.html :

<popup class="something" .. on-close="update()"></popup>

Directive code, only scope definition since there is a lot of code prior to this:

scope: {
         onClose: "&"
       },
link: function(scope, element, attr){
          //some code    
          ......
          scope.closeFn = function(){
               scope.onClose();
         }
         //opening of the modal:
         var modalInstance = $modal.open({
                   ....
                   templateUrl: 'path/to/template.tpl.html,
                   controller: 'PopupController',
                   scope: scope,
                   ....
         });

In the template of the popup i have a function binded to a close button that calls a function in the 'PopupController' that calls the closeFn from the directive link function like so.

<button type="button" class="btn-close btn btn-large" ng-click="closePopup()">Close
    </button>

And in the 'PopupController' :

$scope.closeUploadPopup = function () {
        $scope.$parent.closeFn();
        $modalInstance.close();
    };

As far as i understand the scope.onClose() should execute the function specified by the on-close attribute?

I have not provided a lot of code since there is a lot of the original code, but i can add more if it helps.

like image 817
Loshmeey Avatar asked May 25 '26 22:05

Loshmeey


1 Answers

You need to use proper API $modal service provides. Thus, modalInstance has a property promise which you can use to "subscribe" to get notified when popup closed ("Ok" button) or dismissed ("Cancel" button).

scope: {
    onClose: "&"
},
link: function(scope, element, attr) {
    // ... some code       
    var modalInstance = $modal.open({
        // ....
        templateUrl: 'path/to/template.tpl.html',
        controller: 'PopupController',
        scope: scope,
        // ....
    });

    modalInstance.result.then(function() {
        scope.onClose(); // close handler
    }, function() {
        // dismiss handler
    });

};

And in popup template use $close and $dismiss methods:

<button type="button" class="btn-close btn btn-large" ng-click="$close()">Close</button>
like image 91
dfsq Avatar answered May 28 '26 11:05

dfsq