在某些情况下, Angular 引擎不会输出原始的 javascript 错误。例如
myapp.directive('helloWorld', function() {
return {
scope: '@',
restrict: 'AE',
template: '<p ng-click="clearMessage2()">Hello, World! {{message}}</p>',
link: function(scope, elem, attrs) {
scope.clearMessage = function() {
scope.message = '';
}
}
}});
当我点击使用指令生成的 p 元素时,我期望控制台中的错误提示 clearMessage2() 未定义,但这并没有发生,并且检查内容的唯一方法是在 clearMessage 定义中使用 console.log。
是否可以更改 angular.js 的行为并且不隐藏 JS 代码中发生的错误?
最佳答案
可以,但不推荐。问题是 Angular 不会按原样执行 ng-click 指令中的方法(就像在常规的 onclick 中一样),而是使用 $parse 服务评估表达式。来自 Angular 文档:
Angular does not use JavaScript's eval() to evaluate expressions. Instead Angular's $parse service processes these expressions.
Angular 中表达式计算的实现是故意宽容的。
In JavaScript, trying to evaluate undefined properties generates ReferenceError or TypeError. In Angular, expression evaluation is forgiving to undefined and null. 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
因此 $parseProvider 根本不会执行未定义的函数,而是执行 noop 函数(这是空对象模式的实现)。以下是 $parseFunctionCall 方法的摘录:
var fn = fnGetter(scope, locals, context) || noop;
空对象的执行不会做任何事情,这就是正在发生的事情。您可能可以通过修改 $parseFunctionCall 来执行任何函数而不是执行 noop 函数来实现您想要的。
更改代码似乎是唯一的选择,因为这些服务的配置不足以满足您的用例。但是,除非您非常了解 Angular API,否则我认为这不是推荐的方法。
补充阅读:
关于javascript - 在 angular.js 中暴露 javascript 错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29155171/