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
Related
how to write different modules with their own routing?
i have an angular app and it has different modules.i am going to write for each of them, specific route file, but i got this error
Uncaught Error: [$injector:unpr] http://errors.angularjs.org/1.6.4/$injector/unpr?p0=routeServiceProvider%20%3C-%20routeService
it is my code :
sample.module.js
angular.module('app.sample', []);
sample.route.js
angular
.module('app.sample')
.run(appRun);
/* #ngInject */
function appRun (routeService) {
routeService.configureRoutes(getRoutes());
}
function getRoutes () {
return [ {
url: '/sample',
config: {
templateUrl: 'sample.html'
}
}
];
}
i already add ngRoute and inject these files in index.html file
To achieve such project structure, ui-router is the best way to go. It is a separate library so you have to include into your project as a dependency.
Here are the snippets that will be useful for your case
dashboard.module.js
angular.module('app.dashboard', ['ui.router']);
dashboard.router.js
angular.module('app.dashboard')
.config(routerConfig);
routerConfig.$inject = ['$stateProvider'];
function routerConfig($stateProvider) {
$stateProvider
.state('state1', {
url: '/state1',
templateUrl: 'url/to/state1.html',
controller: function () {
// controller code here
}
})
.state('state2', {
url: '/state2',
templateUrl: 'url/to/state2.html',
controller: function () {
// controller code here
}
});
}
sample.module.js
angular.module('app.sample', ['ui.router']);
sample.router.js
angular.module('app.sample')
.config(routerConfig);
routerConfig.$inject = ['$stateProvider'];
function routerConfig($stateProvider) {
$stateProvider
.state('state3', {
url: '/state3',
templateUrl: 'url/to/state3.html',
controller: function () {
// controller code here
}
})
.state('state4', {
url: '/state4',
templateUrl: 'url/to/state4.html',
controller: function () {
// controller code here
}
});
}
Lastly, app.module that connects all these modules
app.module.js
angular.module('app', [
/*
* sub-modules
*/
'app.dashboard',
'app.sample'
]);
To sum up, you have two independent sub-modules (app.dashboard and app.sample) with their own routing logic and one module (app) that wraps them into one angular application.
$stateProvider, service provided by ui.router, is used for registering states.
Additional info
Since your application is modular, you are probably going to need nested routing which is greatly supported by ui.router. Read docs to get more information on nested states.
Update
However, if you still want to stick with ngRoute, this and this clearly explain how to achieve the same result.
I use Typescript 1.4 with angularjs 1.3.6.
Using VS 2015 RC with webessentials, with no module system (no --module flag)
I have a working code like this:
demoModule.ts
module Demo.Test {
'use strict';
(() => {
var app = angular.module('Demo.Test', []);
// Routes.
app.config([
'$stateProvider', $stateProvider => {
$stateProvider
.state('demo', {
url: '/demo',
templateUrl: '/views/test/demo.html',
controller: 'demoController as vm'
});
}
]);
})();
demoController.ts
module Demo.Test {
'use strict';
export class DemoController {
constructor(/* ... */) { /* ... */}
}
angular.module('Demo.Test').controller('demoController', Demo.Test.DemoController);
}
But when I move this line:
angular.module('Demo.Test').controller('demoController', Demo.Test.DemoController);
to the demoModule.ts file(see below) it will compile, but getting JS error when run:
Error: [ng:areq] Argument 'demoController' is not a function, got undefined
Any idea how can I make it work? I mean like this:
module Demo.Test {
'use strict';
(() => {
var app = angular.module('Demo.Test', []);
angular.module('Demo.Test').controller('demoController', Demo.Test.DemoController);
// Routes.
app.config([
'$stateProvider', $stateProvider => {
$stateProvider
.state('demo', {
url: '/demo',
templateUrl: '/views/test/demo.html',
controller: 'demoController as vm'
});
}
]);
})();
If you used the script reference not in the right order, then you are going to get the runtime error.
as: Error: [ng:areq] Argument 'demoController' is not a function, got undefined
Add demoController.ts before demoModule.ts in your html file.
<script src="demoController.js"></script>
<script src="demoModule.js"></script>
Its got to do with ordering of files. One of the well known errors caused by using --out in TypeScript : https://github.com/TypeStrong/atom-typescript/blob/master/docs/out.md#runtime-errors
I have a Utils Service which is very heavy. I Want to use some of the functions defined in it on a particular user action. As this service is heavy I want to instantiate it lazily(on user action).
How do I achieve this?
Service
module.service('Utils', function (dep1, dep2) {
this.method1 = function () {
// do something
}
// other methods
});
Controller
module.controller('AppCtrl', function ($scope) {
// I don't want to inject Utils as a dependency.
$scope.processUserAction = function () {
// If the service is not instantiated
// instantiate it and trigger the methods defined in it.
}
});
Markup
<div data-ng-controller="AppCtrl">
<button data-ng-click="processUserAction()"> Click Me </button>
</div>
You can use $injector service to get services anywhere: https://docs.angularjs.org/api/auto/service/$injector. Inject the $injector into your controller, and whenever you need a service use:
This worked fine for me, the service is instantiated only on the $injector call, no error thrown.
angular.module('yp.admin')
.config(['$stateProvider', '$urlRouterProvider', 'accessLevels', '$translateWtiPartialLoaderProvider',
function ($stateProvider, $urlRouterProvider, accessLevels, $translateWtiPartialLoaderProvider) {
$stateProvider
.state('admin.home', {
url: "/home",
access: accessLevels.admin,
views: {
content: {
templateUrl: 'admin/home/home.html',
controller: 'AdminHomeController'
}
}
});
}])
.service('UtilsService', function() {
console.log('utilsSerivce instantiated');
return {
call: function() {
console.log('Util.call called');
}
};
})
.controller('AdminHomeController', ['$scope', '$rootScope', 'UserService', '$injector',
function($scope, $rootScope, UserService, $injector) {
$injector.get('UtilsService').call();
}]);
console gives me this:
stateChangeStart from: to: admin.home
stateChangeSuccess from: to: admin.home
utilsSerivce instantiated
Util.call called
If you want to delay loading the JS you should have a look at the ocLazyLoad Module: https://github.com/ocombe/ocLazyLoad. It addresses all sorts of lazy loading use cases and yours sounds like a good fit for it.
I'm trying to get to work angular.js, ui-router, and require.js and feel quite confused. I tried to follow this tutorial http://ify.io/lazy-loading-in-angularjs/. First, let me show you my code:
app.js =>
var app = angular.module('myApp', []);
app.config(function ($stateProvider, $controllerProvider, $compileProvider, $filterProvider, $provide) {
$stateProvider.state('home',
{
templateUrl: 'tmpl/home-template.html',
url: '/',
controller: 'registration'
resolve: {
deps: function ($q, $rootScope) {
var deferred = $q.defer(),
dependencies = ["registration"];
require(dependencies, function () {
$rootScope.$apply(function () {
deferred.resolve();
});
})
return deferred.$promise;
}
}
}
);
app.lazy = {
controller: $controllerProvider.register,
directive: $compileProvider.directive,
filter: $filterProvider.register,
factory: $provide.factory,
service: $provide.service
};
});
Now in my registration.js I have following code:
define(["app"], function (app) {
app.lazy.controller("registration" , ["$scope", function ($scope) {
// The code here never runs
$scope.message = "hello world!";
}]);
});
everything works well, even the code in registration.js is run. but the problem is code inside controller function is never run and I get the error
Error: [ng:areq] http://errors.angularjs.org/1.2.23/ng/areq?p0=registration&p1=not a function, got undefined
Which seems my code does not register controller function successfully. Any Ideas?
P.s. In ui-router docs it is said "If any of these dependencies are promises, they will be resolved and converted to a value before the controller is instantiated and the $routeChangeSuccess event is fired." But if I put the deferred.resolve(); from mentioned code inside a timeOut and run it after say 5 seconds, my controller code is run and my view is rendered before resolve, Strange.
Seems like I ran into the exact same problem, following the exact same tutorial that you did, but using ui-router. The solution for me was to:
Make sure the app.controllerProvider was available to lazy controller script. It looked like you did this using app.lazy {...}, which a really nice touch BTW :)
Make sure the lazy ctrl script uses define() and not require() I couldn't tell from your code if you had done this.
Here is my ui-router setup with the public app.controllerProvider method:
app.config(function ($stateProvider, $controllerProvider, $filterProvider, $provide, $urlRouterProvider) {
app.lazy = {
controller: $controllerProvider.register,
directive: $compileProvider.directive,
filter: $filterProvider.register,
factory: $provide.factory,
service: $provide.service
};
$urlRouterProvider.otherwise('/');
$stateProvider
.state('app', {
url:'/',
})
.state('app.view-a', {
views: {
'page#': {
templateUrl: 'view-a.tmpl.html',
controller: 'ViewACtrl',
resolve: {
deps: function ($q, $rootScope) {
var deferred = $q.defer();
var dependencies = [
'view-a.ctrl',
];
require(dependencies, function() {
$rootScope.$apply(function() {
deferred.resolve();
});
});
return deferred.promise;
}
}
}
}
});
});
Then in my lazy loaded controller I noticed that I had to use require(['app']), like this:
define(['app'], function (app) {
return app.lazy.controller('ViewACtrl', function($scope){
$scope.somethingcool = 'Cool!';
});
});
Source on GitHub: https://github.com/F1LT3R/angular-lazy-load
Demo on Plunker: http://plnkr.co/edit/XU7MIXGAnU3kd6CITWE7
Changing you're state's url to '' should do the trick. '' is root example.com/, '/' is example.com/#/.
I came to give my 2 cents. I saw you already resolved it, I just want to add a comment if someone else have a similar problem.
I was having a very similar issue, but I had part of my code waiting for the DOM to load, so I just called it directly (not using the "$(document).ready") and it worked.
$(document).ready(function() { /*function was being called here*/ });
And that solved my issue. Probably a different situation tho but I was having the same error.
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();
}]);
});