angular-ui-router with requirejs, lazy loading of controller - angularjs

Could you help me to understand how to load controller in the example below before the view? It looks like the view is loaded just immediately while the controller is not loaded yet.
//app.js
$stateProvider.state('index', {
url: "/",
views: {
"topMenu": {
templateUrl: "/Home/TopMenu",
controller: function($scope, $injector) {
require(['controllers/top-menu-controller'], function(module) {
$injector.invoke(module, this, { '$scope': $scope });
});
}
}
}
});
//top-menu-controller.js
define(['app'], function (app) {
app.controller('TopMenuCtrl', ['$scope', function ($scope) {
$scope.message = "It works";
}]);
});
//Home/TopMenu
<h3>TopMenu</h3>
<div ng-controller="TopMenuCtrl">
{{message}}
</div>

I created working plunker here.
Let's have this index.html:
<!DOCTYPE html>
<html>
<head>
<title>my lazy</title>
</head>
<body ng-app="app">
#/home // we have three states - 'home' is NOT lazy
#/ - index // 'index' is lazy, with two views
#/other // 'other' is lazy with unnamed view
<div data-ui-view="topMenu"></div>
<div data-ui-view=""></div>
<script src="angular.js"></script> // standard angular
<script src="angular-ui-router.js"></script> // and ui-router scritps
<script src="script.js"></script> // our application
<script data-main="main.js" // lazy dependencies
src="require.js"></script>
</body>
</html>
Let's observe the main.js - the RequireJS config:
require.config({
//baseUrl: "js/scripts",
baseUrl: "",
// alias libraries paths
paths: {
// here we define path to NAMES
// to make controllers and their lazy-file-names independent
"TopMenuCtrl": "Controller_TopMenu",
"ContentCtrl": "Controller_Content",
"OtherCtrl" : "Controller_Other",
},
deps: ['app']
});
In fact, we only create aliases (paths) for our ControllerNames - and their Controller_Scripts.js files. That's it. Also, we return to require the app, but we will in our case use different feature later - to register lazily loaded controllers.
what does the deps: ['app'] mean? Firstly, we need to provide file app.js (the 'app' means find app.js) :
define([], function() {
var app = angular.module('app');
return app;
})
this returned value is the one we can ask for in every async loaded file
define(['app'], function (app) {
// here we would have access to the module("app")
});
How will we load controllers lazily? As already proven here for ngRoute
angularAMD v0.2.1
angularAMD is an utility that facilitates the use of RequireJS in AngularJS applications supporting on-demand loading of 3rd party modules such as angular-ui.
We will ask angular for a reference to $controllerProvider - and use it later, to register controllers.
This is the first part of our script.js:
// I. the application
var app = angular.module('app', [
"ui.router"
]);
// II. cached $controllerProvider
var app_cached_providers = {};
app.config(['$controllerProvider',
function(controllerProvider) {
app_cached_providers.$controllerProvider = controllerProvider;
}
]);
As we can see, we just created the application 'app' and also, created holder app_cached_providers (following the angularAMD style). In the config phase, we ask angular for $controllerProvider and keep reference for it.
Now let's continue in script.js:
// III. inline dependency expression
app.config(['$stateProvider', '$urlRouterProvider',
function($stateProvider, $urlRouterProvider) {
$urlRouterProvider
.otherwise("/home");
$stateProvider
.state("home", {
url: "/home",
template: "<div>this is home - not lazily loaded</div>"
});
$stateProvider
.state("other", {
url: "/other",
template: "<div>The message from ctrl: {{message}}</div>",
controller: "OtherCtrl",
resolve: {
loadOtherCtrl: ["$q", function($q) {
var deferred = $q.defer();
require(["OtherCtrl"], function() { deferred.resolve(); });
return deferred.promise;
}],
},
});
}
]);
This part above shows two states declaration. One of them - 'home' is standard none lazy one. It's controller is implicit, but standard could be used.
The second is state named "other" which does target unnamed view ui-view="". And here we can firstly see, the lazy load. Inside of the resolve (see:)
Resolve
You can use resolve to provide your controller with content or data that is custom to the state. resolve is an optional map of dependencies which should be injected into the controller.
If any of these dependencies are promises, they will be resolved and converted to a value before the controller is instantiated and the $stateChangeSuccess event is fired.
With that in our suite, we know, that the controller (by its name) will be searched in angular repository once the resolve is finished:
// this controller name will be searched - only once the resolve is finished
controller: "OtherCtrl",
// let's ask RequireJS
resolve: {
loadOtherCtrl: ["$q", function($q) {
// wee need $q to wait
var deferred = $q.defer();
// and make it resolved once require will load the file
require(["OtherCtrl"], function() { deferred.resolve(); });
return deferred.promise;
}],
},
Good, now, as mentioned above, the main contains this alias def
// alias libraries paths
paths: {
...
"OtherCtrl" : "Controller_Other",
And that means, that the file "Controller_Other.js" will be searched and loaded. This is its content which does the magic. The most important here is use of previously cached reference to $controllerProvider
// content of the "Controller_Other.js"
define(['app'], function (app) {
// the Default Controller
// is added into the 'app' module
// lazily, and only once
app_cached_providers
.$controllerProvider
.register('OtherCtrl', function ($scope) {
$scope.message = "OtherCtrl";
});
});
the trick is not to use app.controller() but
$controllerProvider.Register
The $controller service is used by Angular to create new controllers. This provider allows controller registration via the register() method.
Finally there is another state definition, with more narrowed resolve... a try to make it more readable:
// IV ... build the object with helper functions
// then assign to state provider
var loadController = function(controllerName) {
return ["$q", function($q) {
var deferred = $q.defer();
require([controllerName], function() {deferred.resolve(); });
return deferred.promise;
}];
}
app.config(['$stateProvider', '$urlRouterProvider',
function($stateProvider, $urlRouterProvider) {
var index = {
url: "/",
views: {
"topMenu": {
template: "<div>The message from ctrl: {{message}}</div>",
controller: "TopMenuCtrl",
},
"": {
template: "<div>The message from ctrl: {{message}}</div>",
controller: "ContentCtrl",
},
},
resolve : { },
};
index.resolve.loadTopMenuCtrl = loadController("TopMenuCtrl");
index.resolve.loadContentCtrl = loadController("ContentCtrl");
$stateProvider
.state("index", index);
}]);
Above we can see, that we resolve two controllers for both/all named views of that state
That's it. Each controller defined here
paths: {
"TopMenuCtrl": "Controller_TopMenu",
"ContentCtrl": "Controller_Content",
"OtherCtrl" : "Controller_Other",
...
},
will be loaded via resolve and $controllerProvider - via RequireJS - lazily. Check that all here
Similar Q & A: AngularAMD + ui-router + dynamic controller name?

On one project I used lazy loading of controllers and had to manually call a $digest on the scope to have it working. I guess that this behavior does not change with ui-router.
Did you try that ?
define(['app'], function (app) {
app.controller('TopMenuCtrl', ['$scope', function ($scope) {
$scope.message = "It works";
$scope.$digest();
}]);
});

Related

appCtrl is not a function, got undefined error triggered when trying to load appCtrl (ON THE FLY)

I want to load controllers on the fly when needed rather than loading them in one go. So, for the I've implemented dynamic approach which works fine without any error. It also works well with Ui-Router.
But the problem is in Index.html page. I want to put global (super parent) controller name "appCtrl". As this appCtrl should be initialized when I run my app. For that I need to write like ng-controller="appCtrl" or ng-controller="appCtrl as vm" at body tag.
But when I do it, it gives error that appCtrl is a function, got undefined. I tried sever ways but still unable to identify exact error. I have working on this issue since two to three days but still not able to identify it.
I have made this plunker.
look at body tag of index.html.
main.js
require.config({
paths: {
"angular": "//cdnjs.cloudflare.com/ajax/libs/angular.js/1.4.0-rc.1/angular",
"ui-router": "//rawgit.com/angular-ui/ui-router/0.2.15/release/angular-ui-router"
},
shim: {
"angular": {
exports: 'angular'
},
"ui-router": {
deps: ['angular']
}
}
});
define(
['angular',
'app',
'controllers/appCtrl'],
function (angluar, app) {
angular.bootstrap(document, ['MyApp'])
});
app.js
define([
'angular',
'ui-router'
], function (angular) {
var app = angular.module('MyApp', ['ui.router']);
function lazy () {
var self = this;
this.resolve = function (controller) {
return {
ctrl: ['$q', function ($q) {
var defer = $q.defer();
require(['controllers/' + controller], function (ctrl) {
app.register.controller(controller, ctrl);
defer.resolve();
});
return defer.promise;
}]
};
};
this.$get = function (){
return self;
};
}
function config ($stateProvider, $urlRouterProvider,
$controllerProvider, $compileProvider,
$filterProvider, $provide, lazyProvider) {
$stateProvider
.state("home", {
url: "/",
controller: 'homeCtrl',
controllerAs: 'vm',
templateUrl: 'views/homeView.html',
resolve: lazyProvider.resolve('homeCtrl')
});
app.register = {
controller: $controllerProvider.register,
directive: $compileProvider.directive,
filter: $filterProvider.register,
factory: $provide.factory,
service: $provide.service,
constant: $provide.constant
};
}
app.provider('lazy', lazy);
app.config(config);
return app;
});
Index.html
<!DOCTYPE html>
<html>
<head>
<script src="https://cdnjs.cloudflare.com/ajax/libs/require.js/2.1.17/require.js" data-main="main.js"></script>
</head>
<body ng-controller="appCtrl as vm"> // I want this to work correctly but it is not getting loaded dynamically. I don't know why. Help me to resolve it.
<a ui-sref="home">go home</a>
<ui-view></ui-view>
{{vm.appVar}}
</body>
</html>
You are actually missing the controller statement in your controller code.
Use the following code
define(['app'], function (app){ //Updated Line
console.log('app controller loaded');
app.controller('appCtrl',ctrl); //New Line added
ctrl.$inject = ['$http'];
function ctrl ($http) {
this.appVar = 'hi from appCtrl';
};
return ctrl;
});
See the plunker

How to tell angular that a controller has been added? (loaded from a separate file)

I have index.html main file and partial view1.html and I use ng-route. So I want controller view1.js to be loaded only when view1.html is accessed. So I successfully loaded the file using resolve directive. Since javascript loads in background angular starts to parse view1.html and I get:
[ng:areq] Argument 'SimpleController2' is not a function, got undefined
How do I to tell angular that a new controller has been added, and it should parse view1.html only after applying the controller.
Check this out
main.js
var demoApp = angular.module('demoApp', ['ngRoute']);
demoApp.config(function ($routeProvider) {
$routeProvider
.when('/view1', {
controller: 'SimpleController1',
templateUrl: 'View1.html',
resolve: {
lol : function get() {
console.log('file is being loaded');
var fileRef = document.createElement('script');
fileRef.setAttribute("type", "text/javascript");
fileRef.setAttribute("src", "view1.js");
document.getElementsByTagName("head")[0].appendChild(fileRef);
fileRef.onload = function () {
console.log('file loaded');
}
}
}
})
.when('/view2',
{
controller: 'SimpleController',
templateUrl: 'View2.html'
})
.otherwise({redirectTo: '/view1'});
});
console.log('config has been added');
controller.js
console.log("file parsed");
demoApp.filter('myFilter', function ($sce) {
return function (input, isRaw) {
input = input.replace(/a/g, 'b');
return $sce.trustAsHtml(input);
};
});
demoApp.controller("SimpleController1", function ($scope, simpleFactory) {
$scope.names = [
{name: 'Nick', city: 'London'},
{name: 'Sick', city: 'Tokio'},
{name: 'Brick', city: 'cellar'}
];
});
I'm new to angular I tried this, this (how to apply files)
and this (gave up with applying $controllerProvider)
this (didn't succeed either) and this (couldn't make the whole thing work together) I'm not even sure that those described my needs. Please give me a clue what post I should dive deeper.
You can't check the existence of the controller without dry-running it with $controller and catching an exception, which is terrible thing to do.
Even then you will have hard time to register a new controller, because after config phase app.controller can't be used, and $controllerProvider.register is available only in config blocks.
You may look at existing solutions for lazy loading, i.e. ocLazyLoad. Here is how it manages routes.

AngularAMD + ui-router + dynamic controller name?

I'm trying to write a generalized route in my application and resolve the view and controller names on the fly based on the route params.
I have the following code that works:
$stateProvider.state('default', angularAMD.route({
url: '/:module/:action?id',
templateUrl: function (params) {
var module = params.module;
var action = module + params.action.charAt(0).toUpperCase()
+ params.action.substr(1);
return 'app/views/' + module + '/' + action + 'View.html';
},
controller: 'userController',
}));
However, I'm unable to figure out a way to resolve the controller name dynamically. I tried using resolve as described here, but ui-router seems to handle resolve differently than angular-route.
Any pointers?
EDIT: I've already tried using controllerProvider but it doesn't work for me (for instance, the following code just returns a hard coded controller name to test whether it actually works):
controllerProvider: function () {
return 'userController';
}
Gives me the following error:
Error: [ng:areq] Argument 'userController' is not a function, got undefined
http://errors.angularjs.org/1.3.3/ng/areq?p0=userController&p1=not%20aNaNunction%2C%20got%20undefined
This is a link to working plunker.
solution
We need two features of the UI-Router:
resolve (to load the missing pieces of js code)
controllerProvider (see cites from documentation below)
angularAMD - main.js definition
This would be our main.js, which contains smart conversion controllerName - controllerPath:
require.config({
//baseUrl: "js/scripts",
baseUrl: "",
// alias libraries paths
paths: {
"angular": "angular",
"ui-router": "angular-ui-router",
"angularAMD": "angularAMD",
"DefaultCtrl": "Controller_Default",
"OtherCtrl": "Controller_Other",
},
shim: {
"angularAMD": ["angular"],
"ui-router": ["angular"],
},
deps: ['app']
});
controllers:
// Controller_Default.js
define(['app'], function (app) {
app.controller('DefaultCtrl', function ($scope) {
$scope.title = "from default";
});
});
// Controller_Other.js
define(['app'], function (app) {
app.controller('OtherCtrl', function ($scope) {
$scope.title = "from other";
});
});
app.js
Firstly we would need some method converting the param (e.g. id) into controller name. For our test purposes let's use this naive implementation:
var controllerNameByParams = function($stateParams)
{
// naive example of dynamic controller name mining
// from incoming state params
var controller = "OtherCtrl";
if ($stateParams.id === 1) {
controller = "DefaultCtrl";
}
return controller;
}
.state()
And that would be finally our state definition
$stateProvider
.state("default", angularAMD.route({
url: "/{id:int}",
templateProvider: function($stateParams)
{
if ($stateParams.id === 1)
{
return "<div>ONE - Hallo {{title}}</div>";
}
return "<div>TWO - Hallo {{title}}</div>";
},
resolve: {
loadController: ['$q', '$stateParams',
function ($q, $stateParams)
{
// get the controller name === here as a path to Controller_Name.js
// which is set in main.js path {}
var controllerName = controllerNameByParams($stateParams);
var deferred = $q.defer();
require([controllerName], function () { deferred.resolve(); });
return deferred.promise;
}]
},
controllerProvider: function ($stateParams)
{
// get the controller name === here as a dynamic controller Name
var controllerName = controllerNameByParams($stateParams);
return controllerName;
},
}));
Check it here, in this working example
documentation
As documented here: $stateProvider, for a state(name, stateConfig) we can use controller and controllerProvider. Some extract from documentation:
controllerProvider
...
controller (optional) stringfunction
Controller fn that should be associated with newly related scope or the name of a registered controller if passed as a string. Optionally, the ControllerAs may be declared here.
controller: "MyRegisteredController"
controller:
"MyRegisteredController as fooCtrl"}
controller: function($scope, MyService) {
$scope.data = MyService.getData(); }
controllerProvider (optional) function
Injectable provider function that returns the actual controller or string.
controllerProvider:
function(MyResolveData) {
if (MyResolveData.foo)
return "FooCtrl"
else if (MyResolveData.bar)
return "BarCtrl";
else return function($scope) {
$scope.baz = "Qux";
}
}
...
resolve
resolve (optional) object
An optional map<string, function> of dependencies which should be injected into the controller. If any of these dependencies are promises, the router will wait for them ALL to be resolved before the controller is instantiated...
I.e. let's use controllerProvider:
... to resolve the controller name dynamically...
In case, that you managed to get here, maybe you'd like to check another similar solution with RequireJS - angular-ui-router with requirejs, lazy loading of controller

Is there a way to preload templates when using AngularJS routing?

After the Angular app is loaded I need some of the templates to be available offline.
Something like this would be ideal:
$routeProvider
.when('/p1', {
controller: controller1,
templateUrl: 'Template1.html',
preload: true
})
This is an addition to the answer by #gargc.
If you don't want to use the script tag to specify your template, and want to load templates from files, you can do something like this:
myApp.run(function ($templateCache, $http) {
$http.get('Template1.html', { cache: $templateCache });
});
myApp.config(function ($locationProvider, $routeProvider) {
$routeProvider.when('/p1', { templateUrl: 'Template1.html' })
});
There is a template cache service: $templateCache which can be used to preload templates in a javascript module.
For example, taken from the docs:
var myApp = angular.module('myApp', []);
myApp.run(function($templateCache) {
$templateCache.put('templateId.html', 'This is the content of the template');
});
There is even a grunt task to pre-generate a javascript module from html files: grunt-angular-templates
Another way, perhaps less flexible, is using inline templates, for example, having a script tag like this in your index.html:
<script type="text/ng-template" id="templates/Template1.html">template content</script>
means that the template can be addressed later in the same way as a real url in your route configuration (templateUrl: 'templates/Template1.html')
I think I have a slightly improved solution to this problem based on Raman Savitski's approach, but it loads the templates selectively. It actually allows for the original syntax that was asked for like this:
$routeProvider.when('/p1', { controller: controller1, templateUrl: 'Template1.html', preload: true })
This allows you to just decorate your route and not have to worry about updating another preloading configuration somewhere else.
Here is the code that runs on start:
angular.module('MyApp', []).run([
'$route', '$templateCache', '$http', (function ($route, $templateCache, $http) {
var url;
for (var i in $route.routes) {
if ($route.routes[i].preload) {
if (url = $route.routes[i].templateUrl) {
$http.get(url, { cache: $templateCache });
}
}
}
})
]);
Preloads all templates defined in module routes.
angular.module('MyApp', [])
.run(function ($templateCache, $route, $http) {
var url;
for(var i in $route.routes)
{
if (url = $route.routes[i].templateUrl)
{
$http.get(url, {cache: $templateCache});
}
}
})
if you wrap each template in a script tag, eg:
<script id="about.html" type="text/ng-template">
<div>
<h3>About</h3>
This is the About page
Its cool!
</div>
</script>
Concatenate all templates into 1 big file. If using Visual Studio 2013,Download Web essentials - it adds a right click menu to create an HTML Bundle
Add the code that this guy wrote to change the angular $templatecache service - its only a small piece of code and it works :-)
https://gist.github.com/vojtajina/3354046
Your routes templateUrl should look like this:
$routeProvider.when(
"/about", {
controller: "",
templateUrl: "about.html"
}
);

Angular.js configuring ui-router child-states from multiple modules

I'd like to implement a setup where i can define a "root state" in the main module, and then add child states in other modules. This, because i need the root state to resolve before i can go to the child state.
Apparently, this should be possible according to this FAQ:
How to: Configure ui-router from multiple modules
For me it doesn't work:
Error Uncaught Error: No such state 'app' from ngBoilerplate.foo
Here is what i have:
app.js
angular.module( 'ngBoilerplate', [
'templates-app',
'templates-common',
'ui.state',
'ui.route',
'ui.bootstrap',
'ngBoilerplate.library'
])
.config( function myAppConfig ( $stateProvider, $urlRouterProvider ) {
$stateProvider
.state('app', {
views:{
"main":{
controller:"AppCtrl"
}
},
resolve:{
Auth:function(Auth){
return new Auth();
}
}
});
$urlRouterProvider.when('/foo','/foo/tile');
$urlRouterProvider.otherwise( '/foo' );
})
.factory('Auth', ['$timeout','$q', function ($timeout,$q) {
return function () {
var deferred = $q.defer();
console.log('before resolve');
$timeout(function () {
console.log('at resolve');
deferred.resolve();
}, 2000);
return deferred.promise;
};
}])
.run(function run( $rootScope, $state, $stateParams ) {
console.log('greetings from run');
$state.transitionTo('app');
})
.controller( 'AppCtrl', function AppCtrl ( $scope, Auth ) {
console.log('greetings from AppCtrl');
});
foo.js
angular.module( 'ngBoilerplate.foo', ['ui.state'])
.config(function config( $stateProvider ) {
$stateProvider
.state( 'app.foo', {
url: '/foo/:type',
views: {
"main": {
controller:'FooCtrl',
templateUrl: function(stateParams) { /* stuff is going on in here*/ }
}
}
});
})
.controller( 'FooCtrl', function FooCtrl( $scope ) {
console.log('deferred foo');
});
How do i make this work or what other approaches could i take to have something global resolved before every state (without defining a resolve on each state)?
I finally chose this approach which does the job for me:
// add all your dependencies here and configure a root state e.g. "app"
angular.module( 'ngBoilerplate', ['ui.router','templates-app',
'templates-common','etc','etc']);
// configure your child states in here, such as app.foo, app.bar etc.
angular.module( 'ngBoilerplate.foo', ['ngBoilerplate']);
angular.module( 'ngBoilerplate.bar', ['ngBoilerplate']);
// tie everything together so you have a static module name
// that can be used with ng-app. this module doesn't do anything more than that.
angular.module( 'app', ['ngBoilerplate.foo','ngBoilerplate.bar']);
and then in your app index.html
<html ng-app="app">
In the documentation the feature1 module depends on the application module. Try
angular.module( 'ngBoilerplate.foo', ['ngBoilerplate'])
I would of just commented but i do not have the rep. I know this is old but i had the same problem and came across this. One thing i am confused about is in app.js you do not import "ngBoilerplate.foo" but ngBoilerplate.library instead. I had the same problem and my solution was to inject sub modules into the top module instead of their parent.
My structure was module('ngBoilerplate'), module('ngBoilerplate.foo') and module('ngBoilerplate.foo.bar')'. I was injecting ngBoilerplate.foo.bar into ngBoilerplate.foo and the $stateProvider was failing. I needed to inject ngBoilerplate.foo.bar into top level ngBoilerplate.
I thought i would put this here in case anyone else sees this. The error i had was Uncaught TypeError: Cannot read property 'navigable' of undefined from ngBoilerplate.foo

Resources