jonv1
jonv1

Reputation: 586

Why is there no error when calling an undefined function in AngularJS?

I have the following example: https://jsfiddle.net/vr0dkwrh/1/

Basically, I'm calling a function that doesn't exist in the scope. Why is there no error shown in the browser? (I have tested with Firefox 38.1 and IE 11).

When anchor 'click me' is clicked, go() will be called.

When anchor 'click me2' is clicked, go2() will be called but it doesn't exists and there is no error in the console.

For the record, I'm new to AngularJS and I was requested to learn it in such short notice (2 days...).

Could someone tell me if this is normal behaivor in AngularJS?

I had to choose 1.2.1 version in JSFiddle but I'm using 1.4.4 locally.

HTML:

<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="utf-8"><meta http-equiv="X-UA-Compatible" content="IE=edge">
    <title>AngularJS Test</title>
  </head>
  <body>
    <div class="col-lg-12" ng-app="app" ng-strict-di>
      <div ng-controller="EditableRowCtrl">
          <a ng-href="#here" ng-click="go()" >click me</a><br />
          <a ng-href="#here2" ng-click="go2()" >click me2</a><br />
      </div>
    </div>
    <script src="../libs/angularjs.js"></script>
    <script src="../app/app-test1.js"></script>
  </body>
</html>

Javascript:

(function(){
'use strict';

function GoodController1($scope, $http, $filter) {
  $scope.go = function(){
    console.log('asd');
    //notexists();
  };
}
GoodController1.$inject = ["$scope", "$http", "$filter"];

angular.module("app", [])
.controller('EditableRowCtrl', GoodController1);
})();

Upvotes: 3

Views: 971

Answers (1)

deceze
deceze

Reputation: 522261

As the manual puts it, Angular's template expression evaluation is explicitly forgiving:

Expression evaluation is forgiving to undefined and null. In JavaScript, evaluating a.b.c throws an exception if a is not an object. While this makes sense for a general purpose language, the expression evaluations are primarily used for data binding, which often look like this:

{{a.b.c}}

It makes more sense to show nothing than to throw an exception if a is undefined (perhaps we are waiting for the server response, and it will become defined soon). If expression evaluation wasn't forgiving we'd have to write bindings that clutter the code, for example:

{{((a||{}).b||{}).c}}

Similarly, invoking a function a.b.c() on undefined or null simply returns undefined.

https://docs.angularjs.org/guide/expression

Angular uses a custom expression evaluation engine which is not Javascript. Its syntax allows a narrow subset of Javascript, but the execution is entirely custom.

Upvotes: 4

Related Questions