Can a service in Angularjs be used as tool for data transfer between controllers?

Viewed 18

I have worked with this example to generate a data transfer between two different controllers in AngularJs, but it doesnt seem to work. Specifically I can change a variable of the service from the second controller and show it in its view, but the change will not show on the first controller. There, the variable has the original value which it has in the service. I think it has something to do with the life cycle of the controller, and maybe I need to call the sencond controller first from the frist controller so the changes can be made? Also the code I am working with is different from the exmaple meaning I have a view for every controller and I am not using ng-controller in the html as in the exmaple.

Service This is my service. I want to overwrite itemId with value from a "foreign" controller, and than use it in my controller dashctrl which is connected to my dashboard.html. var itemId = 10;

    this.getData = function()
    {
        //console.log('in the Get Function');
        return itemId;
    };
    
    this.setData = function(Id)
    {
        //console.log('in the Set Function');
        itemId = Id;
    };

Controller 1 This is the dashCtrl Controler where I read the variable itemId.

"Foreign" controller This is my foreign controller. I am trying to overwrite the variable from here so then I can use it in the dashboard.html which is only connected to dashCtrl, but its not working. This only shows the initial value of 10 of the service and nothing is overwritten. Now if I do the same with dashctrl the overwrite will work.

The view in html Screenshot from dashboard.html, calling the variable from dashCtrl.

1 Answers

Yes, it's possible and it was one the ways to handle or sync data between controllers in angularjs, we used services and factories.

I have a plnkr with an online demo here: https://plnkr.co/edit/ckV5P6nezNLpqvKK0vHm?preview

Basically, you need the service:

var app = angular.module('myApp', []);

app.service("myService", function() {
  var c = 10;
  
  this.theC = function () {
    return c;
  };
  this.updateC = function () {
    c++;
  }

In the app Controller you will have:

app.controller('myCtrl1', [
  '$scope',
  '$rootScope',
  'myService',
  function($scope, $rootScope, myService) {
    $scope.name = "Control 1";
    $scope.service = myService;
  }
]);

Finally in the template:

        <div class="col-xs-6">
          <h3>The Service</h3>
          Shared Parameter: {{service.theC()}}
          <br/>
          <span class="btn btn-primary" ng-click="service.updateC()">Add to Shared</span>
        </div>
Related