2

I need to add / remove certain classes based on a click on any of the multiple elements (element children). These elements can be constructed dynamically on page load so I can't put ng-click on each.

How can I accomplish this correctly and as easily in AngularJS ?

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

addClass(), siblings() and removeClass() should work without having jQuery included as far as I know since Angular has its jqLite right?

I am sure I am missing something obvious ... Thanks for any help.

2 Answers 2

1

More elegantly you could extend the .btn class like this :

.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');
          });
        }
      }
    }
}

Any .btn on your dom will then have the custom behavior if it has been correctly compiled.

Sign up to request clarification or add additional context in comments.

Comments

0

You could use event delegation.

Basically you will need to add an event listner to the parent element of the dynamically created elements and check the source of the event bubble up

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);
  }
});

please refer to this jsfiddle

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.