Mistalis Mistalis - 1 year ago 63
AngularJS Question

Pass an object in a redirection

I am trying to use

$location
for redirecting to one of the page of my app by providing an object of my
$scope
.

Here is a simplified version of what I'm trying to achieve:

HTML

<div>
Name: {{bruce.name}}
E-mail: <a ng-click="contact(bruce)">{{bruce.mail}}</a>
</div>


In my Angular controller

$scope.bruce = {name: 'Bruce Wayne', mail: 'brucewayne@batman.com'}

/* Should redirect to mail page with dest object */
$scope.contact = function(dest) {
$location.path("/mail");
// Provide dest object
}





In the second page (which has a different controller), I would like to be able to show the sended object:

<div>
<p>From: mymail@me.com <br/>
To: {{dest.mail}}</p>

<p>Type your email...</p>
</div>





I guess the solution is really simple, so I don't need a full working code, but I would appreciate some ideas for how to achieve this.

PS: A solution without using
$location
may suit me as well.

Answer Source

That is a typical scenario where you share data inside your application. A potential solution should be this:

var app = angular.module('myApp', []);
app.service('myService', function(){
  var data;
  this.setData = function(d){
    data = d;
  }
  this.getData = function(){
    return data;
  }
});

app.controller('myCtrl1', function($scope, myService){
 ..
 myService.setData(objectSent);

});

app.controller('myCtrl2', function($scope, myService){
 $scope.objectSent= myService.getData();
 //do something
});

Services are singleton, are instantiated once and then cached by angular, everytime you need that specific data you can inject the service and call the methods provided.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download