简体   繁体   中英

How to access the controller value from service in angularjs?

I want to access the controller values from service, how can I access it. I am try to access the controller values by using the following code. The code is here JsBin.com

    <script>

    var app = angular.module('app', [])
.controller("ctrl1",['$scope','svc',function($scope,svc){

    $scope.fun1=function(){
      svc.service_set();

      alert(svc.txt1);
      alert(svc.txt2);

    }

}])
.controller("ctrl2",['$scope','svc',function($scope,svc){

    $scope.fun2=function(){
        svc.service_set();

        alert(svc.txt1);
        alert(svc.txt2);
    }

}]).
service("svc",function(){
      var svc={};
      svc.service_set=function()
      {
        //I want to access the controller values from here
        svc.txt1=ctrl1.c1txt1; 
        svc.txt2=ctrl2.c2txt1;

      }

      return svc;
    })
;

    </script>

You should not use controllers inside your service. Services are meant to be used as container for reusable logic. Instead of calling controller from service, call service methods from controller

If you want to store controller values inside your service, pass the value with a connection to the controller. Or in your case, $scope .

.service(function () {
  var dataStore = {};

  this.set = function (ctrl, value) {
    dataStore[ctrl] = value;
  });

  this.get = function (ctrl) {
    return ctrl ? dataStore[ctrl] : dataStore;
  };
});

updated your jsbin


I would rethink your approach; If there are values residing in controllers that need to be accessed by other controllers, then said values should originate from services and/or factories. Or even just plain constants / values .

The controller would then fetch the values it desires, possibly modify them, and send any modifications back to the service so as to keep in sync.

The controller is the glue between your services and the view, not the other way around.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM