简体   繁体   中英

Passing data from one controller to another controller in AngularJS

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?

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM