我有这个模板:
<li ng-repeat="item in results.items track by item.id"><ul result-list-line></ul></li>
有时候我会Duplicates in a repeater are not allowed
。基本上是一个后端问题,但我需要在FE中处理它。
现在,我知道之前已经讨论过:我可以循环访问数据并自己捕获重复数据,或者我可以使用track by $index
来绕过它。 我不想做任何一件事 - 我想抓住Angular错误并处理它(基本上显示错误信息)。我该怎么做?
以下是Stepan Kasyanenko的答案:
.factory('$exceptionHandler', [ '$injector', function ( $injector ) {
return function (exception, cause) {
// Preventing circular reference when using $rootScope
var $rootScope = $injector.get('$rootScope');
var msg = exception.message;
// Still have the usual console error - extend instead of replace
var $log = $injector.get('$log');
$log.error.apply($log, arguments);
//catching ngRepeat duplicates
if ( msg.search("ngRepeat:dupes") > -1 ) {
msg = "Duplicate entries were sent from the server"
}
// Not always you get a cause string, but if so you might want to add it to the message
if ( cause ) {
msg += ". Cause: "+cause;
}
// No matter what I did, I couldn't inject any factory that uses $rootScope, so I used custom event instead
$rootScope.$emit("angularError", msg);
};
}])
答案 0 :(得分:1)
您可以使用$exceptionHandler。
jsfiddle上的实例。
angular.module('ExampleApp', [])
.controller('ExampleController', function($scope) {
$scope.countries = [{
countryName: 'United States',
countryCode: 1
}, {
countryName: 'Canada',
countryCode: 2
}, {
countryName: 'Bahamas',
countryCode: 3
}, {
countryName: 'Chile',
countryCode: 4
}, {
countryName: 'Chile',
countryCode: 4
}];
})
.factory('$exceptionHandler', function() {
return function(exception, cause) {
alert(exception)
}
});
&#13;
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<div ng-app="ExampleApp">
<div ng-controller="ExampleController">
<label>Country:</label>
<div ng-repeat="country in countries track by country.countryCode">
{{country.countryName}}
</div>
</div>
</div>
&#13;
<强>已更新强>
$exceptionHandler
也处理自定义错误。
angular.module('ExampleApp', [])
.controller('ExampleController', function($scope) {
$scope.countries = [{
countryName: 'United States',
countryCode: 1
}, {
countryName: 'Canada',
countryCode: 2
}, {
countryName: 'Bahamas',
countryCode: 3
}, {
countryName: 'Chile',
countryCode: 4
}, ];
$scope.raiseError = function() {
throw "my raiseError";
}
$scope.addBadElement = function() {
$scope.countries.push({
countryName: 'Chile',
countryCode: 4
});
}
})
.factory('$exceptionHandler', function() {
return function(exception, cause) {
alert(exception);
}
});
&#13;
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<div ng-app="ExampleApp">
<div ng-controller="ExampleController">
<label>Country:</label>
<button ng-click="raiseError()">
raise Error
</button>
<button ng-click="addBadElement()">
Add Bad Country
</button>
<div ng-repeat="country in countries track by country.countryCode">
{{country.countryName}}
</div>
</div>
</div>
&#13;