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.
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.
The ng-click directive tells AngularJS what to do when an HTML element is clicked.
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.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With