How to Use AngularJS to build a single-page application and load JS files as needed

Source: Internet
Author: User

How to Use AngularJS to build a single-page application and load JS files as needed

In AngularJS, we can directly switch the view based on different URLs and dynamically load the webpage template. However, the Controller of the template must be defined first before it can be loaded at the same time as the webpage template, in this way, the JS of the entire website must be loaded first.

RequireJS is the first thing you think of, but it is a little large. Someone on github wrote Angular's dynamic loading controller module through js promise asynchronous programming technology, the final solution is very simple ~~
First, add the resolve attribute to $ routeProvider,

$ RouteProvider. when ('/phones', {templateUrl: 'partials/phone-list.html ', controller: PhoneListCtrl, resolve: PhoneListCtrl. resolve })


Then
Function PhoneListCtrl ($ scope) {// you don't need to worry about it. How can I get it?} PhoneListCtrl. resolve = {delay: function ($ q) {var delay = $ q. defer (), load = function () {$. getScript ('/js/xxxxx. js', function () {delay. resolve () ;}) ;}; load (); return delay. promise ;}}

With this technology, our HybridApp can be divided into static parts packaged in native applications and dynamic parts placed on servers, it is convenient to add some temporary page functions without upgrading the main App. Let's think about the specific application scenarios!

Related Article

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.