Aniket Narvankar

Aniket Narvankar

  • 559
  • 2.1k
  • 605.4k

Routing in Angular 1.x

Jul 21 2020 6:25 AM
I am trying to do routing in angular 1.x
 
This is my app.js file
  1. var app = angular.module('app', ['ui.router']);  
  2. app.config(function ($stateProvider, $urlRouterProvider, $locationProvider) {  
  3. $locationProvider.html5Mode(true);  
  4. $locationProvider.hashPrefix('');  
  5. $urlRouterProvider.otherwise('/home');  
  6. $stateProvider  
  7. // State managing  
  8. .state('home', {  
  9. url: '/home',  
  10. templateUrl: 'home1.html',  
  11. controller:'Home1'  
  12. }).state('home2', {  
  13. url: '/home2',  
  14. templateUrl: 'home2.html',  
  15. controller:'Home2'  
  16. }).state('home3', {  
  17. url: '/home3',  
  18. templateUrl: 'home3.html',  
  19. controller: 'Home3'  
  20. })  
  21. })  
I have added three js files home1,home2,home3 with controller name Home1,Home2,Home3 respectively
 
This is my code for all files
 
home1
  1. app.controller('Home1'function ($scope, $rootScope, $location) {  
  2. $scope.name12345 = sessionStorage.getItem('name1234');  
  3. $scope.back = function () {  
  4. $location.path('home2')  
  5. }  
  6. });  
home2
  1. app.controller('Home2',function ($scope, $rootScope, $location) {  
  2. $scope.msg = "Welcome";  
  3. $scope.name = sessionStorage.getItem('name');  
  4. $scope.data2 = JSON.parse(sessionStorage.getItem('data1'));  
  5. console.log($scope.data2);  
  6. $scope.click2 = function (name) {  
  7. alert(name);  
  8. $scope.name123 = name;  
  9. sessionStorage.setItem('name1234',($scope.name123))  
  10. $location.path('home3')  
  11. }  
  12. })  
home3
  1. app.controller('Home3',function ($scope, $rootScope, $location) {  
  2. $scope.msg = "Welcome";  
  3. $scope.click = function () {  
  4. sessionStorage.setItem('name', ($scope.msg))  
  5. sessionStorage.setItem('data1', JSON.stringify($scope.data))  
  6. $location.path('/home2');  
  7. }  
  8. });  
Now this controller and app module on all three html files home1.html,home2.html and home3.html
When I run home3.html it changes url name to home,instead of changing it to home3,you can check this code in app.js
  1. state('home3', {  
  2. url: '/home3',  
  3. templateUrl: 'home3.html',  
  4. controller: 'Home3'  
  5. })  
instead it consider this
 
$urlRouterProvider.otherwise('/home');
 
So my First question is when I run home3.html it should change url to home3,when I run home2.html it should change url to home2,when I run home1.html it should change url to home
 
And second question is I have used $location.path('home2') in this scenario I have to redirect to home2.html with home2 as Url but this is not happening to.
 
How to do this kindly guide me on this

Answers (2)