Find `$apply` or `$digest` invoker - angularjs

I'm looking for at way to track down the pesky error of
apply/digest is already in progress
I'm familier with not using the anti-pattern and have check my codebase for nested apply's/digest's.
The problem lies in third-party plugins in this case FormEditor and Flatpickr. I have nested FlatPickr (with angular add-on) into a formEditor cshtml file which gives me the pesky error.
Is there a way to track the location of all the invokation of apply and/or digest that are present in my project?
Or does anyone have a solution to formEditor with flatPickr and flatpickr angular add-on?
FormEditor: https://github.com/kjac/FormEditor FlatPickr: https://github.com/chmln/flatpickr FlatPickr add-on: https://www.npmjs.com/package/angular-flatpickr
SOLUTION:
The problem was a $apply called by an eventListener which injected the apply into the running apply/digest. Used $timeout as suggested in the answer marked as correct.
The location was found by looking into the error log as suggested in comments

AngularJS automatically triggers a $digest cycle in many cases (after ng-click triggered for example) so the solution is not to find all the "apply / digest" in your code because it won't help you to prevent this error.
The right approach is to control 3rd parties calls to $apply method.
One approach can be wrapping $apply call with a safety check:
if(!$scope.$$phase) {
// place 3rd party updates to scope here
$scope.$apply();
}
The problem with this method is that sometimes you code won't be called.
The better approach will be to wrap it with $timeout 0:
$timeout(function(){
// place 3rd party updates to scope here
});
This way you merged more naturally into angular digest cycle.

Related

$on Not Communicating With $Scope When Used With ng-include

Basically, I am unable to update my controller information when I listen for the $on event if I loaded my html dynamically using ng-include. Plunker example.
If you click once, you'll see the view keeps the original $scope.name. If you click again it will update.
I put a setTimeout on the broadcast to make sure the ng-include was loaded. You can set that to as long as you want, and will never be able to update the $scope on the first try (at least in my example).
Thoughts?
EDIT:
I'm using <ng-include="template"></ng-template>
As an area I can load alternate content in. If there is a better way to do this, please let me know.
setTimeout() is a function out of the control of AngularJS, so AngularJS will not automatically run a digest after the callback runs. That means, your $rootScope.$broadcast() was run, but AngularJS didn't realize that. The next time when you use $rootScope.template = '....';, a digest runs, and the view was updated to the previous run's model.
To solve the problem, you will need to manually call $scope.$apply() at the end of your setTimeout() callback, or use the Angular-wrapped version of setTimeout(), which is $timeout(), that will automatically run a digest afterwards.
Please refer to the docs for more details about digest/apply:
It works for me if you use $timeout instead of setTimeout. Which you should be using for angular applications.
$timeout(function(){
$rootScope.$broadcast('BROADCAST', param);
}, 1000);
There is definitely something wrong with your design if you are trying to do something like this though. Perhaps someone could suggest an alternate solution if you better explained what you are trying to achieve. As you cannot possibly know how long the timeout should be.
A few things:
1) First, do not define the $scope.template in the broadcast function. The ngInclude will not have a file to display until that value is set; so from it makes sense--in my mind--that the template would not be able to make changes before it and the controller are loaded.
2) You never actually apply Controller C2 to the ngInclude. You can do that like:
<ng-include src="template" ng-controller="c2"></ng-include>
Once I do these two things, the code works and updates the first time without the use of the setTimeout() at all.
Plunker

When will AngularJS trigger dirty-checks?

I've read this Q/A about databinding and $apply -> $digest in AngularJS :
How does data binding work in AngularJS?
While I understand the principle and the consequences, I'm still unsure about when AngulaJS is going to call $digest to do the dirty-checks. (And so, when should I consider to do something about the $watcher)
Every example I found was about using 'ng-click', 'ng-show', or 'ng-class'. But I'm pretty sure that it is also triggered by any change on variables of the scope ({{myData}}), and by many others directives (All of them maybe ?).
I would like to understand in which cases a $digest is called.
Can you give me any generic rule to knwo when it is called, or an exhaustive list of actions that will trigger a dirty-check ?
Have a look at this:
angularjs docs, specifically at "Integration with the browser event loop" section.
Basically the way it works is that AngularJS binds event handlers to any element that interacts with angular (any element that has a directive attached to it) and every time that event fires, $apply is called which internally calls $digest which will trigger the reevaluation of all the $watches which will check for values changed, etc...

Decorating Angular-UI Bootstrap modal

I have a feature that I am building that is about 90% of the functionality the Angular-UI Bootstrap Modal provides. The only difference is:
The modal needs to be positioned relative to a container div (I've already handled the styling aspect with the windowClass)
At issue is that the $modalStack service hard codes the body.append call, as seen here:
body.append(modalDomEl)
body.addClass(OPENED_MODAL_CLASS)
Step one is here
I started by simply copying / pasting the open methods on each service (renaming as openWithinElement), and modifying what I needed to make it work. As you can see, if you run the app, it throws an error on the $q dependency not being defined. Okay, I guess that makes sense.
Next I added the dependencies to the provider.decorator method, which bypassed all dependency errors. But then I was getting another error, function getTemplatePromise is undefined ... well of course it isn't defined. It's an internal method to the service.
That's when I got truly stuck. It seems impossible to decorate this service with a new method, without redefining all of the private functions / objects / props within the service.
Is that the case?
[EDIT TO ADD]
I ultimately ended up decorating the service with an updateParentElement method, which then moved the modal to the passed in element, which was executed in the .opened promise. It's hacky, but works, but I'm hoping there's something I'm missing with decorators.
[/EDIT]
The simplest solution as I see it will be to provide specific windowClass, then after dialog is open find its element by that class and move it to the container.

Angular $scope.$apply vs $timeout as a safe $apply

I'm trying to better understand the nuances of using the $timeout service in Angular as a sort of "safe $apply" method. Basically in scenarios where a piece of code could run in response to either an Angular event or a non-angular event such as jQuery or some standard DOM event.
As I understand things:
Wrapping code in $scope.$apply works fine for scenarios where you
aren't already in a digest loop (aka. jQuery event) but will raise an error if a digest is in progress
Wrapping code in a $timeout() call with no delay parameter works whether already in a digest cycle or not
Looking at Angular source code, it looks like $timeout makes a call to $rootScope.$apply().
Why doesn't $timeout() also raise an error if a digest cycle is already in progress?
Is the best practice to use $scope.$apply() when you know for sure that a digest won't already be in progress and $timeout() when needing it to be safe either way?
Is $timeout() really an acceptable "safe apply", or are there gotchas?
Thanks for any insight.
Looking at Angular source code, it looks like $timeout makes a call to
$rootScope.$apply().
Why doesn't $timeout() also raise an error if a digest cycle is already in progress?
$timeout makes use of an undocumented Angular service $browser. Specifically it uses $browser.defer() that defers execution of your function asynchronously via window.setTimeout(fn, delay), which will always run outside of Angular life-cycle. Only once window.setTimeout has fired your function will $timeout call $rootScope.$apply().
Is the best practice to use $scope.$apply() when you know for sure that a digest won't already be in progress and $timeout() when needing it to be safe either way?
I would say so. Another use case is that sometimes you need to access a $scope variable that you know will only be initialized after digest. Simple example would be if you want to set a form's state to dirty inside your controller constructor (for whatever reason). Without $timeout the FormController has not been initialized and published onto $scope, so wrapping $scope.yourform.setDirty() inside $timeout ensures that FormController has been initialized. Sure you can do all this with a directive without $timeout, just giving another use case example.
Is $timeout() really an acceptable "safe apply", or are there gotchas?
It should always be safe, but your go to method should always aim for $apply() in my opinion. The current Angular app I'm working on is fairly large and we've only had to rely on $timeout once instead of $apply().
If we use $apply heavily in the application, we might get the Error: $digest already in progress. It happens because one $digest cycle can be run at a time. We can resolve it by $timeout or by $evalAsync.
The $timeout does not generate error like "$digest already in progress“ because $timeout tells Angular that after the current cycle, there is a timeout waiting and this way it ensures that there will not any collisions between digest cycles and thus output of $timeout will execute on a new $digest cycle.
I tried to explain them at : Comparison of apply, timeout,digest and evalAsync.
May be it will help you.
As far as I understand it, $timeout is a wrapper around setTimeout which implicitly calls $scope.$apply, meaning it runs outside of the angular lifecycle, but kickstarts the angular lifecycle itself. The only "gotcha" I can think of is that if you're expecting your result to be available this $digest, you need to find another way to "safe apply" (which, AFAIK, is only available via $scope.$$phase).

which event fires when AngularJS is done rendering?

I have an application where I need to to some computation based on the final height of the content. Is there a generic event that fires when Angular is done rendering the current scope? Alternatively, is there a way to get notified if the DOM will no longer be modified (but is not nessecarily rendered yet)?
To clarify: I am not looking for an equivalent of DOM ready. ideally I'd like a notification every time any model changes have propagated to the dom. I am aware that i can watch angular expressions and have built a workaround that basically gets called x milliseconds after the last call of a watcher on a given expression. I thought however that there is a more 'angular way' to do that.
Angular has not provided a way to trigger an event when a page finished loading.
I found a great answer by Lior
who says "Angular hasn't provided a way to signal when a page finished loading, maybe because 'finished' depends on your application..."
full answer here.

Resources