Siddhartha Thota Siddhartha Thota - 1 year ago 113
AngularJS Question

How to pass Data from One Controller to Other using Service?

I'm facing some issue while trying to pass the data from one controller to the other using my service.

I've been implementing the prototype inheritance using the $rootScope in my controller and broadcasting that object, so that I can access that data in the other controllers.

As I'm using the $rootScope, I'm polluting the global namespace, I'd like to pass the data from this controller to the other.

I'm just displaying minimal data inside a table, when the user clicks on specific record of the table, I want to display entire data inside the object.

This is how I'm handling.

<tr ng-repeat="contact in filterContacts = (contacts.contactsData | filter:sensitiveSearch | orderBy:selectBox) " ng-style="{'background-color': == ? 'lightgrey' : ''}" ng-click="selectContact(contact)">

Here is the reference Link:

I don't want to use the $rootScope, but I'd like to access the data onto the other controller.

Answer Source

You could use an angular service for this.

The angular services are singletons and you inject them in controllers so you could inject the same service in two different controllers and you are effectively passing state between them.

Imagine you have a property in your service which could be called selectedUserID. You update this property when you click on the specific row. Then in the next controller, you inject the same service and use this property to determine which details you will load.

so you could have a method inside your service which could look like this :

updateSelectedUser = function(userID) {
    this.selectedUserID = userID;

Your controller then calls this method from the service when the click action happens :


This is just an example of course, put your own values in there.

One thing to keep in mind : services can hold state, they are objects after all and singletons so you always inject the same instance.

It makes sense to make sure that the state stored inside the service is not modified by outside actions which do not go through this service. In other words make sure that nothing else changes this selectedUserID so your service state data never gets out of sync. If you can do this, then you are golden.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download