当Angular应用程序中有一行代码导致错误时,整个模板都会损坏。
例如,此代码(当我们尝试将值分配给foo.bar
时会导致错误):
<!doctype html>
<html ng-app="myApp">
<head>
<meta charset="utf-8">
<title>My App</title>
</head>
<body>
<div class="container" id="home" ng-controller="MainCtrl">
<h1>Message: {{hello_msg}}</h1>
</div>
<script src="//cdnjs.cloudflare.com/ajax/libs/angular.js/1.3.10/angular.js"></script>
<script>
var myApp = angular.module('myApp', ['myApp.controllers']);
angular.module('myApp.controllers', []).
controller('MainCtrl', ['$scope', function ($scope) {
var hello_msg = 'Hello!';
$scope.hello_msg = hello_msg;
// malformed JS
foo.bar = 'app breaks';
}]);
</script>
</body>
</html>
完全破坏页面,它看起来像这样:
是否有一些配置选项可以添加到我的Angular应用程序中,以便页面更优雅地出错?具体而言,如果应用中存在错误,则{{
和}}
中包含的模板中的变量根本不会显示。
答案 0 :(得分:2)
更优雅地出错的一种方法是使用:
<div ng-bind-html="hello_msg">
当{{hello_msg}}
打破应用时,丑陋的foo.bar
将无法显示。
请查看证明要点的this plunker
重要提示
要使用ng-bind-html代替大括号,您需要在模块中加入ng-sanitize 。