3

我做了一個自定義(ul li)下拉指令。檢查一個event.target是否是Angular指令的子元素(元素)

  • 單擊此下拉列表時打開列表。
  • 當再次點擊列表時,關閉下拉菜單。
  • 當點擊列表中的選項時,該選項被保存在模型中,下拉將被關閉。
  • 在下拉菜單外單擊時,關閉下拉菜單。

大部分這是由下面的代碼(閉幕和開幕部分)完成。

scope.closeDropDown = function() { 
    scope.isOpened = false; 
    $document.unbind('click'); 
}; 

//The part for opening and closing is pressed 
scope.openDropDown = function() { 
    if (scope.isOpened) { 
     //The dropdown is already opened, close it 
     scope.closeDropDown(); 
    } else { 
     //Open the dropdown, and add an event handler to the document 
     scope.isOpened = true; 

     $document.bind('click', function (evt) { 
      var target = $(evt.target); 
      // Check if the document clicked element is a child of the directive 
      // ATTENTION HERE 
      if (!target.parents('dropdown').length) { 
       //Target is not a child element, close the dropdown 
       scope.closeDropDown(); 
       scope.$apply(); 
      } 
     }); 
    } 
}; 

仔細看看這裏的注意部分。
這裏我在整個頁面上設置了一個事件監聽器。使用這會給我下面的問題:

例如:有多個下拉菜單(例如A和B)。

  • 打開下拉列表中選擇
    • 下拉列表中選擇正確打開
  • 打開下拉乙
    • 下拉乙正確打開
    • 下拉列表中獲取文檔事件,並表示被按下的元素是下拉指令(這是正確的)的孩子
    • dropdown A不關閉S(但我希望它關閉!)

如何檢查event.target是angular.element的孩子?
現在我只是檢查如果event.target是一個下拉指令的孩子(這隻有在使用1下拉指令時纔有效)!

+0

請分享此更新 –

回答

1

根據Zia Ul Rehman Mughal的要求,我會用我自己的下拉指令中使用的答案更新問題。


,我所犯的錯誤的部分是增加一個點擊監聽時下拉被打開,而當它被再次關閉將其刪除。 這是不對的

您必須添加時創建對象的監聽器,當對象被銷燬,再把它們去掉(與角$destroy事件。

要檢查是否點擊的目標元素,你可以的孩子使用length屬性$element.find(event.target)

function closeDropDown() { 
    $scope.opened = false; 
} 

function handleClickEvent(event) { 
    /* When the clicked element is not a child of the element and 
     the dropdown is openend, close the dropdown. */ 
    if ($element.find(event.target).length === 0 && $scope.opened) { 
     closeDropDown(); 
     /* Trigger new digest cycle */ 
     $scope.$apply(); 
    } 
}; 

function setListeners() { 
    /* Bind click event to the document, close the dropDown if clicked 
     elsewhere on the page. */ 
    var clickHandler = handleClickEvent; 
    $document.bind('click', clickHandler); 

    /* Remove the used event handlers when destroying the object */ 
    $scope.$on('$destroy', function() { 
     $document.unbind('click', clickHandler); 
    }); 
} 
相關問題