What am I missing about using jQuery with Angular's $digest method? - angularjs

I am having trouble understanding using jQuery with Angular's digest cycle.
I am using an ng-repeat= to load content. the content (using $compile) ends up being a div with with two child divs and several grandchild elements. after loading the arrary for the ng-repeat, I want to use jQuery's children.each() like so:
callBack = function(index) {
var objParent = $('#' + $scope.panes[index].windID); //entire window
var objChild = [];
//objChild[0] = title bar
//objChild[1] = contentpane
objParent.children().each(function(i){
objChild[i] = $(this);
});
//more code
}
The problem is that as my open window method got larger with more features, somehow Angular's digest started working differently. What I mean is that before I added my maximize/restore/minimize methods and buttons to match, when my controller got to the code above, the window was already digested through scope and showed in the dom (although hidden with {display: none} for jQuery's fade in) meaning that the above code worked.
However now that there is more going on to be digested, when it gets to that point the digest is not complete, and the child finder fails since that DOM has not been updated yet. I have to use $timeout, and I increasingly have to increase the time. I have to wait around 600ms right now, and I feel that is to slow from icon click to window showing.
Now, If I add a $scope.$apply() right before the $timeout(), it acts like it's just forcing the digest to hurry up. I can reduce the time back to 0ms, and everything works instantly. Yet I get a digest in progress error. I thought the $timeout waited for the end of the digest anyways?
I've tried various methods, even $$postDigest, but the only thing that seems to work is forcing an $apply resulting in a digest in progress error that the end user will never see nor even care about since it actually makes it all work. That would not me so much of a problem, but it bugs me because after opening and closing my window "panes" the digest in progress error can multiply in the console.
Here's a link to a little bit older version: AkadineWebOS
The app is more jQuery than Angular, I'm just using Angular for it's http module and to make it easy to push and splice my window array and let the ng-repeat magic handle the dom. jQuery does all the heavy lifting with dragging, resizing, fadein/out, centering windows on open, and most everything else.
So here is my question: Can someone please explain to me what I am missing about the way that Angular's digest works?

As Claise said, jQuery is not asyc like angular. I actually just had to change the $timeout() to a plain ol' setTimeout(), basically asycing my jQuery callback. Now it works great!

Related

$$phase does not seem to update back to null

I am working on an enterprise Angular application, with Ruby PageObject for testing. The problem we are running into is that sometimes an $interval that we have kicks off the $digest leading to random failures. I am trying to write a Javscript command that the page object can execute to see if a $digest is running. To do this I came up with the following...
angular.element("#application").injector().get('$rootScope').$$phase
This seems to work, however, I wanted to create a plunker to demonstrate the issue, however, this plunker doesn't change from $digest. However when I add the following....
$timeout(function() {
console.log("phase is "+$scope.$root.$$phase);
})
I see it become null, so how can I show that in the UI?
AFAIK You can show $root.$$phase value on UI, but it would be always shown as $digest only, it will never shown as null. Because Angular does run digest cycle for each 50ms to update all data-bindings, you need to look at Databinding in AngularJS.

Late created animations angular

I have some code that creates and registers some animations inside a controller. Unfortunately, whenever I register an animation inside a controller, it does not seem to initialise (The function never gets called.)
I have created a plunker to illustrate the issue. In this, I call"createAnim1" outside the controller and the animation functions correctly. I call "createAnim2" inside a controller, and the animation does not function.
createAnim1();
app.controller('main', function($scope) {
createAnim2(); //This animation does not work
});
The createAnim function are in the form:
app.animation('.anim1', function() {
return {
...
}
});
Am I missing something obvious? The $animate and $animateProvider documentation don't seem to contain anything relevant to this.
I assume this has to do with the fact that a compilation has already happened, and some step required to initialise the animations is being missed? Is there some way to get around this?
PS: I have only been using angular since last week, so I'm not well versed on the internals.
Edit:
After the comments from Alex, I think it is worth clarifying what I am trying to do:
I have some code which generates css class animation selectors and appends them to the document head. If the browser does not support transitions, the code generates a jquery animation equivalent. I have tried to create a factory to expose this code via DI, and it is when this code is run (From inside a controller) the animation is never able to trigger (The initialisation code is never run).

$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

AngularJS's $scope.watch function is not firing on data modification

You can see the problem in this plunk with Chrome or FireFox's console open:
http://plnkr.co/edit/jmDcxqQ48PmeHt3EPVMU
When you click "Push!" for the first time, the watch function doesn't execute. But if you push it again, it does execute. It's like it ignores the first push. However, you can clearly see the dataPoints array changes after the first push due to the timeout function that is executing in the background. What's weirder, is if you comment out the jQuery fadeIn wrapper, the code works as expected (the watch function is executed on the first button push).
What's going on here? Why is the $watch function not executing when jQuery().fadeIn is used?
jQuery('#mytest').fadeIn(200, function() {
$scope.mydata.dataPoints.push(1);
$scope.$$phase || $scope.$apply();
})
When the fadeIn callback runs, it runs "outside" Angular, so we need to call $scope.$apply() to run a digest cycle. However, if the object is already visible, it seems that jQuery runs the callback immediately (so we're still "inside" Angular), so we don't need to (and shouldn't) call $scope.$apply().
The easy way to handle both cases is to check to see if we are already in a digest cycle using private property $$phase. A cleaner implementation would be to not call fadeIn() if the div is already visible.

How do I use $scope.$watch and $scope.$apply in AngularJS?

I don't understand how to use $scope.$watch and $scope.$apply. The official documentation isn't helpful.
What I don't understand specifically:
Are they connected to the DOM?
How can I update DOM changes to the model?
What is the connection point between them?
I tried this tutorial, but it takes the understanding of $watch and $apply for granted.
What do $apply and $watch do, and how do I use them appropriately?
You need to be aware about how AngularJS works in order to understand it.
Digest cycle and $scope
First and foremost, AngularJS defines a concept of a so-called digest cycle. This cycle can be considered as a loop, during which AngularJS checks if there are any changes to all the variables watched by all the $scopes. So if you have $scope.myVar defined in your controller and this variable was marked for being watched, then you are implicitly telling AngularJS to monitor the changes on myVar in each iteration of the loop.
A natural follow-up question would be: Is everything attached to $scope being watched? Fortunately, no. If you would watch for changes to every object in your $scope, then quickly a digest loop would take ages to evaluate and you would quickly run into performance issues. That is why the AngularJS team gave us two ways of declaring some $scope variable as being watched (read below).
$watch helps to listen for $scope changes
There are two ways of declaring a $scope variable as being watched.
By using it in your template via the expression <span>{{myVar}}</span>
By adding it manually via the $watch service
Ad 1)
This is the most common scenario and I'm sure you've seen it before, but you didn't know that this has created a watch in the background. Yes, it had! Using AngularJS directives (such as ng-repeat) can also create implicit watches.
Ad 2)
This is how you create your own watches. $watch service helps you to run some code when some value attached to the $scope has changed. It is rarely used, but sometimes is helpful. For instance, if you want to run some code each time 'myVar' changes, you could do the following:
function MyController($scope) {
$scope.myVar = 1;
$scope.$watch('myVar', function() {
alert('hey, myVar has changed!');
});
$scope.buttonClicked = function() {
$scope.myVar = 2; // This will trigger $watch expression to kick in
};
}
$apply enables to integrate changes with the digest cycle
You can think of the $apply function as of an integration mechanism. You see, each time you change some watched variable attached to the $scope object directly, AngularJS will know that the change has happened. This is because AngularJS already knew to monitor those changes. So if it happens in code managed by the framework, the digest cycle will carry on.
However, sometimes you want to change some value outside of the AngularJS world and see the changes propagate normally.
Consider this - you have a $scope.myVar value which will be modified within a jQuery's $.ajax() handler. This will happen at some point in future. AngularJS can't wait for this to happen, since it hasn't been instructed to wait on jQuery.
To tackle this, $apply has been introduced. It lets you start the digestion cycle explicitly. However, you should only use this to migrate some data to AngularJS (integration with other frameworks), but never use this method combined with regular AngularJS code, as AngularJS will throw an error then.
How is all of this related to the DOM?
Well, you should really follow the tutorial again, now that you know all this. The digest cycle will make sure that the UI and the JavaScript code stay synchronised, by evaluating every watcher attached to all $scopes as long as nothing changes. If no more changes happen in the digest loop, then it's considered to be finished.
You can attach objects to the $scope object either explicitly in the Controller, or by declaring them in {{expression}} form directly in the view.
Further readings:
Make Your Own AngularJS, Part 1: Scopes And Digest
In AngularJS, we update our models, and our views/templates update the DOM "automatically" (via built-in or custom directives).
$apply and $watch, both being Scope methods, are not related to the DOM.
The Concepts page (section "Runtime") has a pretty good explanation of the $digest loop, $apply, the $evalAsync queue and the $watch list. Here's the picture that accompanies the text:
Whatever code has access to a scope – normally controllers and directives (their link functions and/or their controllers) – can set up a "watchExpression" that AngularJS will evaluate against that scope. This evaluation happens whenever AngularJS enters its $digest loop (in particular, the "$watch list" loop). You can watch individual scope properties, you can define a function to watch two properties together, you can watch the length of an array, etc.
When things happen "inside AngularJS" – e.g., you type into a textbox that has AngularJS two-way databinding enabled (i.e., uses ng-model), an $http callback fires, etc. – $apply has already been called, so we're inside the "AngularJS" rectangle in the figure above. All watchExpressions will be evaluated (possibly more than once – until no further changes are detected).
When things happen "outside AngularJS" – e.g., you used bind() in a directive and then that event fires, resulting in your callback being called, or some jQuery registered callback fires – we're still in the "Native" rectangle. If the callback code modifies anything that any $watch is watching, call $apply to get into the AngularJS rectangle, causing the $digest loop to run, and hence AngularJS will notice the change and do its magic.
AngularJS extends this events-loop, creating something called AngularJS context.
$watch()
Every time you bind something in the UI you insert a $watch in a $watch list.
User: <input type="text" ng-model="user" />
Password: <input type="password" ng-model="pass" />
Here we have $scope.user, which is bound to the first input, and we have $scope.pass, which is bound to the second one. Doing this we add two $watches to the $watch list.
When our template is loaded, AKA in the linking phase, the compiler will look for every directive and creates all the $watches that are needed.
AngularJS provides $watch, $watchcollection and $watch(true). Below is a neat diagram explaining all the three taken from watchers in depth.
angular.module('MY_APP', []).controller('MyCtrl', MyCtrl)
function MyCtrl($scope,$timeout) {
$scope.users = [{"name": "vinoth"},{"name":"yusuf"},{"name":"rajini"}];
$scope.$watch("users", function() {
console.log("**** reference checkers $watch ****")
});
$scope.$watchCollection("users", function() {
console.log("**** Collection checkers $watchCollection ****")
});
$scope.$watch("users", function() {
console.log("**** equality checkers with $watch(true) ****")
}, true);
$timeout(function(){
console.log("Triggers All ")
$scope.users = [];
$scope.$digest();
console.log("Triggers $watchCollection and $watch(true)")
$scope.users.push({ name: 'Thalaivar'});
$scope.$digest();
console.log("Triggers $watch(true)")
$scope.users[0].name = 'Superstar';
$scope.$digest();
});
}
http://jsfiddle.net/2Lyn0Lkb/
$digest loop
When the browser receives an event that can be managed by the AngularJS context the $digest loop will be fired. This loop is made from two smaller loops. One processes the $evalAsync queue, and the other one processes the $watch list. The $digest will loop through the list of $watch that we have
app.controller('MainCtrl', function() {
$scope.name = "vinoth";
$scope.changeFoo = function() {
$scope.name = "Thalaivar";
}
});
{{ name }}
<button ng-click="changeFoo()">Change the name</button>
Here we have only one $watch because ng-click doesn’t create any watches.
We press the button.
The browser receives an event which will enter the AngularJS context
The $digest loop will run and will ask every $watch for changes.
Since the $watch which was watching for changes in $scope.name
reports a change, it will force another $digest loop.
The new loop reports nothing.
The browser gets the control back and it will update the DOM
reflecting the new value of $scope.name
The important thing here is that EVERY event that enters the AngularJS context will run a $digest loop. That means that every time we write a letter in an input, the loop will run checking every $watch in this page.
$apply()
If you call $apply when an event is fired, it will go through the angular-context, but if you don’t call it, it will run outside it. It is as easy as that. $apply will call the $digest() loop internally and it will iterate over all the watches to ensure the DOM is updated with the newly updated value.
The $apply() method will trigger watchers on the entire $scope chain whereas the $digest() method will only trigger watchers on the current $scope and its children. When none of the higher-up $scope objects need to know about the local changes, you can use $digest().
I found very in-depth videos which cover $watch, $apply, $digest and digest cycles in:
AngularJS - Understanding Watcher, $watch, $watchGroup, $watchCollection, ng-change
AngularJS - Understanding digest cycle (digest phase or digest process or digest loop)
AngularJS Tutorial - Understanding $apply and $digest (in depth)
Following are a couple of slides used in those videos to explain the concepts (just in case, if the above links are removed/not working).
In the above image, "$scope.c" is not being watched as it is not used in any of the data bindings (in markup). The other two ($scope.a and $scope.b) will be watched.
From the above image: Based on the respective browser event, AngularJS captures the event, performs digest cycle (goes through all the watches for changes), execute watch functions and update the DOM. If not browser events, the digest cycle can be manually triggered using $apply or $digest.
More about $apply and $digest:
There are $watchGroup and $watchCollection as well. Specifically, $watchGroup is really helpful if you want to call a function to update an object which has multiple properties in a view that is not dom object, for e.g. another view in canvas, WebGL or server request.
Here, the documentation link.
Just finish reading ALL the above, boring and sleepy (sorry but is true). Very technical, in-depth, detailed, and dry.
Why am I writing? Because AngularJS is massive, lots of inter-connected concepts can turn anyone going nuts. I often asked myself, am I not smart enough to understand them? No! It's because so few can explain the tech in a for-dummie language w/o all the terminologies!
Okay, let me try:
1) They are all event-driven things. (I hear the laugh, but read on)
If you don't know what event-driven is Then
think you place a button
on the page, hook it up w/ a function using "on-click", waiting for
users to click on it to trigger the actions you plant inside the
function. Or think of "trigger" of SQL Server / Oracle.
2) $watch is "on-click".
What's special about is it takes 2 functions as parameters, first one
gives the value from the event, second one takes the value into
consideration...
3) $digest is the boss who checks around tirelessly,
bla-bla-bla but a good boss.
4) $apply gives you the way when you want to do it manually, like a fail-proof (in case on-click doesn't kick in, you force it to run.)
Now, let's make it visual. Picture this to make it even more easy to
grab the idea:
In a restaurant,
- WAITERS
are supposed to take orders from customers, this is
$watch(
function(){return orders;},
function(){Kitchen make it;}
);
- MANAGER running around to make sure all waiters are awake, responsive to any sign of changes from customers. This is $digest()
- OWNER has the ultimate power to drive everyone upon request, this is $apply()

Resources