Custom Click directive event using Angular Js

You can easily create a custom click directive using link function in angular js.

html source
ang1
I have added a custom attribute named custom-click in the button element for handling the click event which is similar to angular ng-click. Now i am going to write a custom directive for this custom attribute.

angular.module('app', []);

angular.module('app').controller('myController', function ($scope) {
$scope.obj = { message: "Not Clicked" };
$scope.callMethod = function (p) {
p.message = "Clicked!!";
}
});

angular.module('app').directive("customClick", function ($parse) {
return {
link: function (scope, element, attrs) {
var func = $parse(attrs["customClick"]);
element.on('click', function () {
scope.$apply(function () {
func(scope);
});
});
}
}
});

when you clicked the button you can see the message ‘Clicked !!’ in the h1 tag.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s