Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

AngularJS - dynamic loading of external JS based on routes

Tags:

I am trying to make a simple single page mobile app with multiple views and a next\back button to control each view. I am using the Angular Mobile UI library.

The basic mockup is as follows:

<html>     <head>         <link rel="stylesheet" href="mobile-angular-ui/dist/css/mobile-angular-ui-base.min.css">         <link rel="stylesheet" href="mobile-angular-ui/dist/css/mobile-angular-ui-desktop.min.css">          <script src="js/angular/angular.min.js"></script>         <script src="js/angular/angular-route.min.js"></script>         <script src="mobile-angular-ui/dist/js/mobile-angular-ui.min.js"></script>          <script src="app/app.js"></script>         <script src="app/firstController.js"></script>         <script src="app/secondController.js"></script>         <script src="app/thirdController.js"></script>      </head>      <body ng-app="demo-app">         <div ng-view></div>          <div ng-controller="nextBackController" class="navbar navbar-app navbar-absolute-bottom">             <div class="btn-group justified">               <a href="#/" class="btn btn-navbar btn-icon-only"><i class="fa fa-home fa-navbar"></i></a>               <a href="#/second" class="btn btn-navbar btn-icon-only"><i class="fa fa-list fa-navbar"></i></a>             </div>         </div>      </body>   </html> 

App.js is as follows:

var app = angular.module('demo-app', [   "ngRoute",   "mobile-angular-ui" ]);  app.config(function($routeProvider) {   $routeProvider.when('/', { controller: "firstController",                              templateUrl: "views/first.html"});   $routeProvider.when('/', { controller: "secondController",                              templateUrl: "views/first.html"});   $routeProvider.when('/', { controller: "thirdController",                              templateUrl: "views/first.html"}); });  controllers = {};  controllers.nextBackController = function($scope, $rootScope) {     //Simple controller for the next, back buttons so we just put it in app.js };  app.controller(controllers); 

firstController.js will contain something similar to:

controllers.firstController = function($scope) {     //Do our logic here!!! }; 

The problem is if you notice at the top of the HTML page I have to load all the controllers in. This is not scalable. I want each controller to be in it's own JS file and not have to statically load each one since the user may never even require that controller. Is there a way to dynamically load the actual JS file when switching routes? or can I stick a script tag at the top of my "first.html", "second.html", etc.

like image 613
user3621014 Avatar asked May 14 '14 13:05

user3621014


Video Answer


2 Answers

If I understand correctly you need to load specific scripts for each view? I am sharing this snippet from a personal project that uses ocLazyLoader a plugin that loads modules on demand.

var myApp = angular.module("myApp", [ "ui.router",  "oc.lazyLoad",   ]);  

then in your routing you could load dynamic JS / CSS files accordingly, in this example I am loading the UI Select plugin dependencies

myApp.config(['$stateProvider', '$urlRouterProvider', function($stateProvider, $urlRouterProvider) {  $stateProvider    // State     .state('demo', {         url: "/demo.html",         templateUrl: "views/demo.html",         data: {pageTitle: 'demo page title'},         controller: "GeneralController",         resolve: {             deps: ['$ocLazyLoad', function($ocLazyLoad) {                 return $ocLazyLoad.load([{                     name: 'ui.select',  // add UI select css / js for this state                     files: [                         'css/ui-select/select.min.css',                          'js/ui-select/select.min.js'                     ]                  }, {                     name: 'myApp',                     files: [                         'js/controllers/GeneralController.js'                     ]                  }]);             }]         }     }) 
like image 147
Raja Khoury Avatar answered Oct 10 '22 02:10

Raja Khoury


If you're familiar with Grunt:

https://github.com/ericclemmons/grunt-angular-templates

Use Grunt and the above build task to create one .js from all views. Include a watch task listener over all html files in a views directory. Whenever a change is made to any partial views, a "$templateCache" entry is created with all of the html in the file and a url to alias the cache. Your routes will point to the partial views in the same manner, but the html files do not need to be present. Only the .js file with the templates. The beauty of this is that it loads once and is available on the client side for the entire session. This cuts down on http calls and your traffic can be reduced to web service calls, only.

This is the example of a template from the github link, above:

angular.module('app').run(["$templateCache", function($templateCache) { $templateCache.put("home.html", // contents for home.html ... ); ... $templateCache.put("src/app/templates/button.html", // contents for button.html ); }]); 

If you're not familiar with Grunt

Check it out. It's pretty invaluable for automating builds, minification, concatenation, transpiling, etc...

http://gruntjs.com/

like image 30
Lee Duckworth Avatar answered Oct 10 '22 01:10

Lee Duckworth