簡體   English   中英

角度指令兩次使用,覆蓋元素

[英]Angular directive used twice, override element

我正在嘗試為模式編寫一個簡單的指令,以便在我向其中提交表單時將其關閉。

我有2個模態:Loginmodal和signup modal,分別在我的html中排序。

模態位於modals.html中,在html文件中也稱為ng-include,而html文件也稱為ng-include,因此在這里我們有一個childscope的childscope

我的指令

directive('myModal', function() {
    return {
        restrict: 'A',
        scope : { },
        link: function(scope, element, attr) {
            scope.$parent.$parent.$parent.dismiss = function() {
                console.log(element.hasClass('in')); //returns false
                element.modal('hide');// doesn't work because element is always the second modal
                };
            $(element).bind('shown.bs.modal', function () {
                if (!scope.$$phase && !scope.$root.$$phase)
                    scope.$parent.$parent.$parent.$apply();
                });
            }
        };
});

我不知道為什么link內的元素被最后一個元素覆蓋?

我將我的模態指令應用於兩個模態,但是我打開了第一個模態指令。

任何幫助將不勝感激

您確定scope.$parent.$parent.$parent與您的兩個模式不同嗎? 如果他們具有相同的grand-old-parent-parent,則只有最后一個將實際定義grandOldParent.dismiss函數。

老實說,當我看到這個scope.$parent.$parent.$parent東西時,我有點害怕。 始終建議避免使用$parent ,因此鏈接其中的3個甚至更瘋狂。

如果實際上您要操縱它的上級父級,您真的需要一個孤立的范圍( scope: {} )嗎? 為什么不使用繼承的作用域?

可能存在一種更清潔的方式來處理這些范圍。 您是否正在使用,或者是否查看過https://angular-ui.github.io/bootstrap/ ,其中模態是使用$modal服務定義了模板和控制器的角度的?

這也沒用:

if (!scope.$$phase && !scope.$root.$$phase)
  scope.$parent.$parent.$parent.$apply();
});

並且應替換為

if (!scope.$root.$$phase) {
  scope.$apply();
}

(如果此事件是異步的並且不在Angular摘要周期scope.$apply則簡單地使用scope.$apply )。

另請注意, scope.$apply實際上確實是$rootScope.$digest因此無論您應用$哪個范圍都沒有關系。

更新 :您可以做的是在指令html中添加ng-click="close" ,並將其添加到其鏈接函數中:

scope.close = function() {
  // do stuff on this directive instance
  console.log(element.hasClass('in'));

  // close the modal
  var parent = scope;
  while (!parent.dismiss) { parent = parent.$parent; }
  parent.dismiss();
}

這樣,您的指令的每個實例都有其自己的close函數(因此不會覆蓋任何其他函數),但仍會調用屬於每個實例使用的一個模式的唯一dismiss

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM