Aspirant9
Aspirant9

Reputation: 165

Exchanging data between different controllers in angularjs?

I am trying to exchange data between two different controllers. I will access data in different controllers. I use /loading for showing a spinner. While navigating between different pages I load this spinner and after some time delay I navigate to another url which is intended. So I use this service to store the uri.

I have the following service in my angular js app.

myApp.service('myService', function() {
    var data = "";
    return {
        getUri: function () {
            return data;
        },
        setUri: function (uri) {
            data = uri;
        }
    };
});

The following are my routes:

twitter.config([ '$routeProvider', '$locationProvider',
    function($routeProvider, $locationProvider, $routeParams) {
        $routeProvider.when('/', {
            templateUrl : 'main.html',
            controller : 'mainController'
        }).when('/loading', {
            templateUrl : 'spinner.html',
            controller : 'spinnerController'
        }).when('/login', {
            templateUrl : 'login.html',
            controller : 'loginController'
        }).when('/signup', {
            templateUrl : 'signup.html',
            controller : 'signupController'
        });
        $locationProvider.html5Mode(true);
    } ]);

so I am trying to put data into the service by doing

myService.set('mydata');

and getting data by

myService.get();

But every time when I try to access the service in different controllers defined above I get empty string.

Upvotes: 2

Views: 63

Answers (2)

Pavan Teja
Pavan Teja

Reputation: 3202

your service public methods are getUri and setUri but you are trying to use as myservice.get() and myservic.set().check the below snippet

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

myApp.controller('controller1', function($scope, myService) {
  $scope.ControllerData = 'From Controller 1';
  myService.setUri('www.google.com');

});

myApp.controller('controller2', function($scope, myService) {
  $scope.ControllerData = 'From Controller 2';
  $scope.sharedData = myService.getUri();

});


myApp.service('myService', function() {
  var data = "";
  return {
    getUri: function() {
      return data;
    },
    setUri: function(uri) {
      data = uri;
    }
  };
});
<!DOCTYPE html>
<html ng-app="myApp">

<head>
  <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.1.5/angular.min.js"></script>
  <meta charset=utf-8 />
  <title>ng-click</title>
</head>

<body>

  <div ng-controller="controller1">
    Controller1 Data: {{ControllerData}}
  </div>
  <div ng-controller="controller2">
    Controller 2 Data:{{ControllerData}}
    <br>Shared Data :{{sharedData}}
  </div>
</body>

</html>

Upvotes: 2

ojus kulkarni
ojus kulkarni

Reputation: 1907

Try to set in this way :

setUri: function (uri) {
    this.data = uri;
}

Upvotes: 0

Related Questions