Angular apps use the ng-click()
attribute rather than the the onclick
event.
Why is this?
The ng-click directive tells AngularJS what to do when an HTML element is clicked.
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 in AngluarJS is used to apply custom behavior when an element is clicked. It can be used to show/hide some element or it can popup alert when button is clicked.
Syntax of using ng-click directive There, the button is an element that can be replaced by any other HTML element like a link, span, paragraph, div etc.
ng-click holds an angular expression. Angular expressions are evaluated in the context of an Angular scope, which is bound to the element having the ng-click attribute or an ancestor of that element.
The Angular expression language doesn't include flow control statements and can't declare variables or define functions. These limitations mean templates can only access variables and run functions made available by a controller or directive.
Angular doesn't change the meaning of the onclick
attribute; it adds the parallel ng-click
attribute to take an Angular expression. onclick
takes plain old JavaScript code even when you're using Angular.
Practically speaking, suppose what you're doing in a click handler is changing some variables in an Angular scope, or calling a function in an Angular scope that changes some variables. To do that from JavaScript code (like what you would put in onclick
) requires a bunch of steps
scope.$apply
so that anything watching for updates to the variables that you changed gets notifiedThis looks like:
<a onclick="var $scope = angular.element(event.target).scope(); $scope.yourVar = 42; $scope.$apply()">Go</a>
and with ng-click
and an Angular expression for the assignment, almost all of that is implicit:
<a ng-click="yourVar = 42">Go</a>
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