2

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;

}
Brian Tompsett - 汤莱恩
  • 5,753
  • 72
  • 57
  • 129
David says Reinstate Monica
  • 19,209
  • 22
  • 79
  • 122

1 Answers1

4

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.

halilb
  • 4,055
  • 1
  • 23
  • 31