ANGULARJS Routing Asynchronous loading JS

Source: Internet
Author: User

This problem first comes out when I put require into the project is, want to do click on the route to load the corresponding page HTML and JS.

At first I was setting the controller of the route to require (' controller.js ') to load asynchronously,

Of course, the problem is not so simple, there must be some problems.

So there is a problem, when I am routing sub-page in the data-related initialization, the first jump is normal, when jumping to another page, and then jump back to the page controller data is not available.

Causes the page to be blank.

$routeProvider. When ('/quick_set ', {           ' layout/quick_set.html ',           controller:require (' Quick_set ')  })

I also read a lot of blogs about this problem and found the following solutions.

Using the Angularjs built-in $q service, similar to the promise in Es6, that is, to create an asynchronous load, return to promise after loading, the promise to determine whether to successfully load JS, successfully loaded and then assigned to the controller,

The program is written in the resolve of the route.

1 $routeProvider. When ('/quick_set ', {2                 templateurl: ' layout/quick_set.html ',  3                 controller: ' Quick_set ',4                resolve: {5                     LoadController:app.asyncJS (' Quick_set ')  //Join the asynchronous request here 6                }7             })
1App.asyncjs =function(JS) {2   return function($q) {3         varDeferred =$q. Defer ();4Require ([JS],function(Controller) {5$controllerProvider. Register (JS, Controller);//because it is a dynamically loaded controller, you must first register and then use the6 deferred.resolve ();//marks the returned promise as a resolve state, which is the success status, reject Ask the Deny state. 7         });8        returndeferred.promise;9   }Ten}

This has succeeded in solving the problem.

ANGULARJS Routing Asynchronous loading JS

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.