Possible to call 'alert()' or 'console.log()' from Angular ng-click Expression?

alert() and console.log(), do not seem to be available.

Both alert() and console.log() are evaluated against the global window object. On the other hand ng-click is an AngularJS Expression and is evaluated against the scope associated with it which does not have any direct access to the window object. Thus they are not available inside scope.

AngularJS Expressions vs. JavaScript Expressions

Context: JavaScript expressions are evaluated against the global window. In AngularJS, expressions are evaluated against a scope object.

AngularJS provides a service called $log for that purpose. You can use $log service like the following:

var myApp = angular.module('myApp',[]);

myApp.controller('myController', ['$scope', '$log', function($scope, $log){
  $scope.TestClick = function(){
    $log.log('You have clicked');
  }
}])
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>

<div ng-app="myApp" ng-controller="myController">
  <input type="button" value="Click" ng-click="TestClick()"/>
</div>

Both of that is basic JS provided tools. It should be available!

If you wish to console or alert from HTML, it probably not a good way to do it. Nor i think it is possible.

You may choose to attach your HTML to a controller and then move the Console.log or alert to that controller. And It will work as expected.


AngularJS Expressions vs. JavaScript Expressions

AngularJS expressions are like JavaScript expressions with the following differences:

  • Context: JavaScript expressions are evaluated against the global window. In AngularJS, expressions are evaluated against a scope object.

- AngularJS Developer Guide - AngularJS Expressions vs. JavaScript Expressions


ng-click must be call an expression. AngularJS expressions do not have direct access to global variables like window, document or location. This restriction is intentional. It prevents accidental access to the global state – a common source of subtle bugs.