Как включить содержимое в модальную директиву ui bootstrap

Я создал пользовательскую директиву поверх модальной директивы ui bootstrap, поэтому я могу использовать один и тот же модальный шаблон везде в своем приложении.

Моя директива работает, пока я не попытаюсь включить ее содержимое в шаблон:

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


Из 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>

Код модуля:

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 : '&'
    }
  };
});

Модальный шаблон:

<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>

Раскомментируйте свойство transclude из директивы и шаблона, и вы увидите, что получили TypeError: undefined is not a function.

Я не могу понять, что я делаю неправильно.


person Florian F    schedule 07.03.2013    source источник


Ответы (2)


ОП, твой фрагмент именно то, что я хотел сделать — спасибо!

Мне удалось заставить ваш планк работать, передав replace:true, а также transclude: true

Вот обновленный планк http://plnkr.co/edit/gxCS2V?p=preview.

Я новичок в Angular, поэтому мне было интересно узнать, почему:

replace - если установлено значение true, то шаблон заменит текущий элемент, а не добавит шаблон к элементу.

(через документы Angular)

Что, конечно, имеет смысл, когда вы знаете.

Полезно знать, если вы хотите сделать свою директиву особенно пригодной для вторичной переработки. Модальные окна — прекрасный пример.

Связано: ui-bootstrap стоит проверить.

person couzzi    schedule 12.03.2013

Проверьте это решение, вам не нужен дополнительный контроллер или угловой интерфейс, для которого нужно передать простой обработчик и использовать его.

пример.js

angular.module('plunker', [], function() {

})

.directive('modal', function() {
  return {
    restrict : 'E',
    templateUrl: 'myTpl.html',
    transclude: true,
    controller: function($scope) {
      // you need get a better unique generator
      $scope.modal_id = 'modal_' + Math.floor((Math.random()*100+1));
      $scope.handler = $scope.modal_id;
    },
    scope : {
      handler : '='
    }
  };
})
.run();

index.html

<!doctype html>
<html ng-app="plunker">
  <head>    
    <link href="//netdna.bootstrapcdn.com/twitter-bootstrap/2.3.1/css/bootstrap-combined.min.css" rel="stylesheet">    
  </head>
<body>

<div ng-init="handler = null">  
  <modal handler="handler">
    <h1>Content</h1>
  </modal>  
  <a href="#{{handler}}" role="button" class="btn primary" data-toggle="modal">Open me</a>
</div>
    <script src="//ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
    <script src="http://ajax.googleapis.com/ajax/libs/angularjs/1.0.5/angular.js"></script>    
    <script src="//netdna.bootstrapcdn.com/twitter-bootstrap/2.3.1/js/bootstrap.min.js"></script>
    <script src="example.js"></script>
</body>
</html>

myTpl.html

<div id="{{modal_id}}" class="modal hide fade" tabindex="-1" role="dialog" aria-labelledby="{{modal_id}}Label" aria-hidden="true">
    <div class="modal-header">
        <button type="button" class="close" data-dismiss="modal" aria-hidden="true">×</button>
        <h4 id="{{modal_id}}Label">I'm a modal!</h4>
    </div>
    <div class="modal-body">
      <div ng-transclude></div>
    </div>    
    <div class="modal-footer">
      <button class="btn" data-dismiss="modal" aria-hidden="true">Cancel</button>
    </div>
</div>

посмотрите, как работает плункер

person rkmax    schedule 08.03.2013
comment
Спасибо за Ваш ответ. Я попробую. Однако, если честно, мне больше интересно узнать, что не так в моем примере. - person Florian F; 08.03.2013
comment
Я решил сделать решение, которое не использует angular-ui из-за неудачного опыта, потому что angular-ui доставил мне больше проблем, чем решений. но будет внимательно следить за модальной директивой из angular-ui - person rkmax; 08.03.2013