0

I am new to angular and I face a strange problem: not able to pass string from one controller to another.

I was trying few things including setting up data- attribute by using JQuery which works for me without Angular. Then to implement it thru the "service". It does not work for me. probably I mixed up something.

Could anybody provide clear and simple demo.

Thanks in advance!

2 Answers2

0

See below code. You need to write a sharing service to save your city name(refer service created by me in demo) and then you need to save city in sharing service wherever you getting city from server.

And in another controller you need to get that name of city from shared service.

var mainMod = angular.module('MainApp', []);
mainMod.controller('MainCtrl', ['$scope','dataShare',
    function ($scope,dataShare) {         
         $scope.city = 'London';
         $scope.send = function(){
           dataShare.saveCity($scope.city);
         };

    }
]);
mainMod.controller('MainCtrl2', ['$scope','dataShare',
    function ($scope,dataShare) {         
         $scope.getSavedCity = function(){
            $scope.cityInAnotherController = dataShare.getData(); 
         }
       
              
    }
]);
mainMod.factory('dataShare',function($rootScope){
  var service = {};

  service.saveCity = function(data){
      this.data = data;
  };
  service.getData = function(){
    return this.data;
  };
  return service;
});
<!-this is your HTML ->
<html >

  <head>
    
    <script data-require="angular.js@*" data-semver="2.0.0" src="https://code.angularjs.org/1.4.8/angular.js
"></script>
    <script data-require="jquery@*" data-semver="2.1.4" src="https://code.jquery.com/jquery-2.1.4.js"></script>
  </head>

  <body ng-app='MainApp'>
    <div ng-controller='MainCtrl'>
      <div>
        <h4>Ctrl1</h4>
        <div>{{text}}</div>
        <input type='text' ng-model='city' />
        <button type='button' ng-click='send();'>Send Data</button>
        {{city}}
      </div>
    </div>
    <div ng-controller='MainCtrl2'>
      <div>
        <h4>Ctrl2</h4>
        <button ng-click="getSavedCity()">Get Saved City </button> 
        <div>{{cityInAnotherController}}</div>
      </div>
    </div>
</body>

</html>
user1608841
  • 2,455
  • 1
  • 27
  • 40
0

That is what works for me dear experts..

        function selectedItemChange(item) {
        document.cookie = item.value;
        $('#dcity').show();
    }

...

url = '/api/Country/' + document.cookie;

And I've spent nearly all day trying service, factory and all patterns..