1

I'm fairly new to AngularJS and I realise this question has been asked before (so hopefully I wont get voted down) but I've been unable to find a question matching my situation.

I want to pass search data (about 4 fields) from a search page (My HomeCtrl) to a ListingCtrl. The listingCtrl already uses a factory/service to get info based on whats passed from an API (I've hardcoded the data at present).

Now everything I read says uses another server/facotry to pass the data between the search page and the listing page but (and forgive me if I'm missing something) why not just pass these additional params as routeParams??

Incase you need to know - I'm using partials and route params to navigate around the app and pass a few simple IDs between pages.

Jimothey
  • 2,414
  • 9
  • 41
  • 66
  • If it's a single page app, use the service's to share data since it will persist. Else, go with params. – tymeJV Feb 18 '14 at 16:17
  • @tymeJV I have 3 partials going though one ng-view - so I'm guessing it would be classed as single page? – Jimothey Feb 18 '14 at 16:19
  • Yep, should be storing data in a service/factory -- way easier than route params IMO – tymeJV Feb 18 '14 at 16:21
  • 1
    nope. route params are fair enough. Imagine case you open just put url with these params - it will work, rather then if you save it in service share it won't . I agree if there are dozens of fields, but 4 is too small. for service share. ui-router for example is an excellent case – Eugene P. Feb 18 '14 at 16:22

1 Answers1

3

I suggest to use a service.

If you want stock persistant data, i suggest to use this https://github.com/Zmetser/localstorageservice

This module uses localStorage (documentation) (or cookies if you use IE)

Untested example:

The service

myApp.service('controllerSharingData', function() {
  var __variables = {};

  return {
   get: function(varname) {
    return (typeof __variables[varname] !== 'undefined') ? __variables[varname] : false;
   },
   set: function(varname, value) {
    __variables[varname] = value;
   }
  };
});

Controllers

myApp.controller('IndexCtrl', function($scope, controllerSharingData) {
  controllerSharingData.set('toto', 'hello world');
});

myApp.controller('ListCtrl', function($scope, controllerSharingData) {
  alert(controllerSharingData.get('toto'));
});
Paul Rad
  • 4,820
  • 1
  • 22
  • 23
  • 1
    Thanks - this is now going to lead me into the dreaded - "whats the difference between factories and services" debate! – Jimothey Feb 18 '14 at 16:35
  • 1
    Np ;) Best answer is here: http://stackoverflow.com/questions/15666048/angular-js-service-vs-provider-vs-factory – Paul Rad Feb 18 '14 at 16:58