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!