Highlight duplicate exception in ng-repeat Angularjs table

I try to notify the user every time a duplicate is registered in the table. I would like to catch: Error: [ngRepeat:dupes]and warn the user before continuing. Here is a controller method that adds elements to the table:

$scope.addProdukt = function (item) {
    kladdValidationService.checkTable(); 
    try {
        $scope.addedResult.push(item); // works fine
        logService.info('Produktet er lagt til i tabellen'); 

    } catch (e) {
        console.log(e.stack); 
        console.log($exceptionHandler(e)); // neither of these two work
    }
    console.log($scope.addedResult);
};

Each time I click an already added item in a table, the outputs Error: [ngRepeat:dupes]are displayed in the console. Juswt is not sure how to catch him.

+4
source share
4 answers

The reason the error is not caught is because pushing a duplicate into an array is absolutely valid and does not raise an exception. an exception occurs in the directive ng-repeat.

, , - :

$scope.addProdukt = function (item) {
    if(addedResult.indexOf(item) != -1){
        console.log("You tried to add a duplicate");
    }else{
         $scope.addedResult.push(item);
    }
}

, , html, track by $index ng-repeat :

<div ng-repeat="item in $scope.addedResult track by $index">
</div>
+2

:

$index

<div ng-repeat="n in [42, 42, 43, 43] track by $index">
  {{n}}
</div>
0

: : [ngRepeat: dupes] .

, Exception?

. , Error: [ngRepeat:dupes] - ! . ..

, .

Angular Exception !


In any case, if you want to handle exceptions, you can catch the override $exceptionHandler:

For instance:

app.config(function($provide) {

   $provide.decorator("$exceptionHandler", function($delegate, $injector) {
    return function(exception, cause) {

            var data = {
                message: "Exception: " + exception.message,
                stack: exception.stack || "none"
            };

             // manage your exception
             alert(JSON.stringify(data));


            // Call The original Angular Exception Handler
            $delegate(exception, cause);

       };
   });

});

Demo Plunker

After you can enter some service and transfer all the data of the Exception:

// ...
var someService = $injector.get("SomeService"); 

someService.reportClientError(data).then(function(data) {
               //...
            }, function(error) {
                //...
            }); 

0
source

Something like that? Unfortunately, I cannot check this right now, but the kernel was taken from the anguarJS example code, which describes how to log exceptions

angular.
module('exceptionOverwrite', []).
factory('$exceptionHandler', [function() {
var exceptions = [];
return function myExceptionHandler(exception, cause) {
   if(exceptions.indexOf(exception) !== -1) 
    {// its duplicate do your thing
     }
   this.exceptions.add(exception)
};
}]);
0
source

Source: https://habr.com/ru/post/1686035/


All Articles