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?

1

3 Answers 3

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

Sign up to request clarification or add additional context in comments.

5 Comments

It's probably some other error on your side. Check out my Fiddle. It's working perfectly fine. Post your angular code.
In your exmaple there are two controllers, but they are separated, I have controller inside controller
At first I get value from AJAX and after I do: setProperty(objFromAjax);. But controller Map works faster that AJAX returns data
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.
Can yoy give me example how do it?
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/

Comments

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;
}]);

2 Comments

Look please comment to previos question, I use AJAX and it puts $scope, but controller Map works faster
OK, remember to complete your initial question to help next person understand the problem.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.