Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 836
ehfeng Avatar asked Feb 12 '13 01:02

ehfeng


People also ask

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.

What is the use of NG-click?

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

What is the difference between controller and link in directives in AngularJS?

The link option is just a shortcut to setting up a post-link function. controller: The directive controller can be passed to another directive linking/compiling phase. It can be injected into other directices as a mean to use in inter-directive communication.

What is Link function in AngularJS directive?

Link: The link function deals with linking scope to the DOM. Using Code for Compile. While defining a custom directive we have the option to define a link against which either we can define a function or we have the option to assign an object which will have pre & post function.


1 Answers

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;          $scope.click = function(){            $scope.clicked++          }        }      }    }); 

Demo on plunkr

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

like image 196
Maxim Grach Avatar answered Sep 19 '22 13:09

Maxim Grach