Jeffrey Rosselle
Jeffrey Rosselle

Reputation: 765

Why is the ng-click handler being fired twice?

I've got a button that's used to delete a question:

<a class="btn-small float-right" data-ng-click="deleteQuestion(question)">
  <i data-ng-class="{true: 'icon-step-backward', false: 'icon-remove'}
  [question.IsDeleted]"></i>
</a>

This is the code behind the button:

$scope.deleteQuestion = function (data) {
  if (data.IsDeleted) {
      data.IsDeleted = false;
      for (var i = 0; i < deletedQuestions.length; i++) {
          if (deletedQuestions[i] == data) {
              deletedQuestions.splice(i, 1);
          }
      }  
  } else {
      data.IsDeleted = true;
      if ($.inArray(data, deletedQuestions) === -1) {
          deletedQuestions.push(data);
      }
  }
};

Now when I press the button I noticed the function has been fired twice. The first time it deletes the question, the second time it undoes that action.

What I want was one button to delete a question and when you click it again, it undoes that action.

I'm just wondering what I've overlooked...

EDIT Here is a fiddle: http://jsfiddle.net/rquackenbush/AbWKs/

Upvotes: 6

Views: 9246

Answers (1)

Jeffrey Rosselle
Jeffrey Rosselle

Reputation: 765

I found out what the problem was.

The link is inside a list:

<li class="question-item"
   data-app-bind-html="question.template">                        
       <a class="btn-small float-right" data-ng-click="deleteQuestion(question)">
         <i data-ng-class="{true: 'icon-step-backward', false: 'icon-remove'} [question.IsDeleted]">
         </i>
      </a>
<li>

I've made an data-app-bind-html which binds a html part inside it. This caused the link to be bound twice, which made it fire twice too. To solve this I just made sure the directive binds the html part and not the whole listitem.

Upvotes: 5

Related Questions