0

How do I pass data from one controller to another?

I read many things like use root Scope, use services, use broadcast event etc., but nothing seems to be working. Can some one please guide me?

Termininja
  • 6,620
  • 12
  • 48
  • 49
  • 1
    See this question for a code example: http://stackoverflow.com/questions/21919962/share-data-between-angularjs-controllers – DevDig Jan 16 '17 at 07:27
  • here is the plunker: https://plnkr.co/edit/T2QZMamO8tg5wPnm2V40?p=preview –  Jan 16 '17 at 07:45

2 Answers2

0

You can use a Service or factory to share the data across the controllers.

DEMO

var app = angular.module("clientApp", [])
 app.controller("TestCtrl", 
   function($scope,names) {
     $scope.names =[];
    $scope.save= function(){
      names.add($scope.name);
    }
   
   
   }
  );
  
 app.controller("TestCtrl2", 
   function($scope,names) {   
   
   $scope.getnames = function(){
     $scope.names = names.get();
   }
  }
  );
app.factory('names', function(){
  var names = {};

  names.list = [];

  names.add = function(message){
    names.list.push({message});
  };
  
  names.get = function(){
    return names.list;
  };

  return names;
});
<!doctype html>
<html >

<head>
  <script src="//ajax.googleapis.com/ajax/libs/angularjs/1.5.8/angular.min.js"></script>
  <script src="script.js"></script>
</head>

<body ng-app="clientApp">
  <div ng-controller="TestCtrl">
    <input type="text" ng-model="name">
    <button ng-click="save()" > save</button>
    
  </div>
  
  <div ng-init="getnames()" ng-controller="TestCtrl2">
     <div  ng-repeat="name in names">
       {{name}}
       </div>
     
  </div>
</body>

</html>

DEMO WITH ROUTE

Sajeetharan
  • 216,225
  • 63
  • 350
  • 396
0
I think you are switching controller due to state change. Then an easy way to pass data from parent controller to any child controller apart from using factory or services is using state params

// In parent controller
$state.go('child.state', {
        'key' : $scope.value
    });
 //In child controller
$scope.sentObject = angular.copy($stateParams.key);
Yauza
  • 180
  • 1
  • 13
  • It is not a parent child controller relationship. –  Jan 18 '17 at 10:00
  • It doesn't have to be, It just sends some value to angular along with the state your are changing to. And you can access it in the controller of this new state. – Yauza Jan 20 '17 at 09:07