vaved
vaved

Reputation: 129

How to pass data in controller Angular JS?

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?

Upvotes: 0

Views: 260

Answers (3)

Geoffrey Lallou&#233;
Geoffrey Lallou&#233;

Reputation: 1464

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

Upvotes: 0

Bidhan
Bidhan

Reputation: 10687

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

Upvotes: 2

paul
paul

Reputation: 22001

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/

Upvotes: 0

Related Questions