Creating a SPA  containting multiple pages/views would require the use of a router like ui-router. The only thing about ui-router is that the documentation is kinda messed up. I will explain how to pass parameters between multiple views.

When you switch between states in your Angular app, you will sometimes need to pass some parameters to the state you want to enter. Mostly you will pass some kind of a number that stands for the primary key of the entity you are trying to show.

In the code below you see an state that requires a personId as a param. The url of the state contains a placeholder where the personId param is expected.

If you would go to the URL /person/1337/  or calling ui-sref="person.detail({personId:1337})" or even calling $state.go("person.detail", {personId: 1337}), then the personId can be acquired by calling $stateParams.personId. Keep in mind that you could get a string value.

$stateProvider
   .state("person.detail", {
		url: "/person/:personId/",
		templateUrl: "templates/personDetail.html",
		controller: "PersonDetailController"
	});

 

Let's come to the next part. Sometimes you want to pass some object as param. UI-router allows that, but you need to define the param first in your state.You can't just pass randomly params until you have defined them. These parameters are optional and have their initial value.

$stateProvider
   .state("person.detail", {
		url: "/person/:personId/",
		templateUrl: "templates/personDetail.html",
		controller: "PersonDetailController",
                params: {
                    dateOfRequest: new Date(), //inital default value
                    manager: null //Null  as initial value but yet is defined
                }
	});

In the code above I have defined the params dateOfRequest and manager. These parameters must have a initial value. If you really don't need a initial value, then you can set the parameter value on null.

This is the way how we pass the params now:

$state.go("person.detail", {personId: 1337, dateOfRequest: getDate(), manager: getManager()});

Same story if you use ui-sref:

ui-sref="person.detail({personId:1337, dateOfRequest: getDate(), manager: getManager()})"

In the controller of the state you want to switch you can fetch the parameter like this:

.controller("PersonDetailController", function($scope, $stateParams) {
    $stateParams.personId;
    $stateParams.dateOfRequest;
    $stateParams.manager;
});

 

The last way to pass value between controllers, states, views is using the Angular service. A service is only instantiated once and it's reference is shared.

Angular services are:

  • Lazily instantiated – Angular only instantiates a service when an application component depends on it.
  • Singletons – Each component dependent on a service gets a reference to the single instance generated by the service factory.