Angularjs – How to transclude content in ui bootstrap modal directive

angular-uiangularjsangularjs-directive

I've made a custom directive on top of ui bootstrap modal directive so I can use the same modal template everywhere in my app.

My directive works until I try to transclude its content into the template:

http://plnkr.co/edit/YPESA3?p=preview


From index.html

<div ng-controller="ModalDemoCtrl">
  <button class="btn" ng-click="open()">Open me!</button>
  
  <my:modal open="shouldBeOpen" close="close()">
    <h1>Content</h1>
  </my:modal>
</div>

Module code:

angular.module('plunker', ['ui.bootstrap'])

.controller('ModalDemoCtrl', function($scope) {
  $scope.open = function () {
    $scope.shouldBeOpen = true;
  };

  $scope.close = function () {
    $scope.closeMsg = 'I was closed at: ' + new Date();
    $scope.shouldBeOpen = false;
  };

  $scope.items = ['item1', 'item2'];

})


.directive('myModal', function() {
  return {
    restrict : 'E',
    templateUrl: 'myTpl.html',
    //transclude: true,
    scope : {
      open : '=',
      close : '&'
    }
  };
});

Modal template:

<div modal="open">
    <div class="modal-header">
        <h4>I'm a modal!</h4>
    </div>
    <div class="modal-body">
      <!--<div ng-transclude/>-->
    </div>
       
    
    <div class="modal-footer">
      <button class="btn btn-warning cancel" ng-click="close()">Cancel</button>
    </div>
</div>

Uncomment transclude property from the directive and the template and you'll see you get a TypeError: undefined is not a function.

I can't figure what I'm doing wrong.

Best Answer

OP, your snippet is exactly what I was looking to do—thanks!

I managed to get your plunk working by passing replace:true as well as transclude: true

Here's the updated plunk http://plnkr.co/edit/gxCS2V?p=preview

I'm new to Angular, so I was interested to know why:

replace - if set to true then the template will replace the current element, rather than append the template to the element.

(via the Angular docs)

Which, of course makes sense once you know.

Good to know if you want to make your directive especially recyclable. Modals are pretty perfect example.

Related : ui-bootstrap is worth checking out.

Related Topic