It's possible to intercept current event object in ng-click
like handlers by using $event
property.
But is it possible to get the element from which the method has been called?
like for example:
<div ng-controller='myController'>
<div>{{distortThatDiv($element)}}</div>
</div>
If you're going to manipulate the DOM, you really should be using a directive. However, if you have the $event
, you can get the raw element the event was triggered on easily:
$scope.clickHandler = function($event) {
var element = $event.target;
};
With a directive in angular it is easy to access the element. Just use the link function:
angular.module('myModule', [], function ($compileProvider) {
$compileProvider.directive('distortThatDiv', function distortThatDivDirective() {
return {
restrict: 'A',
link : function (scope, element, attrs) {
element.on('click', function () {
// do something
});
}
};
});
});
Your html would be:
<div ng-controller='myController'>
<a distort-that-div>My link</a>
</div>
Here's another alternative (not sure if this is a good practice, though):
In your template:
<div data-ng-click="foo()">Lorem ipsum</div>
In your controller:
angular.module('fooApp')
.controller('FooController', ['$scope', '$window', '$log', function FooController ($scope, $window, $log) {
$scope.foo = function foo () {
$log.info($window.currentTarget.innerHTML); // Outputs 'Lorem Ipsum';
}
}]);