Please consider the this code where the routeProvider is needed to inject page(n).html in ng-view.
In addition to the console error:
unknown provider: $routeProviderProvider <- $routeProvider
The argument to function routeIt is the name of the page to navigate to, How can I mix a conditional switch with routeProvider.when in order to call the page matching the argument in the most efficient manner? Thanks
(function () {
'use strict';
angular
.module('appModule')
.controller('MainMenuCtrl', ['$scope', '$http', 'TogglerFactory', '$routeProvider', MainMenuCtrl]);
function MainMenuCtrl($scope, $http, Toggler, routeProvider) {
$http.get('models/mainMenu.json').then(
function (response) {
$scope.menuItems = response.data;
},
function (error) {
alert("http error");
}
)
function routeIt (page) {
routeProvider
.when('/page1', {
url: "/page1",
templateUrl: 'views/page1.html',
controller: 'Page1Ctrl'
})
.when('/page2', {
url: "/page2",
templateUrl: 'views/page2.html',
controller: 'Page2Ctrl'
})
}
$scope.itemClicked = function (item){
Toggler.menuToggle();
routeIt(item);
}
}
})();
Service providers aren't available for injection in run phase (i.e. anywhere but provider services and config blocks). It is possible to make route provider injectable and configure it after config phase,
app.config(function ($provide, $routeProvider) {
$provide.value('$routeProvider', $routeProvider);
});
And controllers aren't the best places to implement any logic (e.g. route hot-plug).
Ok you're using your routeProvider wrong you need to configure your routes inside .config blocks
angular.module('myApp', [])
.config(function($routeProvider, $locationProvider) {
$routeProvider
.when('/page1', {
url: "/page1",
templateUrl: 'views/page1.html',
controller: 'Page1Ctrl'
}
})
If you want to change the url from your controller use $location.path('/page1'); inside your controller.
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 am using angularJs for my webApp, but i used $stateProvider everywhere to define state.so now I want to use $routeProvider instead of $stateProvider.and how I change the route? is $location is good to change the path ?
This is my trial code with $routeProvider
angular.module("angular.states", [])
.config(['$routeProvider', '$locationProvider', '$stateProvider'], function ($stateProvider, templateRoot, $routeProvider) {
$routeProvider.when('/login?username&message&error', {
'templateUrl': '/templates/login.html',
'controller': 'LoginController'
});
$routeProvider.when('/logout', {
'templateUrl': '/templates/logout.html',
'controller': 'LogoutController'
});
})
.controller('LoginController', function (UserService, $scope, $state, $stateParams, AuthFactory, $timeout, $location) {
$scope.login = function (username, password) {
UserService.login({
'username': username,
'password': password
});
};
})
.controller('LogoutController', function (UserService, $scope, $location) {
$scope.logout = function () {
UserService.logout({}, function () {
$location.path("/login", {
});
});
};
});
I am not sure about $routeProvider, so please tell me how to use it
You should use $stateProvider instead of $routeProvider. because you can easily change your state using $stateProvider.
& if you use $routeProvider you need to use location, path, its url & all,
You cannot relate to routes with each other like who is parent and who is child.
so $stateProvider is always better to use.
Using $stateProvider :
$stateProvider.state('login', {
'url': '/login
'templateUrl': '/templates/login.html',
'controller': 'LoginController'
});
here you can simply change your state with given url you dont need to locate the path.
I am currently defining my global module in my routes.js, but for some reason the other controllers are not being created and I keep getting errors that say that my main app module 'LiveAPP' is not available. Here is my code:
routes.js
angular.module('LiveAPP', ['ngRoute'])
.config(function($routeProvider, $httpProvider) {
$routeProvider
.when('/', {
templateUrl : '/home.html',
controller : 'mainCtrl'
})
.when('/signup',{
templateUrl : '/signup.html',
controller : 'signUpCtrl'
})
.when('/artist',{
templateUrl : '/artistpage.html',
controller : 'artistCtrl'
})
})
mainCtrl.js
angular.module('LiveAPP')
.controller('mainCtrl', ['$scope','$http', '$location',mainCtrl]);
function mainCtrl($scope,$http,$location){
$scope.somefunc = function(artistname){
dataFactory.ArtistfromSpotify()
.success(function(data, status, headers, config){
console.log(data)
})
}
};
signUpCtrl
angular.module('LiveAPP')
.controller('signUpCtrl', ['$scope','$http',signUpCtrl]);
function signUpCtrl($scope,$http){
$scope.user = {
email:'',
password:''
}
$scope.postreq = function(user){
$http({
method: "post",
url: "/signup",
data:{
user_username:user.email,
user_password:user.password
}
}).success(function(data){
console.log("User posted to the database")
});
};
}
artistCtrl
angular.module('LiveAPP')
.controller('artistCtrl', ['$scope',function($scope){
$scope.myRating =
{number:3}
}])
.directive("rateYo", function() {
return {
restrict: "A",
scope: {
rating: "="
},
template: "<div id='rateYo'></div>",
link: function( scope, ele, attrs ) {
console.log(scope.rating.number)
$(ele).rateYo({
rating: scope.rating.number
});
}
};
});
I was under the impression that I could retrieve the main liveAPP module and add controllers in other files by using angular.model('liveAPP').controller(...) For some reason it's not working. Anyone have any idea?
To elaborate on my comment above, when you re-use the same module across files, you need to load the files in the right order to satisfy dependencies as well as ensure the module is created before being used.
An easy way to avoid this problem is to specify one module per file. For example
mainCtrl.js
(function() {
angular.module('LiveAPP.main', [])
.controller('mainCtrl', ...);
})();
and in your routes.js
(function() {
angular.module('LiveAPP', [
'ngRoute',
'LiveAPP.main'
])
.config(function($routeProvider, $httpProvider) {
$routeProvider.when('/', {
templateUrl: '/home.html',
controller: 'mainCtrl'
})...
});
})();
It's likely that your html file is including the js files in the wrong order. You need to make sure that routes.js appears first in the html.
You need to change signUpCtrl.js to
angular.module('LiveAPP.controller', [])
.controller('signUpCtrl', ['$scope','$http',signUpCtrl]);
and inject LiveAPP.controller to your global module
angular.module('LiveAPP', ['ngRoute', 'LiveAPP.controller'])
You cannot have LiveAPP in more than one module. Make the same updates on all of your controllers and inject that module names in routes.js
Every example I've looked at has made use of the ng-controller directive to get things working.
The Todo MVC example at https://github.com/tastejs/todomvc/tree/gh-pages/examples/angularjs creates a 'TodoCtrl' controller. But in the corresponding index.html, there is no use of the ng-controller directive.
How is this possible? and why did they choose to do it this way?
It uses the ngRoute provider.
angular.module('todomvc', ['ngRoute'])
.config(function ($routeProvider) {
'use strict';
var routeConfig = {
controller: 'TodoCtrl',//add controller to view
templateUrl: 'todomvc-index.html',
resolve: {
store: function (todoStorage) {
// Get the correct module (API or localStorage).
return todoStorage.then(function (module) {
module.get(); // Fetch the todo records in the background.
return module;
});
}
}
};
$routeProvider
.when('/', routeConfig)
.when('/:status', routeConfig)
.otherwise({
redirectTo: '/'
});
});
I need certain routes to require authentication, I am using this module:
https://github.com/enginous/angular-oauth
Which has $scope.authenticate but I am trying to figure out how to access $scope/that function from the $routeProvider. I saw an example call a factory function but that isn't exactly what I am trying to do.
'use strict';
angular.module('app', [
'ngRoute',
'angularOauth',
'googleOauth',
'app.global',
'app.home',
'app.view'
]).
config(['$routeProvider', function($routeProvider) {
$routeProvider.when('/', {
templateUrl: 'views/home/index.html',
controller: 'home'
});
$routeProvider.when('/view', {
templateUrl: 'views/view/index.html',
controller: 'view',
resolve: {
factory: checkAuth
}
}).otherwise({redirectTo: '/'});
$routeProvider.otherwise({redirectTo: '/'});
}]);
var checkAuth = function() {
};
The annotation for a resolve is the same dependency injection annotation used anywhere else in Angular. Your logic for authentication should live in a service for testability and reusability, so injecting and calling a method on your service is precisely what you should be doing:
resolve: {
auth: ['AuthenticationService', function (AuthenticationService) {
// Authentication service injected, call your method
return AuthenticationService.isAuthenticated();
}]
}
or
var checkAuth = ['AuthenticationService', function (AuthenticationService) {
// Authentication service injected, call your method
return AuthenticationService.isAuthenticated();
}];
angular.module('app', [
// ...
]).
config(['$routeProvider', function($routeProvider) {
// ...
$routeProvider.when('/view', {
templateUrl: 'views/view/index.html',
controller: 'view',
resolve: {
auth: checkAuth
}
})
// ...
}]);