[英]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.