How to pass data from one page to another in single page application in angular

Issue

How can i pass data or value from one page to another in angular single page application . This is my first time to work with angular/typescript and javascript as a whole.

My objective is to pass userid to edit user page.
I am using

 "angular": "^1.7.2",
 "angular-route": "^1.7.2",

My current structure is something like this
in route.js

app.config(function($routeProvider){
  $routeProvider
  .when('/',{
    templateUrl:'home.html'
  })
  .when('/user',{
    templateUrl:'showUsers.html'
  })
.when('/user-edit/:userId',{
  templateUrl:'editUser.html'
})
})

in showUsers.html

<a href="#!user-edit/92">User Edit screen</a>

Now what i want to do is to capture the userId in jquery script of user edit screen so i can get user data.

How can i do that??

I m following

  1. https://www.w3schools.com/angular/angular_routing.asp
  2. https://docs.angularjs.org/tutorial

I also followed some questions over stack overflow

How do I pass data to Angular routed components?
But that did not help me.

Solution

Using $routeParams service: $routeParams service allows us to retrieve route parameters.

var module = angular.module("myApp", ['ngRoute']);
module.config(['$routeProvider', function ($routeProvider) {
    $routeProvider
        .when('/route1/:param1/:param2', {
            templateUrl: 'route1.html',
            controller: 'RoutingController'
        })
        .when('/route2/:param1/:param2', {
            templateUrl: 'route2.html',
            controller: 'RoutingController'
        })
        .otherwise({
            redirectTo: '/route1/default-book/default-page'
        });
}]);
module.controller("RoutingController", function ($scope, $routeParams, $location) {
    // Using $routeParams
    $scope.param1 = $routeParams.param1;
    $scope.param2 = $routeParams.param2;
});

Answered By – Chellappan வ

Answer Checked By – Katrina (AngularFixing Volunteer)

Leave a Reply

Your email address will not be published.