[英]Call a function on click on a transcluded element inside an AngularJS directive
我写了一个模态指令,因为我想在页面上有几个模态。 我使用本教程来实现此目的: http : //adamalbrecht.com/2013/12/12/creating-a-simple-modal-dialog-directive-in-angular-js/
首先,这是我的指令代码,与上一教程中的代码几乎相同:
//here, app is an AngularJS module
app.directive('modal', function() {
return {
restrict: 'E',
scope: {
show: '='
},
replace: true,
transclude: true,
link: function(scope) {
scope.hide = function() {
scope.show = false;
document.body.classList.remove('wwf-noScroll');
};
},
template: '<div class="Modal" ng-show="show"><div class="Modal-overlay" ng-click="hide()"></div><button class="Modal-close" ng-click="hide()"></button><div class="Modal-content" ng-transclude></div></div>'
};
});
这就是我的用法:
<modal show="showInformationsModal">
<h2 class="Modal-title">Informations</h2>
<button type="button">Close this</button>
</modal>
我要实现的是能够关闭模式(即,调用指令范围内定义的hide
函数)。 但是我不能将按钮放在指令模板中,因为有时我希望模式中的按钮将其关闭,但有时却不希望这样做,并且该按钮内的文本永远不会相同。
我尝试了一些类似的事情:
<button type="button" ng-click="hide()">Close this</button>
<button type="button" ng-click="showInformationsModal = false">Close this</button>
<button type="button" ng-click="show = false">Close this</button>
没事。 我想我缺少了什么! 有人可以帮我吗?
谢谢,
西里尔
编辑
因为它是在指出此评论 ,所述transclude
函数可以通过更换更通用的var contentElement = element[0].querySelector('.Modal-content');
与var contentElement = element[0].querySelector('[ng-transclude]');
原版的
一个朋友给我发送了此链接: http : //angular-tips.com/blog/2014/03/transclusion-and-scopes/
我所缺少的正是该链接所指出的:超越HTML的范围不是指令的隔离范围。
我使用了link
功能的第五个参数:
transclude(scope, function(clone, scope) {
var contentElement = element[0].querySelector('.Modal-content');
contentElement.innerHTML = '';
for (var i = 0; i < clone.length; ++i) {
contentElement.appendChild(clone[i]);
}
});
这是更新的代码笔。 我不知道这是否是解决我的问题的最美丽方法,但是它解决了! http://codepen.io/JesmoDrazik/pen/NqZLYR?editors=001
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.