【问题标题】:AngularJS Bootstrap Modal Losing ScopeAngularJS Bootstrap 模式丢失范围
【发布时间】:2016-08-18 20:53:10
【问题描述】:
我有一个由 ngRoute 加载的模板,其中包含一个引导模式对话框。当用户尝试将他们正在编辑的当前行留在表格中时,会弹出此对话框以确认他们是否可以丢失更改。
Bootstrap modal 会在正文级别注入叠加层,因为我的观点比这更深一些。因此,模态被覆盖层隐藏。如果我将模态注入到同一级别,我可以看到覆盖,但现在范围丢失了。
有没有办法以某种方式绑定范围或以其他方式注册事件,以便我可以继续与控制器通信?
这是我尝试的代码笔:http://codepen.io/matthewrhoden1/pen/BzEBxQ 在其中你会发现我放弃的一点是尝试将范围发送到模态。
请记住,html 是通过这一行在更高级别注入的:
$('#secondModal').insertBefore('#outerOverlay');
【问题讨论】:
标签:
javascript
jquery
angularjs
twitter-bootstrap
【解决方案1】:
最终我发现我可以附加到根范围。由于范围丢失,模式的内容不能是动态的。至少这样我仍然可以确认是/否。
// 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 -->