Sco*_*ord 7 angularjs angularjs-directive
我有一个使用帮助器/包装器指令的Angular模态指令.这样我总是可以使用相同的包装器,只需在不同的模态内容中加载不同的模板.
问题:此代码段有效,但仅适用于模态的第一个生命周期.所以我可以发射模态,关闭模态并再次发射它.但是一旦模态打开,第二次ng-click指令都不起作用.任何提示都只是超级.
用法
<button my-modal="views/login.html">Launch Login-specific Modal</button>
Run Code Online (Sandbox Code Playgroud)
指令模块(app.js)
angular.module('myModal',[])
.directive('modalWrapper', function(){
return {
replace: true,
templateUrl: 'views/modal.html',
controller: function($scope, $element){
$scope.close = function(){
$element.remove();
};
// NOTE: I use this array to showcase that ng-repeat still works the second time although ng-click stops functioning properly.
$scope.others = ["One", "Two", "Three"];
}
}
})
.directive('myModal', function( $compile){
function link(scope, element, attr){
scope.partial = attr.myModal; // NOTE: Loads sub template via ng-include
var ngModal = $compile('<div modal-wrapper></div>')(scope);
element.on('click', function(){
angular.element('body').append(ngModal);
});
scope.yo = function(){
alert("Yo from inside template.");
};
}
return {
link: link,
scope: {}
}
});
Run Code Online (Sandbox Code Playgroud)
模板
modal.html
<div class="my-modal">
<p>Modal Wrapper</p>
<div ng-include="partial"></div>
<button ng-click="close()">Close</button>
<p>This just proves that other directives still work (ng-repeat), but ng-click does not.</p>
<div ng-repeat="stuff in others">
<p>{{stuff}}</p>
</div>
</div>
Run Code Online (Sandbox Code Playgroud)
的login.html
<h1>Well hey there, I'm the login template.</h1>
<button ng-click="yo()">Say Yo</button>
Run Code Online (Sandbox Code Playgroud)
我认为问题是你正在破坏ng-click编译的范围.
当scope.close()被调用时,一个$element.remove()发生.这两者都从DOM中删除了元素,并破坏了它附加的范围.这将导致您ng-click被取消注册.
不幸的是(截至上次我检查过),element.detach()也破坏了范围,所以最好的办法就是编译并将元素追加到body只有一次.在此之后,您可以使用element.show()和element.hide()显示和隐藏模态.或者,您可以在每次要显示模式时重新编译模态.