How can I remove an attribute from an element in angular?

How can I remove an attribute (or at least its value) using Angular? In specific, lets say I have an ng-click event. I want this even to only fire once and I think the easiest way to do this would be to have a 'self-destruct' in the ng-click event. Something along the lines of

elementClicked = function(){
    //do work
    element.ngClick=null;

}

Upvotes: 2

Views: 1693

Answers (1)

halilb
halilb

Reputation: 4115

Removing ng-click attribute will not work, because click event listener will still be there after removing attribute. You need to set ng-click binding to null.

I created click-once directive. It listens element click event and executes ng-click binding for the first time, then it removes it.

.directive('clickOnce', function() {
  return {
    scope: {
      'ngClick': '&'
    },
    link: function(scope, element) {
      element.bind('click', function() {
        if (scope.ngClick) {
          scope.ngClick();
          scope.ngClick = null;
        }
      });
    }
  }
});

Here is the markup:

<button click-once ng-click="doThis()>my button<button>

Here is jsFiddle.

Upvotes: 4

Related Questions