如何在AngularJS中添加/删除DOM元素?

时间:2014-08-23 02:50:47

标签: angularjs angularjs-directive

我想显示简单的消息模态对话框(bootstrap模态对话框)。

该对话框是一段HTML:

<div class="dlg">.....</div>

当我想要显示一个对话框并在关闭对话框时删除它时,如何将这段HTML添加到DOM树中?

显然,这应该在指令中完成。但是如何在控制器的按钮单击处理程序中调用指令的'ShowDialog()'方法?

1 个答案:

答案 0 :(得分:0)

正如评论所说,在您的DI中传递$ modal,请查看示例:http://angular-ui.github.io/bootstrap/#/modal

<div ng-controller="ModalDemoCtrl">
    <script type="text/ng-template" id="myModalContent.html">
        <div class="modal-header">
            <h3 class="modal-title">I'm a modal!</h3>
            </div>
            <div class="modal-body">
                <ul>
                <li ng-repeat="item in items">
                    <a ng-click="selected.item = item">{{ item }}</a>
                    </li>
                    </ul>
                    Selected: <b>{{ selected.item }}</b>
                    </div>
                    <div class="modal-footer">
                        <button class="btn btn-primary" ng-click="ok()">OK</button>
                        <button class="btn btn-warning" ng-click="cancel()">Cancel</button>
                        </div>
                        </script>

                        <button class="btn btn-default" ng-click="open()">Open me!</button>
                        </div>

JS:

angular.module('plunker', ['ui.bootstrap']);
var ModalDemoCtrl = function ($scope, $modal, $log) {

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

  $scope.open = function (size) {

    var modalInstance = $modal.open({
      templateUrl: 'myModalContent.html',
      controller: function ($scope, $modalInstance, items) {

  $scope.items = items;
  $scope.selected = {
    item: $scope.items[0]
  };

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

  $scope.cancel = function () {
    $modalInstance.dismiss('cancel');
  };
};,
      size: size,
      resolve: {
        items: function () {
          return $scope.items;
        }
      }
    });

    modalInstance.result.then(function (selectedItem) {
      $scope.selected = selectedItem;
    }, function () {
      $log.info('Modal dismissed at: ' + new Date());
    });
  };
};