0

I have two controllers:

<div ng-controller="Main">
   <div ng-controller="Map"></div>
</div>

In controller Main I have variable $scope.mapCoord; How I can to pass this variable in controller Map?

vaved
  • 129
  • 1
  • 1
  • 12
  • possible duplicate of [Working with $scope.$emit and .$on](http://stackoverflow.com/questions/14502006/working-with-scope-emit-and-on) – paul May 19 '15 at 13:01

3 Answers3

2

Use a service. For example:

var app = angular.module('myApp', [])
app.service('sharedProperties', function () {
    var mapCoord= 'Test';

    return {
        getProperty: function () {
            return mapCoord;
        },
        setProperty: function(value) {
            mapCoord= value;
        }
    };
});

Inside your Main controller

app.controller('Main', function($scope, sharedProperties) {
    $scope.mapCoord= sharedProperties.setProperty("Main"); 
});

Inside your Map controller

app.controller('Map', function($scope, sharedProperties) {
    $scope.mapCoord= sharedProperties.getProperty(); 
});

Here's a fiddle for you. JSFiddle

Bidhan
  • 10,607
  • 3
  • 39
  • 50
  • It's probably some other error on your side. Check out my Fiddle. It's working perfectly fine. Post your angular code. – Bidhan May 19 '15 at 13:50
  • In your exmaple there are two controllers, but they are separated, I have controller inside controller – vaved May 19 '15 at 13:59
  • At first I get value from AJAX and after I do: `setProperty(objFromAjax);`. But controller `Map` works faster that AJAX returns data – vaved May 19 '15 at 14:08
  • You need to bind an element in your view to the property of your $scope object. Once the $scope object is updated after the AJAX request is complete, the view should be updated automatically. – Bidhan May 19 '15 at 14:13
  • Can yoy give me example how do it? – vaved May 19 '15 at 14:20
0

You use events to pass it between controllers using by $broadcast, $emit and $on

Working with $scope.$emit and $scope.$on

http://mariuszprzydatek.com/2013/12/28/sharing-data-between-controllers-in-angularjs-pubsub-event-bus-example/

Community
  • 1
  • 1
paul
  • 21,653
  • 1
  • 53
  • 54
0

In your "Map" controller, set "Main" scope to current scope such as below :

app.controller('Map', ['$scope','$controller',function($scope, $controller) {

    $controller('Main', {
        $scope : $scope
    });
}]);

After that you can access all the scope of Main controller from his son controller :

app.controller('Map', ['$scope','$controller',function($scope, $controller) {

    $controller('Main', {
        $scope : $scope
    });

    var coord = $scope.mapCoord;
}]);
Geoffrey Lalloué
  • 1,456
  • 1
  • 20
  • 43