1. Starting stage
Everyone should know that when the browser loads an HTML page, it will first parse the HMTL page into a DOM tree, and then load each element node in the DOM tree one by one. We can treat AngularJS as a js library similar to jQuery. We introduce it into HTML through the <script> tag. At this time, Angular will be an ordinary DOM node waiting for the browser to parse. When the browser parses this node and finds that it is a js file, the browser will stop parsing the remaining DOM nodes and start executing this js (i.e. angular.js). At the same time, Angular will set up an event listener to listen to the browser's DOMContentLoaded event. When Angular listens to this event, the Angular application will be started.
2. Initialization stage
After Angular starts, it looks for the ng-app directive, then initializes a series of necessary components (i.e. $injector, $compile service, and $rootScope), and then starts parsing the DOM tree again.
3. Compile and link
The $compile service finds DOM elements with declared instructions by traversing the DOM tree. When encountering a DOM element with one or more instructions, it sorts the instructions (based on the instruction's priority) and then uses the $injector service to find and collect the compile function of the instruction and execute it.
After each node's compilation method is run, the $compile service will call the link function. This link function sets monitoring for instructions that are bound to a closed scope. This behavior creates a live view.
Finally, after the $compile service is complete, the AngularJS runtime is ready.
4. Operation stage
Angular provides its own event loop. The instruction itself registers the event listener, so when the event is triggered, the instruction function will run in the $digest loop of AngularJS. The $digest loop will wait for the $watch expression list. When the model changes are detected, the $watch function will be called, and then the $watch list is viewed again to ensure that no model has been changed.
Once the $digest loop stabilizes and no potential changes are detected, the execution process leaves the Angular context and usually returns to the browser, and the DOM will be rendered here.
Draw the key steps of the above process into a graph, as follows:
The above is a detailed introduction to the AngularJS execution process. We will continue to organize relevant information in the future. Thank you for your support for this website.