它提供了一个单一的GetTable /设置变量的服务可以简化? [英] Can a service that provides a single gettable/settable variable be simplified?

查看:100
本文介绍了它提供了一个单一的GetTable /设置变量的服务可以简化?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有这样的服务:

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);

经过5年的POJO,我对的getter / setter方法​​虽小,但强烈的憎恨。有没有更好的方式与角度做到这一点? provide.constant和provide.value似乎并不符合这个要求。我无法找到一个插件来做到这一点either--是有一些词汇对于这个概念我是无知的?

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?

推荐答案

您可以只需直接使用对象是这样的:

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;
});

这大约是接近一个POJO,你可以得到。希望帮助!

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

这篇关于它提供了一个单一的GetTable /设置变量的服务可以简化?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆