Link to home
Start Free TrialLog in
Avatar of Brant Snow
Brant Snow

asked on

Angular service to share objects between controllers

Lets say I have 2 angular controllers and I want to share data between them, using a service or factory could be used for that and some getters and setters could be used something like this.

app.service('MassShip', function() {
                  var list = [];
                  return {
                        addItem: addItem,
                        getList: getList,
                        getLength: getLength
                  };
                  function addItem(item) {
                        list.push(item);
                  }
                  function getList() {
                        return list;
                  }
                  function getLength() {
                        return list.length;
                  }
      });

However that requires injecting MassShip and whatever other services I create, what I would like to is something like this

app.service('MassShip', function() {
                  
this.TotalOrders = function(){
var list = [];
                  return {
                        addItem: addItem,
                        getList: getList,
                        getLength: getLength
                  };
                  function addItem(item) {
                        list.push(item);
                  }
                  function getList() {
                        return list;
                  }
                  function getLength() {
                        return list.length;
                  }

}

      });

That way I could call MassShip.TotalOrders and I could attach alot of other services to MassShip, however if I do this I get the error

MassShip.TotalOrders.addItem is not a function if I call MassShip.TotalOrders.addItem("hello");

How do I fix this so I could use them in this way
ASKER CERTIFIED SOLUTION
Avatar of Julian Hansen
Julian Hansen
Flag of South Africa image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial