Arguments not passing through my service between controllers

66 Views Asked by At

Here is my service:

var MyService= function () {
    var filters, charts, subscription;

    return {
        getFilters: function () {
            return this.filters;
        },
        setFilters: function (value) {
            this.filters = value;
        },
        getCharts: function () {
           return this.charts;
        },
        setCharts: function (value) {
           this.charts = value;
        },
        getSubscription: function () {
           return this.subscription;
        },
        setSubscription: function (value) {
           this.subscription = value;
        }
    };
};

angular.module('Something').factory('MyService', MyService);

Your typical service that can be used to pass arguments between controllers.

Controller A has a function that gets called when a user selects a link; the function sets my item in my service and uses window to redirect to another page.

$scope.pressedButton = function (subscription) {
   MyService.setSubscription(subscription);
   $window.location.href = 'newPage.html';
}

Controller B for the newPage.html should be able to read and console.log out myItem from my service however, it says it's undefined.

console.log(MyService.getSubscription()) == undefined.

Anyone know why? I've been using setters and getters but because I'm a bit limited to my routing ($window instead of ui-router or ng-router), I feel like moving to a brand new page is what's clearing out my service...

2

There are 2 best solutions below

1
On

I personally prefer the $factory data model syntax, as it gives you pseudo-private variables and a single access point for all this data. This makes it easier to test your code, and less likely for it to gain malformed data.

Also, if you are going to be trying to route around like that, I would recommend ui-router.

In a seperate service from where you are doing the set/get, include $state and just inject that template file into your view.

But syntax wise, @alwang85 is correct. :+1:

3
On

I believe you may have the syntax of factories and services swapped.

myApp.factory('sample', function(){
  var obj = {
    item: ''
  }
  return {
    getItem: function () {
      return obj.item;
    },
    setItem: function (value) {
      obj.item= value;
    }
  }
}

vs a service

myApp.service('sample', function(){
  var _item = '';
  this.getItem = function () {
      return _item;
    };
  this.setItem = function (value) {
      _item = value;
    }
}