JohnDoo JohnDoo - 2 months ago 7
AngularJS Question

How to pass form data to another page?

im using angularJS v 1.5.6 and want to know how to pass my form data correctly with $location.path.

Here is my code Page A:

<form>
...
<button type="submit" ng-click="submit(formData)">submit</button>
</form>


JS:

app.config(['$routeProvider', function ($routeProvider) {$routeProvider
// Home
.when("/", {
templateUrl: "A.html",
controller: "ACtrl"
})
.when("/B/", {
templateUrl: "B.html",
controller: "BCtrl"
})
//fallback url if nothing matches
.otherwise({
redirectTo: '/'
});
}]);
app.controller('ACtrl', function ( $scope, $location, $http) {
$scope.formData = {};
$scope.submit = function() {
$location.path("/B/" + $scope.formData );
};
});
//controller for B page
app.controller('BCtrl', ['$scope', '$routeParams',
function($scope,$routeParams) {

$scope.formData = $routeParams.formData;
}]);


it is a pretty simple example, but i cant figure out how to solve it :(

By clicking the submit nothing happens. If i remove the $scope from $scope.formData i get a error like: Error: formData is not defined.

The terms in formdata are available, i tested it with console.log($scope.formData) and everything is ok.

here is the link plunker: https://plnkr.co/edit/K5zwcmRRyom5HR4a5Q9o

EDIT



the only issue is now, how to handle the select object correctly in the foreach loop. Need help please

Answer

You can do it by creating a service and using setter/getter in order to transfer a variable. For example like this: https://plnkr.co/edit/IuTXsVLU7dq3TylfnSYP?p=preview

app.service('TransferService', [function(){

 var savedData,
 service = {
   getData: getData,
   setData: setData
 }

 function getData(){
   return savedData
 }

 function setData(data){
   savedData = data
 }

 return service
}])