简体   繁体   中英

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);
})();

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

Expression evaluation is forgiving to undefined and null . In JavaScript, evaluating abc 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:

 {{abc}} 

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 abc() 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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM