how to pass a object to a new page in angulatjs

646 views
Skip to first unread message

duck

unread,
Feb 27, 2014, 11:18:12 AM2/27/14
to ang...@googlegroups.com
I have a list of objects in the list view, now I want to click any one object to take me a new page without fetching data from server, so the object data can be passed to the new page. I can use angularjs   
$routeParams to pass individual parameter, but not whole object. if I use a individual parameters to fetch data from server, it slows down the performance.
 
Thank you for your help!
Lily

Guillaume Biton

unread,
Feb 28, 2014, 3:00:27 AM2/28/14
to ang...@googlegroups.com
You can set it into $rootScope or a global controller scope in your app

Regards

Guillaume

Luke Kende

unread,
Feb 28, 2014, 3:10:05 AM2/28/14
to ang...@googlegroups.com
You'll need to keep your objects referenced in a service, then use some id that maps to the $routeParam.  Something like this:

function MyService(){
  var objects = [
    { id: 1, data: 'the data'},
    { id: 2, data: 'more data'}
  ]
  
  return objects;
}

//in new route controller - this not fully fleshed-out code.... just providing the idea
var indexOfObject = MyService.indexOf($routeParams.id);
$scope.object = MyService[indexOfObject];

So in essence you are passing references not objects, and storing shared data in a service.

Luke Kende

unread,
Feb 28, 2014, 3:15:41 AM2/28/14
to ang...@googlegroups.com
If you are using $rootScope, which I personally think a service is the better practice, you will need to use ng-click and point it to a function that references the clicked object:

<li ng-repeat="object in objects">
  <a ng-click="viewObject(object)">View</a>
</li>

function TheCtrl($location){
  $scope.objects = [
    { id: 1, data: 'the data', path:'/path/to/this/object'},
    { id: 2, data: 'more data', path: '/path/to/this/object'}
  ]

  $scope.viewObject(object){
    $rootScope.currentObject = object;
    $location.path(object.path);

Zhenghao Huang

unread,
Feb 28, 2014, 5:50:21 AM2/28/14
to ang...@googlegroups.com
Agreed, Service is better practice.

duck

unread,
Feb 28, 2014, 10:14:02 AM2/28/14
to ang...@googlegroups.com
 I will try service. Thank you All!
Reply all
Reply to author
Forward
0 new messages