AngularJS - Data transfer between pages

I am an AngularJS starter. I am trying to send data from:

  • Page A: Van listing page

    to

  • Page B: Van Update Page.

When the user clicks the update link for the van, I call the controller and retrieve the data about the van in the controller. But I cannot assign van details on page B (Van updates page) using the same controller ... Error "Cannot set property 'vanNumber' of undefined"

 *** Page A: Van List **** <form name="listVanForm" > <table> <tr> <td ng-controller="VanUpdateCtrl"><a href="#/van-update" ng-click="prePopulateForm(row.members.vanNumber.value )" class="btn btn-small btn-primary">update</a></td> </tr> </table> </form> *** Page B: Van Update **** <div class="container"> <h2>Edit Van </h2> <form name="updateVanForm" novalidate="novalidate" class="form-horizontal" ng-submit="updateCard(formData)"> <div class="control-group"> <label class="control-label" >Van Number:</label> <div class="controls"> <input type="text" id="vanNumber" ng-model="formData.vanNumber" placeholder=""/> </div> </div> </form> </div> *** VanUpdateCtrl ** app.controller('VanUpdateCtrl', ['$scope', 'VanUpdateFactory', '$location', function ($scope, VanUpdateFactory, $location) { //callback for ng-init 'populateDD': $scope.prePopulateForm = function (cardNoParam m) { alert('cardNo = '+cardNoParam); $scope.formData.cardNumber=cardNoParam;} } So, $scope.formData.cardNumber OR $scope.formData in the destination page is not recognised. 
+58
angularjs
Mar 14 '14 at 15:08
source share
4 answers

You need to create a service for exchanging data between controllers.

 app.factory('myService', function() { var savedData = {} function set(data) { savedData = data; } function get() { return savedData; } return { set: set, get: get } }); 

In your controller A:

 myService.set(yourSharedData); 

In your controller B:

 $scope.desiredLocation = myService.get(); 

Remember to inject myService into the controllers by passing it as a parameter.

+108
Mar 14 '14 at 3:32
source share

If you only need to exchange data between views / regions / controllers, the easiest way is to save them in $ rootScope. However, if you need a generic function, it is better to define a service for this.

+7
Jan 21
source share

What you need to do is create a service for exchanging data between controllers.

Good tutorial https://www.youtube.com/watch?v=HXpHV5gWgyk

+6
Mar 14 '14 at 15:30
source share
 app.factory('persistObject', function () { var persistObject = []; function set(objectName, data) { persistObject[objectName] = data; } function get(objectName) { return persistObject[objectName]; } return { set: set, get: get } }); 

Fill it with such data

 persistObject.set('objectName', data); 

Get object data like this

 persistObject.get('objectName'); 
0
Nov 26 '17 at 10:24
source share



All Articles