I have two modules, where two routes:
angular
.module('lang', ['ngRoute'])
.config('lang', ['$routeProvider', config])
.controller('lang', lang);
function config(route){
route.when('/:lang/:page', {
template : '',
controller : lang
})
}
and route for guide module:
angular
.module('guide', ['ngRoute'])
.config('guide', ['$routeProvider', config])
.controller('guide', guide);
function config(route){
route.when('/:lang/guide', {
template : '/view/guide.html',
controller : guide
})
}
But the second controller not run. How can I run two controllers using two routes?
ng-route using for SPA applications.
If you want to navigate to different pages in your application, but you also want the application to be a SPA (Single Page Application), with no page reloading, you can use the ngRoute module.
Therefore you need to define main module, config routes there and inject dependencies. Example:
var app = angular.module('app',['ngRoute', 'firstModule', 'secondModule']);
var configFunction = function($routeProvider){
$routeProvider
.when('/:lang/:page', {
templateUrl: '/view/guide.html',
controller : 'FirstCtrl'
})
.when('/:lang/guide', {
templateUrl: '/view/guide2.html',
controller: 'SecondCtrl'
})
configFunction.$inject = ['$routeProvider'];
app.config(configFunction);
app.config(['$locationProvider',
function ($locationProvider) {
$locationProvider.hashPrefix('');
}]);
And this is your injected controllers :
var app = angular.module('firstModule', []);
app.controller('FirstCtrl',function(){});
var app = angular.module('secondModule', []);
app.controller('SecondCtrl',function(){});
Be aware regarding syntax. Check syntax for Angular version you use.
Related
I have a webapp that I would like to have some consistent themes across pages. To do so, I have attempted to modify the routeProvider provider to allow for utilization of such a template. As far as I can tell, the ways to do this are to define the provider, configure it, include it in the controller scope, and then inject it into the controller. I believe I have done this. Here are the relevant code blocks:
var webApp = angular.module('myApp.module', ['ngRoute','ngCookies','angular-jwt']);
webApp.provider('extendedRouteProvider', function($routeProvider) {
this.$get = function() {
return {
when: function(path,route) {
if (route.layOutTemplateUrl) {
route.resolve = route.resolve || {};
route.resolve.layOutTemplateUrl = function (){
return route.layOutTemplateUrl;
};
}
$routeProvider.when(path,route);
}
}
}
});
webApp.config(function(extendedRouteProvider) {
extendedRouteProvider
.when('/', {
templateUrl: 'webapp_loginScreen_UIDesign.html',
controller: 'loginScreenController'
})
//Could add the following to after the .html bellow in the file if we want screen to load at anchor point specified in the HTML file: #!/mainPage...
//This would also require adding it into the $location.path within the screenController function if so
.when('/mainPage', {
templateUrl: '/UI Design/Main Page/HTML/webapp_mainPageScreen_UIDesign.html',
controller: 'mainPageScreenController',
layOutTemplateUrl: '/UI Design/webapp_mainLayoutTemplate.html'
})
.otherwise({
redirectTo: '/'
});
});
function loginScreenController($http, $cookies, $location, $route,extendedRouteProvider) {
var vm = this;
var layOutTemplateUrl = $route.current.layOutTemplateUrl;
// do stuff
const serverURL = "URL";
$location.path('/mainPage');
}
webApp.controller('loginScreenController',loginScreenController);
loginScreenController.$inject = ['$http','$cookies','$location','$route','extendedRouteProvider'];
However, this code, when running via VSCode's live server, gives me an $injector:unpr error. I don't understand why this is happening. Note that I 'enter' the webapp through an HTML page which does not itself utilize the layout template, but $location.path('/main') should be sending the user to the mainpage, which does utilize the layout template.
I have the following Angular Module, Routes and Controllers inside my index.js file. Nothing complex. So far I load this one javascript file into my Index.html file and everything work fine so far as I have the ng-app & ng-view in the Index.html file. Simple enough
// /ng-modules/render-index.js
angular
.module("homeIndex", ["ngRoute"])
.config(config)
.controller("homeController", homeController)
.controller("aboutController", aboutController);
function config($routeProvider) {
$routeProvider
.when("/", {
templateUrl: "/ng-templates/homeView.html",
controller: "homeController",
controllerAs: "vm"
})
.when("/about", {
templateUrl: "/ng-templates/aboutView.html",
controller: "aboutController",
controllerAs: "vm"
})
.otherwise({ redirectTo: "/" });
};
function homeController() {
var vm = this;
vm.title = "Home Page";
};
function aboutController() {
var vm = this;
vm.title = "About Us";
};
Now I understand that to break this apart at this point in time would be silly because if this was all I was using angular for, why not just keep it all in one javascript file. Understood, But I want to know how to separate these things properly at this level so that I have a basic understanding.
Here is what I want to do. I want to separate the two controllers (homeController & aboutController) to their own files. I also want to know what to do with the routes. DO they get moved into their own javascript file, do they stay in the index.js file? I want to assume that these two controllers will eventually do something complex and therefore I am separating them now.
QUESTION:
Using the (Controller as syntax) How exactly do I do this and what does the index.js file look like and the two home.js and about.js files look like when they have been separated?
What I have tried:
I have tried to put each controller into their own file and inject them into the index.js file
angular
.module("homeIndex", ["ngRoute", "homeController", "aboutController])
I had left the routing inside that file. FOr some reason I was either using the wrong syntax or doing it wrong.
What you tried don't work because you are trying to load controllers as module dependency.
You can split the files like this and add all of them in your index.html
// index.js
angular
.module("homeIndex", ["ngRoute"]);
//route.js
angular
.module("homeIndex")
.config(config);
function config($routeProvider) {
$routeProvider
.when("/", {
templateUrl: "/ng-templates/homeView.html",
controller: "homeController",
controllerAs: "vm"
})
.when("/about", {
templateUrl: "/ng-templates/aboutView.html",
controller: "aboutController",
controllerAs: "vm"
})
.otherwise({ redirectTo: "/" });
};
// homeController.js
angular
.module("homeIndex")
.controller("homeController", homeController)
function homeController() {
var vm = this;
vm.title = "Home Page";
};
// aboutController.js
angular
.module("homeIndex")
.controller("aboutController", aboutController);
function aboutController() {
var vm = this;
vm.title = "About Us";
};
I am trying to lazy load my controllers for my AngularJS app I built along side with requireJS. I have created a custom "lazyLoad" library that creates a resolve object in app.config() routes (also I am using ui-router). If I code the state (without my library) to look like so it works
define(['angular', 'lazyLoader', 'uiRouter'], function(angular, lazyLoader, uiRouter){
var app = angular.module('myApp', ['ui.router']);
app.config(function ($stateProvider, $urlRouterProvider, $controllerProvider, $compileProvider, $filterProvider, $provide) {
window.lazy = {
controller: $controllerProvider.register,
directive: $compileProvider.directive,
filter: $filterProvider.register,
factory: $provide.factory,
service: $provide.service
};
$urlRouterProvider.otherwise('/');
$stateProvider
.state('campaigns', {
url:'/campaigns',
views: {
"top-nav" : {
templateUrl: 'views/home/top-nav.html',
resolve : {
load : ['$q', '$rootScope', function($q, $rootScope){
var d = $q.defer();
require(['../app/controllers/header-controller'], function() {
$rootScope.$apply(function(){
d.resolve();
});
});
return d.promise;
}]
}
},
"fullpage": {
templateUrl: 'views/home/index.html',
resolve : {
load : ['$q', '$rootScope', function($q, $rootScope){
var d = $q.defer();
require(['../app/controllers/home-controller'], function() {
$rootScope.$apply(function(){
d.resolve();
});
});
return d.promise;
}]
}
//controller: 'home-controller'
}
}
});
});
return app;
});
If I attempt to replace the resolve object with my library function it looks would look like this:
define(['angular', 'lazyLoader', 'uiRouter'], function(angular, lazyLoader, uiRouter){
and
.state('home', lazyLoader.route({
url:'/',
views: {
"top-nav" : {
templateUrl: 'views/home/top-nav.html',
controllerUrl: '../app/controllers/header-controller'
},
"fullpage": {
templateUrl: 'views/home/index.html',
controllerUrl: '../app/controllers/home-controller'
}
}
}));
lazyLoader.js
define(function () {
'use strict';
function LazyLoader() {}
LazyLoader.prototype.route = function(config){
var controllerPath;
if(config && config.views){
var singleView = Object.keys(config.views);
for(var i in singleView){
var viewName = singleView[i];
controllerPath = config.views[viewName].controllerUrl;
delete config.views.controllerUrl;
config.views[viewName].resolve = {
load : ['$q', '$rootScope', function($q, $rootScope){
var d = $q.defer();
require([controllerPath], function() {
$rootScope.$apply(function(){
d.resolve();
});
});
return d.promise;
}]
};
}
}
return config;
}
return new LazyLoader();
});
Example Controller
define(['app/module'], function (module) {
lazy.controller('header-controller', ['$scope', function ($scope) {
// stuff here
}]);
});
On a side note I plan on implementing something better than attaching lazy variable to window.
When I code the router like the first example it works. When I use my lazyLoader the one of the two views loads it's controller, the second view's controller's file is started to load (console.logs at the beginning show this) but it cannot resolve "module" in the example above.
link to error: AngularJS Error
Again this issue only happens when using my lazyloader which is producing the same resolve object that I have hard coded in for the version that works.
I have searched high and low and there are a lot of resources out there but I could not find anything that addressed this issue.
Any advice is appreciated!
You are taking too much pain to do lazy loading of controllers & services. There is simple approach to lazy load files with ocLazyLoad. This article might help you resolve the same issue.
https://routerabbit.com/blog/convert-angularjs-yeoman-spa-lazyload/
What you should do is
Add a reference of ocLayzLoad & updated JS files’ reference to load on demand from app.js or .html file of their views.
`bower install oclazyload --save-dev`
Now load the module ‘oc.lazyLoad’ in application. Update app.js file
angular
.module('helloWorldApp', [
'ngCookies',
'ngResource',
'ngRoute',
'ngSanitize',
'oc.lazyLoad',
])
Load JS file by adding reference of JS in .html file
<div oc-lazy-load="['scripts/controllers/about.js', 'scripts/services/helloservice.js']">
<div ng-controller="AboutCtrl as about">
Your html goes here
</div>
</div>
If you using Grunt, update Gruntfile to uglyfy, renamed file name & update references in the final .html or .js file.
On the 'myApp' module definition, shouldn't you be returning app variable instead of myApp?
And to avoid exposing lazy to window, you could define it as a property of app variable, this way when you define new functions, you require app first and you can use it:
app.js:
app.lazy = {
controller: $controllerProvider.register,
directive: $compileProvider.register,
filter: $filterProvider.register,
factory: $provide.factory,
service: $provide.service
};
...
return app;
controller.js:
define(['app'], function (app) {
app.lazy.controller('header-controller', ['$scope', function ($scope) {
// stuff here
}]);
});
I have defined drawerApp on my js . On click of button i am loading partial and there require js file. I need to inject some loaded js into my current drawerApp is there any way to inject in app?
Currentlt config. is as below.
JavaScript:
drawerApp.config([ '$interpolateProvider','$controllerProvider','$compileProvider', '$filterProvider', '$provide',
function ($interpolateProvider,$controllerProvider,$compileProvider, $filterProvider, $provide) {
$interpolateProvider.startSymbol('{[{');
$interpolateProvider.endSymbol('}]}');
drawerApp.register =
{
controller: $controllerProvider.register,
directive: $compileProvider.directive,
filter: $filterProvider.register,
factory: $provide.factory,
service: $provide.service
};
}]);
I have a code based on Angular js framework from google.
The code define some routing and associate views to the url path.
the code is like this
var profileModule = angular.module('profileModule', ['ngResource']);
profileModule.config(function ($routeProvider) {
$routeProvider
.when('/', {
controller: 'profileController',
templateUrl: 'Partials/profileList.html'
})
.otherwise({ redirectTo: '/' });
$routeProvider.when('/profile/:profileId', {
templateUrl: 'Partials/profileDetail.html',
controller: 'profileDetailController'
});
});
profileModule.controller('profileController', function($scope, profileFactory) {
$scope.profiles = [];
function init() {
$scope.profiles = profileFactory.query();
}
init();
});
profileModule.factory('profileFactory', function ($resource) {
return $resource("api/profiles/:Id", { Id: "#Id" }, { "update": { method: "PUT" } });
});
The code was using version 1.1.5 of Angular, and it was working fine.
But then I tried to use the newer version 1.2.3
and the code is not working on this version.
it is giving this error
[$injector:unpr] Unknown provider: $routeProvider
I looked on example on how to use routeProvider in 1.2.3
and I found this example from the web site
profileModule.config(['$routeProvider', function ($routeProvider) {
$routeProvider
.....
I tried this , but still the same error
I am using Angular from the CDN network , and specifically from here
http://code.angularjs.org/1.2.3/angular-route.js
You need to depend on the ngRoute module as well:
var profileModule = angular.module('profileModule', ['ngResource', 'ngRoute']);
Since Angular v 1.2, they've separated the routing into a separate file, so you have to include it in your code and then inject it into your module.
You can find the latest version here (angular-route.js):
http://code.angularjs.org/1.2.3/