我有一个简单的页面,显示字符串的哈希,因为有人将其键入页面。我发现该页面存在JavaScript错误
错误:[$ rootScope:infdig] http://errors.angularjs.org/1.2.26/ $ rootScope / infdig?p0 = 10& p1 =%5B%5B%22sha1 ... 75651%2C1080464653%2C-772792499%5D%2C%5C%22sigBytes%图5C%22%3A20%7D%22%5D%5D
页面的简化版本是
<html lang="en">
<head>
<script src="http://crypto-js.googlecode.com/svn/tags/3.1.2/build/rollups/sha1.js"></script>
<script src="http://ajax.googleapis.com/ajax/libs/angularjs/1.2.26/angular.min.js"></script>
<script>
function MyCtrl($scope) {
$scope.sha1 = function(pwd) {
return CryptoJS.SHA1(pwd);
};
}
</script>
</head>
<body>
<div class="app" ng-app ng-controller="MyCtrl">
<span ng-bind="sha1('bar')"></span>
</div>
</body>
</html>
以Plunker http://plnkr.co/edit/vmBtH8B2EKsdcfZVGlMH提供。
我在原始页面中尝试做的是重新计算哈希,因为有人在表单字段中键入,输入字段定义看起来像这样
<input id="password" ng-model="password" type="text" placeholder="Password">
并且ng-bind实际上是ng-bind="sha1(password)"
,但是Plunker中的简单静态情况表现出相同的行为。
我认为infdig错误与太多的$ digest周期有关,但我不知道这会如何发生。看起来哈希计算会触发错误,因为从sha1函数返回一个静态字符串不会导致错误。
答案 0 :(得分:0)
提供ng-bind="sha1('bar')"
会使摘要周期不稳定,每次sha1函数返回一个不同的对象(引用不同),你的摘要周期必须再次运行以稳定它,每个摘要周期再次评估ng-bind函数表达式它一直持续到达到最大极限设定值(10)。您也可以通过在范围方法中执行return []
来轻松复制此问题。这只是将函数表达式绑定到ng-bind
的不太好的做法的副作用,因为它运行每个摘要周期,如果完全使用它应该仔细评估。
一个简单的解决方案是在您的密码或任何其他触发器上绑定ng-change / ng-blur事件,并将ng-bind绑定到属性而不是函数表达式。
angular.module('app',[])
.constant('Crypto', window.CryptoJS);
function MyCtrl($scope, Crypto) {
$scope.encrypt = function() {
$scope.encrypted = Crypto.SHA1($scope.password);
};
}
<html lang="en" ng-app="app">
<head>
<script src="http://crypto-js.googlecode.com/svn/tags/3.1.2/build/rollups/sha1.js"></script>
<script src="http://ajax.googleapis.com/ajax/libs/angularjs/1.2.26/angular.min.js"></script>
</head>
<body>
<div class="app" ng-app ng-controller="MyCtrl">
<input id="password" ng-model="password" type="password" placeholder="Password" ng-change="encrypt()">
<span ng-bind="encrypted"></span>
</div>
</body>
</html>
为了更好地使用DI,我将crpto放在一个常量中并在需要的地方注入。