Search code examples
javascriptangularjsmodal-dialogangular-bootstraptransclusion

Angular transclude in a directive containing a ng-template (generic Confirm Modal)


Hello I'm struggling while creating a generic confirmation directive based on angular-bootstrap Modal directive.

I can't find a way to transclude my content in the ng-template used for the modal construction because the ng-transclude directive isn't evaluated since it's part of a ng-template loaded afterward when executing $modal.open() :

index.html (directive insertion) :

<confirm-popup
    is-open="openConfirmation"
    on-confirm="onPopupConfirmed()"
    on-cancel="onPopupCanceled()"
>
Are you sure ? (modal #{{index}})

confirmPopup.html (directive template) :

<script type="text/ng-template" id="confirmModalTemplate.html">
    <div>
        <div class="modal-header">
            <h3>Confirm ?</h3>
        </div>
        <div class="modal-body">
            {{directiveTranscludedContent}} // ng-transclude do not work here
        </div>
        <div class="modal-footer">
            <button class="btn btn-warning" ng-click="cancel()">Cancel</button>
            <button class="btn btn-primary" ng-click="ok()">Validate</button> 
        </div>
    </div>
</script>

confirmPopup.js (directive JS) :

.directive('confirmPopup', [
    function() {
        return {
            templateUrl: 'confirmPopup.html',
            restrict: 'EA',
            replace: true,
            transclude: true,
            scope: {
                isOpen: '=',
                confirm: "&onConfirm",
                cancel: "&onCancel"
            },
            controller: ['$scope', '$element', '$modal', '$transclude', '$compile', function($scope, $element, $modal, $transclude, $compile) {

              // watching isOpen attribute to dispay modal when needed
                $scope.$watch(
                    function() {
                        return $scope.isOpen;
                    },
                    function(newValue) {
                        if (newValue === true) {
                            openModal();
                        } else {
                            // if a modal is already dispayed : the modal must be canceled/confirmed by the user
                            // else (if no modal is dispayed), then do nothing
                        }
                    }
                );

                // open modal function
                // create / register ok/cancel callbacks
                // and open modal
                // all on one shot
                function openModal() {

                    $modal.open({
                        templateUrl: 'confirmModalTemplate.html',
                        controller: ['$scope', '$modalInstance', 'content', function($scope, $modalInstance, content) {

                            $scope.directiveTranscludedContent = content;

                            $scope.ok = function() {
                                $modalInstance.close();
                            };

                            $scope.cancel = function() {
                                $modalInstance.dismiss();
                            };
                        }],
                        resolve: {
                            content: function() {
                                return $transclude().html();
                                      //return $compile($transclude().contents())($scope);
                            },
                        }
                    })
                    .result.then(
                        // modal has been validated
                        function() {
                            $scope.confirm();
                        },
                        // modal has been dismissed
                        function() {
                            if ($scope.cancel) {
                                $scope.cancel();
                            }
                        }
                    );
                };
            }]
        };
    }
]);

If it's not clear enough, see this PLUNKER where I'm waiting to see "Are you sure ? (modal #2)" only when clicking on the "open confirm modal #2" button.


Solution

  • ui-bootstrap modal only supports either template or templateUrl as a way to specify the content. However the content is retrieved, it is compiled and linked against the provided scope by the $modal (or rather, the internal $modalStack) service.

    So, at least, like that, there is no way to provide transclusion.

    One way around, would be to embed a placeholder directive that would append the transcluded DOM - but the transcluded DOM, since it's coming from a location different than the modal, needs to be handed over somehow to that placeholder directive. You already have the content as an injected resolve parameter. I will use that with slight modification - I will pass the actual DOM, not the parsed HTML.

    So, at a high-level:

    .directive("confirmPopupTransclude", function($parse){
      return {
        link: function(scope, element, attrs){
          // could have been done with "=" and isolate scope, 
          // but avoids an unnecessary $watch
          var templateAttr = attrs.confirmPopupTransclude;
          var actualTemplateDOM = $parse(templateAttr)(scope);
    
          element.append(actualTemplateDOM);
        }
      };
    })
    

    And, in the openModal function (omitting unrelated properties):

    function openModal{
       $modal.open({
         controller: function($scope, content){
            $scope.template = content;
            // etc...
         },
         resolve: {
           content: function(){
             var transcludedContent;
             $transclude(function(clone){
               transcludedContent = clone; 
             });
             return transcludedContent; // actual linked DOM
           },
         // etc...
    }
    

    Finally, in the actual template for the modal:

    <div class="modal-body">
        <div confirm-popup-transclude="template"></div>
    </div>
    

    Your forked plunker