-3
var app = angular.module("myApp",[]);

app.controller("CTRL1", function($scope){
    $scope.data = [{'name':'Prateek'},{'name':'Agarwal'},{'name': 'Ketan'}];
})

app.controller("CTRL2", function($scope){
    $scope.data = [{'name':'Hari'}];
})

I have two controllers - CTRL1 and CTRL2. How can I access data from one controller in another?

  • 1
    You should use a service for that kind of purpose, so you can import it and use it anywhere in your app :) – DevMoutarde Jun 06 '17 at 18:16
  • https://stackoverflow.com/questions/43902680/how-to-transfer-the-data-between-controllers/43906406#43906406 – Sangwin Gawande Jun 06 '17 at 18:17
  • do not use $emit and $on in your controller. You should use a service for this or find some other way. If you are going to broadcast you should use sub-pub architecture . If these 2 controllers need to talk to each other perhaps they are one controller. If they can only exist together why have 2? I am assuming a lot here.. – Maccurt Jun 06 '17 at 18:59

1 Answers1

0

You can use $emit and $on functions for this, These will send data in any controll on spectfic event named.

<div ng-app="myApp" ng-controller="myCtrl"> 

    <button ng-click="sendData();"></button>

</div>


<script>
var app = angular.module('myApp', []);
app.controller('myCtrl', function($scope, $http) {
    function sendData($scope) {
        var arrayData = [1,2,3];
        $scope.$emit('someEvent', arrayData);
    }

});
app.controller('yourCtrl', function($scope, $http) {
    $scope.$on('someEvent', function(event, data) {
        console.log(data); 
    }); 
});
</script>
Sangwin Gawande
  • 7,658
  • 8
  • 48
  • 66