ehfeng ehfeng - 1 year ago 67
AngularJS Question

Using ng-click vs bind within link function of Angular Directive

In the link function, is there a more "Angular" way to bind a function to a click event?

Right now, I'm doing...

myApp.directive('clickme', function() {
return function(scope, element, attrs) {
scope.clickingCallback = function() {alert('clicked!')};
element.bind('click', scope.clickingCallback);
} });

Is this the Angular way of doing it or is it an ugly hack? Perhaps I shouldn't be so concerned, but I'm new to this framework and would like to know the "correct" way of doing things, especially as the framework moves forward.

Answer Source

You may use a controller in directive:

angular.module('app', [])
  .directive('appClick', function(){
     return {
       restrict: 'A',
       scope: true,
       template: '<button ng-click="click()">Click me</button> Clicked {{clicked}} times',
       controller: function($scope, $element){
         $scope.clicked = 0;
         $ = function(){

Demo on plunkr

More about directives in Angular guide. And very helpfull for me was videos from official Angular blog post About those directives.