2014-11-01 29 views
2

我需要基於多個元素(元素子元素)中的任何一個的單擊來添加/刪除某些類。這些元素可以在頁面加載時動態構建,所以我不能在每個元素上點擊。AngularJS:將事件監聽器應用於多個元素

我該如何在AngularJS中正確且容易地實現這一點?

$(".btn-group > .btn").click(function(){ 
    $(this).addClass("active").siblings().removeClass("active"); 
}); 

addClass(),兄弟姐妹()和removeClass()應該無需jQuery的工作包括,據我知道,因爲角都有jqLit​​e吧?

我確定我缺少明顯的東西... 感謝您的任何幫助。

回答

0

您可以使用事件委派。

基本上你將需要一個事件聽者添加到動態創建的元素的父元素,並檢查該事件氣泡的源向上

document.querySelector('input[type="button"]').addEventListener('click', function() { 
    var el = document.createElement('li'); 
    var id = new Date().getTime().toString(); 
    el.id = id; 
    el.innerHTML = id; 
    document.querySelector('.ct').appendChild(el); 
}); 

document.querySelector('body').addEventListener('click', function(event) { 
    if (event.target.tagName.toLowerCase() === 'li') { 
    alert(event.target.id); 
    } 
}); 

請參閱本jsfiddle

0

更優雅你可以擴展.btn類是這樣的:

.directive('btn', function(){ 
    return { 
     restrict: 'C' // call the directive on DOM elements with the class 'btn' 
     link: function(scope, elem, attr){ 
     if(elem.parent().hasClass('btn-group'){ 
      elem.bind('click', function(){ 
      elem.parent().children().removeClass('active'); 
      elem.addClass('active'); 
      }); 
     } 
     } 
    } 
} 

你的DOM的任何.btn屆時將有自定義的行爲,如果它^ h正確編譯。

相關問題