1

I have an angularjs app that shows a message box when it detects that more than a certain number of rows have been returned in a web service call. Unfortunately, however, angular appears to go into its digest loop when I call the service, and the message box is displayed three times.

I don't really care what Angular needs to do internally, provided it's not to do with the way I have coded the function. However, I certainly don't want this message box shown (nor the web service called) three times. Examining the call stack each time the function below is called, I can see that the call does not originate with my application code.

How can I detect the state of the loop so that I can ignore calls after the first one?

    function bindResults(expression) {
        var maxRows = 100;
        listData.search(expression, maxRows).then(function (data) {
            $scope.searchResults = data;
            if (data.length == maxRows)
            {
                var title = "Search Warning";
                var msg = "The maximum number of cases was returned, try being more specific";
                var btns = [{ result: 'ok', label: 'OK', cssClass: 'btn-primary' }];

                $dialog.messageBox(title, msg, btns)
                  .open(); 
            }
        });
    };
Paul Taylor
  • 5,651
  • 5
  • 44
  • 68

2 Answers2

3

You can check if a $digest is already in progress by checking $scope.$$phase.

if(!$scope.$$phase) {
   //$digest or $apply
}

See a more detailed answer here:

Answer by Lee

Community
  • 1
  • 1
Aaron Hickman
  • 836
  • 6
  • 16
1

Apologies, the description in the question was a bit of a red herring.

On closer inspection, I discovered that the function is called multiple times not because of the digest loop, but because the UI fragment with which it is associated is a partial view, included via ng-view. This directive creates a separate scope. A separate instance of the controller is also created because $routeProvider is configured (unnecessarily) with the controller option.

See this plunker for an illustration.

Paul Taylor
  • 5,651
  • 5
  • 44
  • 68