$uibModal call scope function from windowTemplate

时间:2016-04-07 10:30:21

标签: javascript angularjs angular-ui-bootstrap angular-ui bootstrap-modal

I have a windowTemplate to wrap my modals into. What I'd like to achieve is to extend the wrapper with custom functionality. I added two new buttons to the wrapper a close button and a help button. The close button uses the built-in close function while the help should use my function which I added to the scope.

1: the windowTemplate (we put our modals into this wrapper)

<div modal-render="{{$isRendered}}" tabindex="-1" role="dialog" class="modal"
     modal-animation-class="fade"
     modal-in-class="in" ng-click="($event.target===$event.currentTarget) && close($event)"
     ng-style="{'z-index': 1050 + index*10, display: 'block'}">
  <div class="modal-dialog {{size ? 'modal-' + size : ''}}">
    <div class="modal-content">

      <!-- This is one of the added buttons -> close -->
      <aside><a class="modal-close" ng-click="close($event)"></a></aside>
      <div class="modal-content-body" modal-transclude></div>

      <!-- this is another added item, a pager, works just great -->
      <aside class="modal-pager">#{{$parent.modalId}}</aside>

      <!-- this is the help button, won't call openHelp :( -->
      <aside class="modal-help"><a ng-click="$parent.openHelp($parent.modalId, $event)"></a></aside>

    </div>
  </div>
</div>

2: within a general modalFactory

    const scope = Object.assign(this.$rootScope.$new(), descriptor.scope || {}, { openHelp: this.openHelp });
    let modalInstance = this.$modal.open({
        ...props,
        ...descriptor,
        scope, // the scope here will contain the modalId and the function (openHelp) I'd like to call from the wrapper
        resolve: {
            ...params
        }
    });

The problem is that I can't call the function from the template. Moreover if I debug my code, I debug ui-bootstraps open method where it creates a new scope from my pushed-down scope I can call my function just fine. If I call modalOptions.$parent.openHelp() then I get the desired functionality. modalOptions is ui-bootstrap internals. $parent is needed because (in ui-bootstrap-tpls.js) var modalScope = (modalOptions.scope || $rootScope).$new();. Can anyone help me out with this? :)

1 个答案:

答案 0 :(得分:0)

回答我自己的问题

Blah .. -.-我发现了为什么这不起作用。所以TL; DR

<aside class="modal-help"><a ng-click="$parent.openHelp($parent.modalId, $event)"></a></aside>

线是原因。更确切地说,我将样式规则附加到 modal-help 类,因为我不小心将类放在搁置标记上而不是 anchor 标记上锚没有尺寸(没有宽度,没有高度,没有价值)所以我怀疑当我点击图标时,事件的目标是旁边标记,它从那里冒出来。基本上我从来没有用点击处理程序点击锚标记。叹&#39 ;.只需将 modal-help 类放在 a 标记上即可。

与此同时,我想出了另一种解决方案,但仍然过于苛刻:D

  • 添加&#34;数据模式标识符&#34;属性到包装器上最外层的容器,为其指定{{$parent.modalId}}值,只是为了确保您能够查询它。
  • 在工厂中订阅实例modalInstance.rendered.then(...)
  • 的呈现事件
  • 当渲染模态时,搜索包装器的DOM元素:document.querySelector(`div[data-modal-identifier="${scope.modalId}]"`);
  • 使用事件委托订阅click事件,如果事件源是我们的帮助图标,则调用openHelp func。