AngularJS - dynamic loading of external JS based on routes - javascript

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">
<i class="fa fa-home fa-navbar"></i>
<i class="fa fa-list fa-navbar"></i>
</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.

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'
]
}]);
}]
}
})

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/

Unless your app is MASSIVE, you should REALLY avoid serving small js files individually. This will noticeably slow down your app, even if you were to figure out a way to lazily fetch files on an as-needed basis as you suggest in your question.
A much better way to do this (and the way used and suggested by the AngularJS team) is to have a BUILD PROCESS (you should use grunt for this) concatenate all your javascript files, and serve them as a single app.js file. This way you can maintain an organized code base with as many tiny js files as you want, but reduce script fetching to a single request.

How to Install OCLazyLoad.
1. Download ocLazyLoad.js here
It can be found in the 'dist' folder of the git repository. You can also install it with bower install oclazyload or npm install oclazyload.
2. Add the module oc.lazyLoad to your application:
var myApp = angular.module("MyApp", ["oc.lazyLoad"]);
3. Load your JS files on demand, based on routes:
myApp.controller("MyCtrl", function($ocLazyLoad){
$ocLazyLoad.load('testModule.js');
}});`
With $ocLazyLoad you can load angular modules, but if you want to load any component (controllers / services / filters / ...) without defining a new module it's entirely possible (just make sure that you define this component within an existing module).
There are multiple ways to use $ocLazyLoad to load your files, just choose the one that you prefer.
Also don't forget that if you want to get started and the docs are not enough, see the examples in the 'examples' folder!
Quick Start

RequireJS can be really useful in this case.
You can declare the dependencies of your JS files using RequireJS.
You can refer this simple tutorial.

I think the best way is use RequireJS, as mentioned here Does it make sense to use Require.js with Angular.js? It is totally allowed and it will let you reach what you are trying.
here is an example code
https://github.com/tnajdek/angular-requirejs-seed

I am not sure how it works in standard angular, however, you could use angular-ui-router:
Controllers are instantiated on an as-needed basis, when their corresponding
scopes are created, i.e. when the user manually navigates to a state via a URL,
$stateProvider will load the correct template into the view, then bind the
controller to the template's scope.
https://github.com/angular-ui/ui-router/wiki

Related

Should i include all the script tags for all the controllers in index.html? [duplicate]

This question already has answers here:
Angularjs add controller dynamically
(3 answers)
Closed 3 years ago.
I'm creating a SPA with angularjs and have a separate folder for each feature in the administration panel that contains the partial view and the controller like so:
files and folders structure
The problem i'm facing now is i find my self having to add a script tag which references all the .JS files of all the controllers.
<script src="assets/js/angular.min.js"></script>
<script src="app.js"></script>
<script src="views/clients/clients_controller.js"></script>
<script src="views/clients/orders_controller.js"></script>
This means that if the user is viewing the client data, the whole scripts for the orders, the products, etc..... will be loaded.
Now if I reached a point where i have about 100 or so controllers in my app it will be a huge amount of JS scripts loaded for no reason at all.
I'm sorry I've been programming for about 17 years, started with php to python and I've used angularjs before as a part of ionic framework app but never as a web application
also it's my first time ever I ask a question on stack overflow so please bear with me and thanks in advance.
For this problem we can use oclazyload:
var app = angular.module("app", ["ui.router","oc.lazyLoad"]);
In this example we have ui-router to changes route and with each route we load state files as controller or service
$stateProvider.state("main", {
url: "/",
templateUrl: "view.html",
controller: "mainController",
resolve: {
loadMyCtrl: ["$ocLazyLoad", function ($ocLazyLoad) {
return $ocLazyLoad.load({
files: ["mainController.js"] //["mainController.js", "mainService.js"]
});
}]
}
});
Here is how you can lazy load controllers without using any library.
First get a reference of your control provider where you bootstrap the app. You can attach this to your app object itself.
var myApp = angular.module('myapp', [])
.config(['$controllerProvider', function($controllerProvider) {
myApp.controlProvider = $controllerProvider;
}]);
Now put your controller in to .js or inside a script in an html file you want to add to the DOM - or, maybe in a route.
myApp.controlProvider.register('my-lazy-controller', ['$scope', function($scope) {
}])
If you don't want to use this in a route, load this new script or html using an appropriate method. You can use jQuery .load() if your have the controller in an html file or jQuery getScript() for loading .js file

Angular - scripts load order

I've just started with Angular after many years working with MVC. I'm quite familiar with js, HMTL but still beginner in the Angular world.
I lost 3 hours trying to figure out what is wrong with my app.
So the app has 3 files
index.html
<body ng-app="perica">
<p>main</p>
{{ tagline }}
<a ng-click="logOut();">Logout</a>
<div ng-view><p>inside</p></div>
</body>
<script type="text/javascript" src="../components/angular/angular.js"></script>
<script type="text/javascript" src="../AgularApp.js"></script>
<script type="text/javascript" src="../controllers/AcountController.js">
AngularApp.js
debugger;
angular.module('perica', ['ngRoute']).config(['$routeProvider','$locationProvider', function ($routeProvider, $locationProvider) {
console.log('in');
debugger;
$routeProvider.when('/test', {
templateUrl: 'views/Account/_Login.html'
})
$locationProvider.html5Mode(true);
}]);
and AccountController.js
var myApp = angular.module('perica', []);
myApp.controller('AcountController', ['$scope', function ($scope) {
$scope.tagline = 'The square root of life is pi!';
}]);
So as you can see it is a super simple application.
By all the coding logic, I should load angular core scripts the first, then my angular app and at the end angularcontroles.
When I run the app, Chrome hit the first debugger (above angular.module inside AngularApp.js file) and jumped straight into AccountContoler.js and completely ignored what is defined inside of the AngularApp.js.
but
When I reversed paths and put first AccountController.js and afterwards AngularApp.js everything worked without any issue
I would be really grateful if someone can shed some light on this issue
Thanks!
By using...
var myApp = angular.module('perica', [])
... in your AccountController.js, you're not loading your already existing 'perica' application (declared in the previously loaded AngularApp.js):
you are re-defining the perica application.
The correct way to refer to your already existing module is using:
angular.module('perica')
^
no dependency declared
instead of:
angular.module('perica', [])
^
dependencies
The logic behind this is quite simple once you're acquainted to it: if you're declaring dependencies while "loading" a module, you're creating that module. Otherwise, you're referring to it.
TL;DR: You're basically using a setter here twice and never actually enhancing your existing module.
Here's a working JSFiddle (link) with your application running. I loaded AngularJS directly from the Javascript framework/extensions menu and referred to an external JS resource for angular-route (fetched from cdnjs: https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.4.8/angular-route.min.js).
I basically simply concatenated both your AngularApp.js and AccountController.js contents to emulate loading them one after the other.
Please note that your also have to declare the controller that controls your view: I took the liberty to enhance your <body ng-app="perica"> element as follows:
<body ng-app="perica" ng-controller="AcountController">

AngularJS and Webpack Integration

I am looking for some help with using webpack for a large AngularJS application. We are using folder structure based on feature (each feature/page has a module and they have controllers, directives). I have successfully configured webpack to get it working with Grunt, which produces one single bundle. I want to create chunks as its going to be a large app, we would like to load modules (page/feature) artifacts asynchronously.
I am going through some of the webpack example to use 'code splitting' using require([deps],fn ) syntax. However I couldn't get the chunks lazy-loaded. First of all, I don't know where exactly, I would need to import these chunks before AngularJS would route the user to next page. I am struggling to find a clear separation of responsibility.
Did someone point me to an example AngularJS application where webpack is used to load controllers/directives/filters asynchronously after each route?
Few of the links I am following:
Should I use Browserify or Webpack for lazy loading of dependancies in angular 1.x
https://github.com/petehunt/webpack-howto#9-async-loading
http://dontkry.com/posts/code/single-page-modules-with-webpack.html
Sagar Ganatra wrote a helpful blog post about code splitting.
Suprisingly code splitting isn't really supported by angular's module system. However, there is a way to achieve code splitting by saving a reference to angular's special providers during the config-phase.
[...] when Angular initializes or bootstraps the application, functions - controller, service etc,. are available on the module instance. Here, we are lazy loading the components and the functions are not available at a later point; therefore we must use the various provider functions and register these components. The providers are available only in the config method and hence we will have to store a reference of these providers in the config function when the application is initialized.
window.app.config([
'$routeProvider',
'$controllerProvider',
'$compileProvider',
'$filterProvider',
'$provide',
function ($routeProvider, $controllerProvider, $compileProvider, $filterProvider, $provide) {
$routeProvider.when('/login', {
templateUrl: 'components/login/partials/login.html',
resolve: {
load: ['$q', '$rootScope', function ($q, $rootScope) {
var deferred = $q.defer();
// lazy load controllers, etc.
require ([
'components/login/controllers/loginController',
'components/login/services/loginService'
], function () {
$rootScope.$apply(function () {
deferred.resolve();
});
});
return deferred.promise;
}]
}
});
//store a reference to various provider functions
window.app.components = {
controller: $controllerProvider.register,
service: $provide.service
};
}
]);
Now inside your loginController for instance you write
app.components.controller('loginController');
to define your new controller lazily.
If you want to lazy-load your templates too I recommend to use the ui-router. There you can specify a templateProvider which is basically a function to load templates async
This is a quote from
https://github.com/webpack/webpack/issues/150
webpack is a module bundler not a javascript loader. It package files from local disk and don't load files from the web (except its own chunks).
Use a javascript loader, i. e. script.js
var $script = require("scriptjs");
$script("//ajax.googleapis.com/ajax/libs/angularjs/1.2.9/angular.min.js", function() {
// ...
});

Angular $routeProvider override-able fallback routes

I'm creating my first sizable angular project, so I've opted to break out my angular application code into directories like so:
app/
calendar/
calendar.js
contacts/
contacts.js
companies/
companies.js
...
app.js
Each of these directories will include a handful of files for views (.html), directives, services, etc.
In my app.js file, I want to setup default routes that will be used maybe 80% of the time, like this:
$routeProvider
.when('/:page', {
templateUrl: function($routeParams) {
return 'app/' + $routeParams.page + '/index.html';
},
controller: 'PageController'
})
However, I want the ability to "override" that route from within my modules so I can do things like swap out the controller, do dependency injection stuff, and so on. I would like that sort of logic contained within the module itself to keep things...well...modular, so I would rather not define each module's routing logic within app.js. So for example, in my app/calendar/calendar.js file I want to say:
$routeProvider
.when('/calendar', {
templateUrl: 'app/calendar/index.html',
controller: 'CalendarIndexController',
resolve: { ... }
})
The problem is that the definition in app.js is matched against the location first, so this calendar route is never used.
To achieve this, right now I'm just including an extra file after all of my module javascript files that sets up my fallback routes last, but this seems a little clunky. Is there anyway to define the routes within app.js so that they are override-able?
You might be able to adapt this technique for dynamically loading controllers described by Dan Wahlin here http://weblogs.asp.net/dwahlin/dynamically-loading-controllers-and-views-with-angularjs-and-requirejs combined with your default routes where the parameter controls which view to load. You could pass the same page parameter to the resolve function to control which combination of view and controller to serve up?

migrating angular to angular2 without changing project structure

i had my web app and cordova mobile app running now on angular 1 for about 2 years now, as application grow bigger we wanted to migrate our next version of app to angular 2.
current project is structured like following
----/root
|__app
|____app.js
|____app.css
|____index.html
|____app.common.directives.js
|____app.common.services.js
|____Page1
|______Page1.js
|______Page1.css
|______Page1.service.js
|______Page1.html
|____Page2
|______Page2.js
|______Page2.css
|______Page2.service.js
i had gulp building my app like so
it concat all js files into build/build.min.js
it concat all css files into build/build.min.css
cache all html in app folder and append it to build.min.js using templateCache (angular1)
copy index.html from app folder to build folder.
run watch server root # /build
This setup was very useful for us since when ever we are working on a new Module (a page essentially) all we have to do is create a new folder, drop a js and html file, and we are done !
example Page1.js
angular.module('mainApp')
.config(function($httpProvider, $stateProvider) {
$stateProvider.state('Page1', {
url: '/Page1',
controller: 'Page1Ctrl',
controllerAs: 'Page1',
templateUrl: 'Page1/Page1.html'
});
}).run(function($rootScope) {
$rootScope.sideMenu.push({
link: 'blog',
title: 'Announcements',
icon: 'bullhorn',
sideMenuOrder: 1
});
})
.controller('BlognewPost', function($server, $http, $scope,$state) {
var self = this;
this.method1 = function(){};
this.var1 = 'Hello Angular';
});
as you can see every module define its own routes, add it self to $rootScope.sideMenu -which is used in index.html to show sidemenu- and defines its own controller.
and our app.js was the main app file which wire connect modules/pages together, yet it was important to keep app.js un aware of how many pages/routes our app has.
angular.module('mainApp',['ngAnimate','ngMessages', 'ngAria'])
.config(function() {/*...*/})
.run(function($rootScope) {
$rootScope.sideMenu = [];
});
index.html is something like.
<html>
<ul id="side">
<li ng-for="item in $root.sideMenu" ui-sref="item.link">...</li>
</ul>
<ui-view id="content"></ui-view>
</html>
Question:
now with new angular2 component structure. is there a way we can migrate our old app while keeping same structure and build system ?
is it possible to define all routes in the components without root component have any knowledge of its existence ? -in above example you can see when ever we needed to add a page, we never touch app.js, we just create a new folder, and add the config, routes, run, and controller in its own folder.
our app is composed of 16 root pages making around 500k character compressed. should we rewrite the whole thing at once, or is there a way to migrate page by page ?
i see in angular2 starter component takes templateUrl config to point to template, is there a way to make typescript include the templateUrl html file as a string 'behavior like what templateCache used to do in angular1' ?
#Component({
selector: 'my-app',
template: string // OR templateUrl: 'page.html'
//what i need is something like template: require(page.html) so that my app html would be cached in js.

Categories

Resources