Your confusion comes from misunderstanding what's behind onclick
and ng-click
. Although they are both attributes, they are processed by different entities. The former is the way to add event listener to trigger callback when a click event occurs on DOM element. This attribute is processed by a browser and your callback, specified in this attribute, is executed by a browser. The latter is called angular directive in a form of an attribute, and a browser knows nothing about it. It's processed by the framework and some logic, like triggering event handler, is set up by the framework. If you don't use the framework, than ng-click
is going to live there unattended, and you won't have your callback executed on click
event.
Here is the relevant part of ngClick
directive - the code executed by the framework when it processes ng-click
attribute:
ngEventDirectives['ngClick'] = ['$parse', '$rootScope', function($parse, $rootScope) {
return {
restrict: 'A',
compile: function($element, attr) {
// fn "points" at the function you specified in the `ng-click`
// and will be executed below when a click event occurs
var fn = $parse(attr['ngClick'], null, true);
return function ngEventHandler(scope, element) {
element.on(eventName, function(event) {
var callback = function() {
// here `fn` is being executed
fn(scope, {$event:event});
};
if (forceAsyncEvents[eventName] && $rootScope.$$phase) {
scope.$evalAsync(callback);
} else {
scope.$apply(callback);
}
});
};
}
};
}];
You can see, that when angular processes ng-click
attribute, it executes the function ngEventHandler
, which binds the custom callback to the click
event of the DOM:
element.on(eventName, function(event) {