【发布时间】:2015-01-30 23:28:11
【问题描述】:
后端返回json如下:
[
{
id: 1,
name: "the name",
countryIds: [ 1,2,3]
}, ...
]
如您所见,有countryIds 属性。在客户端,我已经缓存了具有相应 ID 的国家/地区名称:
[
{
id: 1,
name: "USA"
},
{
id:2, name: "France"
}...
]
,因此在检索此对象时,我只需添加新的 countries 属性,我在其中分配国家名称:
obj.countries = getCountryNamesByIds(obj.countryIds);
所以我的初始对象看起来像这样:
{
id: 1,
name: "the name",
countryIds: [ 1,2,3],
countries: ["USA", "France", "England"]
}
问题是在更新后将对象发送到服务器时(使用PUT 方法)我不想将countries 属性发送到服务器。我如何以更优雅的方式处理这种情况?在我看来,有几个选择:
1.向服务器发送对象时,只需删除所有不必要的属性(不好的方法,因为如果将新属性添加到 JSON,那么我也需要在控制器逻辑中应用相同的更改);
2.不要用new countries proeprty 修饰对象,暴露一些应用层的方法比如
$rootScope.getCountryNamesByIds = getCountryNamesByIds;
然后在模板中使用它:
<label> Countries </label>
<div> {{getCountryNamesByIds(obj.countryIds)}} </div>
3.不要使用新的countries proeprty 来装饰对象,并创建名为countryNames 的指令,该指令将从国家ID 生成国家名称(如第2 点):
<div country-names country-ids="obj.countryIds"> // There will be shown country names generated from their IDs</div>
你怎么看,哪个选项更优雅?或者还有什么其他方法可以解决我的挑战?
【问题讨论】:
标签: javascript json angularjs decorator