How to share data between controllers in AngularJs?

To share data between controllers in AngularJs we have to states.

For using states, we need to include angular-ui-router in your application.

<script src=”//cdnjs.cloudflare.com/ajax/libs/angular-ui-router/0.2.11/angular-ui-router.js”></script>

To use ui-router we need to create dependency on ui-router.

angular.module(“app”,["ui.router"])

Then create states for your controllers as shown below:

.config(function config($stateProvider){

$stateProvider.state(“index”,{

url:”/yourUrl”,

controller:”firstController as first”,

templateUrl:”template_url”

})

$stateProvider.state(“second”,{

url:”/yourSecondPageUrl”,

controller:”secondController as second”,

templateUrl:”template_url”

})

})

Then write service to pass data in both controllers as parameter.

.service(“data”, function  shareData(){

var data = this;

data = “data_to_transfer”

})

.controller(“firstController”, function(data){

var first = this;

first.data = data;

})

same for secondController.

Now, in your view you can access it as {{first.data}} and likewise for secondcontroller.

To redirect to new state use

<div ui-sref=”second”>Go to second page</div>


ProsperaSoft offers AngularJs development solutions. You can email at info@prosperasoft.com to get in touch with ProsperaSoft AngularJs experts and consultants.

 

 

 

Leave a Reply

Your email address will not be published. Required fields are marked *


*

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>