Reputation: 65
yesterday I asked about the data exchange form between controllers. But the correct question is how i exchange data between controllers after to redirect a some view. this is a idea(pseudoCode):
controller1("$scope", function($scope){
var val1 = $scope.dataFromview
href = ("#/search", val1);
});
controller2("$scope", function($scope, controller1){
var val2 = controller1.val1;
//make something with val2
});
Thanks
Upvotes: 1
Views: 1248
Reputation: 622
suppose that we want to share a Product object between the controllers. Here I have created an AngularJS service named SharedDataService as shown in the snippet below:
myApp.service('SharedDataService', function () {
var Product = {
name: '',
price: ''
};
return Product;
});
Next let’s go ahead and create two different controllers using SharedDataService. In the controllers, we are using the service created in the previous step. Controllers can be created as shown below:
var myApp = angular.module("myApp", ['CalService']);
myApp.controller("DataController1", ['$scope', 'SharedDataService',
function ($scope, SharedDataService) {
$scope.Product = SharedDataService;
}]);
myApp.controller("DataController2", ['$scope', 'SharedDataService',
function ($scope, SharedDataService) {
$scope.Product = SharedDataService;
}]);
On the view we can simply use the controllers as shown in the listing below:
<h2>In Controller 1h2>
<input type="text" ng-model="Product.name" /> <br/>
<input type="text" ng-model="Product.price" />
<h3>Product {{Product.name}} costs {{Product.price}} h3>
div>
<hr/>
<div ng-controller="DataController2">
<h2>In Controller 2h2>
<h3>Product {{Product.name}} costs {{Product.price}} h3>
div>
Upvotes: 0
Reputation: 46
Check out http://egghead.io/lessons/angularjs-sharing-data-between-controllers
Also prior post on stackoverflow Passing data between controllers in Angular JS?
You could define service that would be injected into both controllers:
app.service('exampleService', function() {
var val1;
var href = "#/search";
var setVal = function(newString) {
val1 = newString
};
var getVal = function(){
return val1;
};
return {
setVal: setVal,
getVal: getVal
};
});
Dependency inject the service into both controllers.
In your First controller, define some action that sets the value:
app.controller('ControllerOne', function($scope, exampleService) {
$scope.addValOne = function(newString){
exampleService.setVal(newString);
};
});
In your Second Controller, get the val1 from the service:
app.controller('ControllerTwo', function($scope, exampleService) {
$scope.val1 = exampleService.getVal();
});
Upvotes: 2