Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why do we need ng-click?

Angular apps use the ng-click() attribute rather than the the onclick event.

Why is this?

like image 358
BanksySan Avatar asked Aug 10 '12 13:08

BanksySan


People also ask

What is the use of NG-click?

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

What is 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 Ng-click in JavaScript?

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.

Can we use NG-click in Div?

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.


2 Answers

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.

like image 26
groner Avatar answered Oct 03 '22 10:10

groner


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

  • get a reference to the scope
  • assign the variable or call the function
  • call scope.$apply so that anything watching for updates to the variables that you changed gets notified

This 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> 
like image 103
rakslice Avatar answered Oct 03 '22 08:10

rakslice