AngularJS: route provider does not work when root

I have an AngularJS application that uses $routeProvider and $stateProvider . I can make all my routes / states work separately from / .

Here is my app.js file

 var MailStash = angular.module("MailStash", ['ui.compat', 'ngResource', 'ngSanitize', 'ui.directives']). config(function($stateProvider, $routeProvider, $urlRouterProvider) { $routeProvider .when('/', { controller: ListCtrl, templateUrl: '/js/partials/list.html' }); $stateProvider .state('templates', { url: '/templates', abstract: true, templateUrl: '/js/partials/list.html', controller: ListCtrl, }) .state('templates.list', { // parent: 'templates', url: '', views: { 'main_content': { templateUrl: '/js/partials/templates.new.html', controller:CreateCtrl, }, } }) .state('templates.view', { parent: 'templates', url: '/{templateId}', views: { 'main_content': { templateUrl: '/js/partials/templates.view.html', controller: ViewCtrl, }, }, }) .state('templates.new', { url: '/new', views: { 'main_content': { templateUrl: '/js/partials/templates.new.html', controller: CreateCtrl, }, }, }) .state('templates.edit', { parent: 'templates', url: '/edit/{templateId}', views: { 'main_content': { templateUrl: '/js/partials/templates.edit.html', controller: EditCtrl, }, }, }) } ) .run( [ '$rootScope', '$state', '$stateParams', function ($rootScope, $state, $stateParams) { $rootScope.$state = $state; $rootScope.$stateParams = $stateParams; }] ); ... 

Nothing happens when I go to / , but when I go to /#templates , the corresponding views and controllers appear.

Can anyone see what is wrong with my $routeProvider and why switching to / does nothing?

+6
source share
3 answers

You can specify a default route like this

 $routeProvider .when('/templates', { controller: ListCtrl, templateUrl: '/js/partials/list.html' }) .otherwise({ redirectTo: '/templates' }); 

Hope this helps!

+1
source

Why not just use $urlRouterProvider and the route to / ?

 $urlRouterProvider.otherwise('/'); 

Then set a new state for /

 $stateProvider.state({ name: 'home', url: '/', controller: 'HomeCtrl', templateURL: 'home.html' }); 
+5
source

Otherwise, it is useful to redirect to the page with the error if the URL is bad. But you can try adding <base href="/" /> to reference the base location in your index and add $ locationProvider.html5Mode (true); after declaring routes in your configuration to enable, otherwise you need to add # to the URL.

Hope this helps you.

+1
source

Source: https://habr.com/ru/post/946001/


All Articles