Shanta
Shanta

Reputation: 262

angularjs ng-click event of two sibling tag fired, instead of one

I have following html code

<li ng-repeat="contact in contacts">
 <label ng-style="myStyle">
<input type="checkbox" ng-click="deleteContact(contact._id); myStyle={'text-decoration': 'line-through'};"/>
<img src="./images/edit_inline.gif" width="16px" height="16px" ng-click="editContact(contact._id)"/> 
{{contact.username}}
{{contact.email}}
 </label>
</li>

controller code is as follows:

function mainController($scope, $http) {

$scope.deleteContact = function(id) {
    $http.delete('/api/contacts/' + id)
        .success(function(data) {
            $scope.contacts = data;
        })
        .error(function(data) {
            console.log('Error: ' + data);
        });
};

$scope.editContact = function(id) {
    $http.get('/api/search/'+id)
    .success(function(data) {
        $scope.formData = data;
    })
    .error(function(data) {
        console.log('Error: ' + data);
    });

}

}

When I click on img tag to call editContact, checkbox ng-click event is also fired, as a result the record get deleted.

I can't understand, how does this happen. I am new to angularJs, please guide

Upvotes: 0

Views: 628

Answers (2)

kubuntu
kubuntu

Reputation: 2535

Not really AngularJS related. You wrapped both inputs in a label. A click inside the label will trigger both events. You can change the format of your HTML. Perhaps, take the image out of the label tag.

As an alternative, you could explicitly associate the label with either the image or chechbox by assigning an id. The following associates the label with image.

...
<label for="image" ng-style="myStyle">
  <input type="checkbox" ng-click="deleteContact(contact._id); myStyle={'text-decoration': 'line-through'};"/>
  <img id="image" src="./images/edit_inline.gif" width="16px" height="16px" ng-click="editContact(contact._id)"/> 
  {{contact.username}}
  {{contact.email}}
</label>
...

Upvotes: 1

dfsq
dfsq

Reputation: 193261

Lable kind of generates another one more event for corresponding for element. What you can do is to prevent propagation of this click event:

HTML:

<img ng-click="editContact($event, contact._id)" src="./images/edit_inline.gif" width="16px" height="16px" /> {{contact.username}}

JS

$scope.editContact = function(e, id) {
    e.preventDefault();
    ...
}

Demo: http://plnkr.co/edit/N2nUZS37MXGq7oViyLdz?p=preview

Upvotes: 0

Related Questions