Search code examples
angularjsangularjs-service

Can a service that provides a single gettable/settable variable be simplified?


I have a service like this:

var app = angular.module('someModule');
app.factory('token', function() {
  var token = null;
  return {
    get: function() {
      return token;
    },
    set: function(tokenIn) {
      token = tokenIn;
    }
  };
});

I'd rather have something like this:

app.variable('token', null);

After 5 years of POJOs, I'm have a small but intense hatred for getter/setters. Is there a better way to do this with angular? provide.constant and provide.value didn't seem to fit the bill. I couldn't find a plugin to do this either-- is there some vocabulary for this concept I am ignorant of?


Solution

  • You can just use the object directly something like:

    myApp.factory('token', function(){
        return { Token : '' };
    });
    

    Then you can inject the token factory into your controller and either get or set the token as follows:

    myApp.controller("Test", function ($scope, token) {
        // set:
        token.Token = 'abc';
        // or get
        var local = token.Token;
    });
    

    This is about as close to a "POJO" as you can get. Hope that helps!