angularjs ng-click silently eats errors

2019-01-18 19:29发布

问题:

If I have an ng-click like this: ng-click="buggy()" and click on no error message is generated on the console.

This makes it a bit tricky to debug.

Why aren't error messages generated? Anything I can do?

回答1:

Angular expressions

Actually, It's not something special with ng-click, It's the default behavior of angular expressions .

buggy() is not evaluated with regular javascript. It is evaluated with $parse.

$parse evaluates expressions and returns a function that would run against a scope.

$parse only log errors when the expression is not valid.

Angular expression evaluation is forgiving , I cannot think of any way to pass it.

Why expressions are forgiving?

A rationale for Angular expressions to be forgiving of undefined and null has to do with data binding. Bound variables may initially be undefined or null when they are compiled into the DOM- one really clear example is when the bound variable is dependent on a promise. The Angular team decided that rather than having error messages popping up until that promise is resolved it'd be better to continue silently.

From the Angular guide to expressions:

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}}

See Also: https://groups.google.com/forum/m/#!topic/angular/HRVOUKEHLFw


Angular expressions:

Expressions are JavaScript-like code snippets that are usually placed in bindings such as {{ expression }}. Expressions are processed by the $parse service. Expressions are often post processed using filters to create a more user-friendly format.

Angular Expressions vs. JS Expressions

It might be tempting to think of Angular view expressions as JavaScript expressions, but that is not entirely correct, since Angular does not use a JavaScript eval() to evaluate expressions. You can think of Angular expressions as JavaScript expressions with following differences:

  • Attribute Evaluation: evaluation of all properties are against the scope doing the evaluation, unlike in JavaScript where the expressions are evaluated against the global window.

  • Forgiving: expression evaluation is forgiving to undefined and null, unlike in JavaScript, where trying to evaluate undefined properties can generate ReferenceError or TypeError.

  • No Control Flow Statements: you cannot do any of the following in angular expression: conditionals, loops, or throw.