Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Angularjs ng-click: how to get `this` data?

Let say I have this item in the list with angular ng-click event.

<a data-id='102' ng-click='delete()'>Delete</a> 

How can I get the data/ info if this then?

        $scope.delete = function() {               var id = $(this).attr('data-id');              console.log(id); // I want to get 102 as the result              if (confirm('Are you sure to delete?')) {                 $('#contactsGrid tr[data-id="' + id + '"]').hide('slow');              }          }; 
like image 415
Run Avatar asked Dec 28 '13 12:12

Run


People also ask

What is data Ng-click?

The ng-click directive tells AngularJS what to do when an HTML element is clicked.

How do you trigger a click event in AngularJS?

The syntax is the following: function clickOnUpload() { $timeout(function() { angular. element('#myselector'). triggerHandler('click'); }); }; // Using Angular Extend angular.

Can we use NG-click in Div?

Syntax of using ng-click directive There, the button is an element that can be replaced by any other HTML element like a link, span, paragraph, div etc.

What is the difference between click and Ng-click?

Another significant difference between ng-click and onclick is the execution context. Code inside an onclick attribute executes against the global window object, while an expression inside of ng-click executes against a specific scope object, typically the scope object representing the model for the current controller.


2 Answers

The right solution will be is to pass the id as an parameter to the delete function like

<a data-id='102' ng-click='delete(102)'>Delete</a> 

then

    $scope.delete = function(id) {          console.log(id); // I want to get 102 as the result          if (confirm('Are you sure to delete?')) {             $('#contactsGrid tr[data-id="' + id + '"]').hide('slow');          }      }; 

This should not be done, but just to demonstrate

Inside ng-click you can get the event using $event, so

<a data-id='102' ng-click='delete($event)'>Delete</a> 

then

$scope.delete = function (e) {     var id = $(e.target).data('id');     console.log(id); // I want to get 102 as the result }; 

Demo: Fiddle

like image 137
Arun P Johny Avatar answered Oct 18 '22 05:10

Arun P Johny


To access clicked link tag attributes

In jQuery,

<a class='test' data-id='102' ng-click='delete(102)'>Delete</a> 

on click of above link is handled as

$('.test').click(function(){    console.log($(this).attr('data-id'));  }); 

Demo code for jQuery : fiddle

In Angularjs,

<a class='test' data-id='102' ng-click='delete($event)'>Delete</a> 

on click of above link is handled as

$scope.delete = function (e) {     console.log($(e.currentTarget).attr("data-id"));   } 

Demo code for Angularjs : fiddle

like image 28
aashish Avatar answered Oct 18 '22 06:10

aashish