Search code examples
javascriptangularjsangularjs-scopeangularjs-service

How to get a $scope object to an angular service


I have an object that I am modifying on $rootScope where I am "storing" my last search parameters. Currently I have the values returnType, rows, and query hard coded. I would like to those just be references to the object on $rootScope.

How can I reference an object on $rootScope in a service?

angular.module('myApp.services').factory("SearchService", function ($resource) {
    return $resource("/do/search", {}, {
        query: {method: "GET", isArray: false, params: {
            returnType: 'json',
            rows: 25,
            query:'bob*'
        }}
    })

Solution

  • I'm not a big fan of storing things like this in localStorage. I don't want to mod the above answer, because it's perfectly valid and it's good code. Thanks for Ed B's contribution there.

    On the other hand, there's a security implication - you're storing potentially sensitive query text in a relatively easy-to-access region, not that great for users on library/Internet cafe computers. Most people are used to clearing cookies, but that doesn't wipe out localStorage data so you'd either have to provide a mechanism for this, or suggest what, that all your users use "Incognito Mode"? I prefer to use things like localStorage for caching app data, but not user data unless you're sure it's not sensitive.

    Only you can decide if this is important. But since your original question was just about how to use $rootScope as a dumping ground, here's an answer for that specific piece. Just inject it into your service/factory/etc:

    angular.module('myApp.services').factory("SearchService", function($rootScope, $resource) {
    // You now have access to $rootScope here
    return $resource("/do/search", {}, {
        query: {method: "GET", isArray: false, params: {
            returnType: 'json',
            rows: 25,
            query: $rootScope.query
        }}
    });
    

    A couple of quick comments:

    1. Why call it a service and make it a factory? :) There isn't really an efficiency difference and the code might be a little simpler if you actually made it a full service.

    2. If you make it a real service, you probably don't need $rootScope any more. With a service, you can create a method that can be called from elsewhere... and then you can accept parameters directly from the caller. So the caller could send data right to the search function and then process its results. Simple!