AngularJS Bootstrap Modal Losing Scope

AngularJS Bootstrap Modal Losing Scope

本文关键字:Scope Losing Modal Bootstrap AngularJS      更新时间:2023-09-26

我有一个由ngRoute加载的模板,其中包含一个引导模态对话框。当用户试图离开他们正在表中编辑的当前行时,会弹出这个对话框,以确认他们是否可以丢失他们的更改。

Bootstrap模式的注入覆盖在身体水平,而我的观点是比那更深一点。因此,模态被覆盖层隐藏。如果我注入模态到相同的水平,我可以看到覆盖,但现在范围丢失了。

是否有一种方法以某种方式绑定范围或另一种方式注册到事件,以便我可以继续与控制器通信?

这是我尝试的代码笔:http://codepen.io/matthewrhoden1/pen/BzEBxQ在其中,你会发现我放弃的点是试图将作用域发送到模态。

请记住,html是通过这一行在更高的级别注入的:

$('#secondModal').insertBefore('#outerOverlay');

最后我认为我可以附加到根作用域。模态的内容不能是动态的,因为作用域丢失了。至少这样我还能确定是/否。

// The directive needs the $rootScope, the event will propagate down.
// This is a bad practice but in my case I don't have any work arounds.
app.directive('event', ['$rootScope', function($rootScope) {
    return {
        restrict: 'A',
        link: function (scope, element, attr) { 
            element.bind('click', function(){
                $rootScope.$broadcast(attr.eventName);
            });
        }
     };
}]);
// Thanks to bootstrap injecting the backdrop at the body level,
// I need to do this to get my modal at the correct location.
$('#secondModal').insertBefore('#outerOverlay');

加上标记:

<div ng-app="myApp">
    <div class="container">
        <div class="content"> 
            <div class="ngView">
                <div ng-controller="TestCtrl">
                    <h1>Angular Rendered Template</h1>
                    <div class="modal">
                        Static Message
                        <button event data-event-name="test">
                            OK
                        </button>
                    </div>
                    <div id="secondModal" 
                         class="modal">
                        Static message
                        <button event data-event-name="test">
                            OK
                        </button>
                    </div>
                </div>
            </div>
        </div>
        <div class="side-menu">
          <ul>
              <li><a href="#">Link 1</a></li>
              <li><a href="#">Link 2</a></li>
              <li><a href="#">Link 3</a></li>
          </ul>
        </div>
    </div>
</div>
<!-- backdrop injected here at bottom of the body -->