Skip to content Skip to sidebar Skip to footer

Sharing Data Between Controllers In Angular Js?

Before this is marked as duplicate I've read quite of few similar questions, but all the answers I've found seem to use $scope, and after reading the documentation I'm not really s

Solution 1:

You need to inject the service in order to use it, then access the service variable.

demoModule.controller("demoContollerOne", function($scope, demoService) {
  $scope.oneFunction = function(){
    demoService.demoSharedVariable = $scope.oneInput;
  };
});

demoModule.controller("demoContollerTwo", function($scope, demoService) {
  $scope.twoFunction = function(){
    demoService.demoSharedVariable = $scope.twoInput;
  };
});

If you are using controllerAs, you rarely (or shouldn't) need to inject and use $scope. As controllerAs is a relatively newer feature, back then we have no choice but to use $scope, so it is not strange to find example with $scope.


Edit: If you are not using controllerAs (like in this example) you would need $scope to expose functions or variables to the view.

There are several place that are not correct I've found while fiddling with it, I'll edit the code. I don't know how to showcase the effect without using advanced concept like $watch, please provide your own fiddle if you don't understand.

Jsbin

Solution 2:

One important thing is if you want to use angular, you have to understand the knowledge of scope.

Since neither you factory or controller is correct, i write a simple example for you to help you understand the service:

detail implementation in this plnkr:

service:

angular.module('myApp').service('MyService', [function() {

      var yourSharedVariable; // Your shared variable//Provide the setter and getter methodsthis.setSharedVariable = function (newVal) {
        yourSharedVariable = newVal;
      };

      this.getSharedVariable = function () {
        return yourSharedVariable;
      };

    }
]);

controller:

myApp.controller('Ctrl2', ['$scope', 'MyService', '$window', function($scope, MyService, $window) {//inject MyService into the controller$scope.setShared = function(val) {
      MyService.setSharedVariable(val);
    };

    $scope.getShared = function() {
      return MyService.getSharedVariable();
    };

    $scope.alertSharedVariable = function () {
      $window.alert(MyService.getSharedVariable());
    };

}]);

Post a Comment for "Sharing Data Between Controllers In Angular Js?"