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

你说的曾经没有我的故事 提交于 2019-12-11 05:27:30

问题


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?


回答1:


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!



来源:https://stackoverflow.com/questions/24184829/can-a-service-that-provides-a-single-gettable-settable-variable-be-simplified

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!