angularjs - Share a variable across controllers -


i have service methods,

 var selectedtype = 0;  .........  .........  return {             updatetype: function (type) {                 return selectedtype = type;             },              gettype: function () {                 return selectedtype;             }         } 

i want share selectedtype variable across 2 controllers. calling updatetype method 1 controller , opening new popup page calling gettype method.

issue is, gettype method returning 0 in popup page, value assigned main page 2 (by calling updatetype method).

main page,

angular.module('controller1module', []) .controller('mycontroller1', ['$scope', 'myservice',  function ($scope, myservice) {   myservice.updatetype(1);  $scope.$watch(myservice.gettype , function(newvalue, oldvalue){                             $scope.selectedtype = myservice.gettype();                         }); } 

popup controller,

angular.module('controller2module', []) .controller('mycontroller', ['$scope', 'myservice',  function ($scope, myservice) {     $scope.$watch(myservice.gettype , function(newvalue, oldvalue){                             $scope.selectedtype = myservice.gettype();                         }); } 

my service,

angular.module('servicemodule', [])  .service('myservice', ['$rootscope',   function($rootscope){      var selectedtype = 0;         return {                updatetype: function (type) {                 return selectedtype = type;             },              gettype: function () {                 return selectedtype;             }     ]); 

here's example using $scope.$watch see changes in myservice.gettype(). particular implementation uses watches because value returned myservice.gettype() string (which value), instead of object (which returns reference) - change in service's selectedtype property not automatically noticed scope in controllers, since they've received value of in service @ time gettype() called.

(function() {    angular.module('myapp', [])      .controller('controller1', ['$scope', 'myservice', controller1])      .controller('controller2', ['$scope', 'myservice', controller2])      .service('myservice', ['$log', myservice]);      function controller1($scope, myservice) {      $scope.$watch(        myservice.gettype,        function(newvalue, oldvalue) {          $scope.selectedtype = myservice.gettype();        }      );      $scope.updatetype = myservice.updatetype;    }      function controller2($scope, myservice) {      $scope.$watch(        myservice.gettype, //watch service function changes in return value, update local scope        function(newvalue, oldvalue) {          $scope.selectedtype = myservice.gettype();        }      );    }      function myservice($log) {      var _selectedtype = 0;        function _updatetype(type) {        $log.log("updatetype: " + type);        return _selectedtype = type;      }        function _gettype() {        $log.log("gettype: " + _selectedtype);        return _selectedtype;      }        return {        updatetype: _updatetype,        gettype: _gettype      }    }  })();
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.28/angular.min.js"></script>  <div ng-app="myapp">    <div ng-controller="controller1">      <div>        <input ng-model="newtype" />        <button ng-click="updatetype(newtype)">update type</button>      </div>      selected type in controller 1: {{selectedtype}}    </div>    <div ng-controller="controller2">      selected type in controller 2: {{selectedtype}}    </div>  </div>

alternatively, consider following (i've demonstrated multiple modules sharing, noticed possible requirement in comment of yours):

(function() {    "use strict";        // define services module can listed dependency of other modules    angular.module('myapp.services', [])      .service('myservice', ['$log', myservice]);      //here show module containing our controller depends on module service    angular.module('module1', ['myapp.services'])       .controller('controller1', ['$scope', 'myservice', controller1]);      angular.module('module2', ['myapp.services'])      .controller('controller2', ['$scope', 'myservice', controller2]);      // module being used ng-app='myapp' tie    // note since controller modules specify dependence on services module,    // don't need list again here.    angular.module('myapp', ['module1', 'module2']);      function controller1($scope, myservice) {      $scope.data = myservice.getdata(); // pass whole object, , scope binding expressions have '.' in them: {{data.selectedtype}}      $scope.updatetype = myservice.updatetype;    }      function controller2($scope, myservice) {      $scope.data = myservice.getdata();    }      function myservice($log) {      var _data = {        selectedtype: 0      };        function _updatetype(type) {        $log.log("updatetype: " + type);          _data.selectedtype = type;      }        function _getdata() {        $log.log("getdata called:");        $log.log(_data);          return _data;      }        return {        updatetype: _updatetype,        getdata: _getdata      }    }  })();
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.28/angular.min.js"></script>  <div ng-app="myapp">    <div ng-controller="controller1">      <div>        <input ng-model="newtype" />        <button ng-click="updatetype(newtype)">update type</button>      </div>      selected type in controller 1: {{data.selectedtype}}    </div>    <hr />    <div ng-controller="controller2">      <div>        <input ng-model="data.selectedtype" /> &lt;- 2-way binding, no separate update function needed      </div>      selected type in controller 2: {{data.selectedtype}}    </div>  </div>

in above example, we're returning object service. since objects passed reference, changes properties within service can seen controller holding reference it. makes 2-way binding pretty easy.

just remember if replace object in service instead of updating properties, you'll break references controllers have on (well, really, controllers maintaining reference old object, service containing new one). in case, helper functions angular.extend and/or angular.copy can make pretty easy update objects in service data properties of objects returned rest api calls, without replacing object entirely (thus avoiding breaking references).


Comments