AngularJS 正在从我的模式对象中剥离键

AngularJS is stripping keys from my schema object

编辑:这不是服务器端问题。请仔细阅读问题

我正在使用 Mongoose、Express、Node 和 Angular 构建解决方案。我正在尝试发送我的 Mongoose 模式文件客户端进行解析。我已经成功地在我的控制器脚本(客户端)中的一个对象中获取了数据,结构如下:

{
    href: {type: String},
    text: {type: String, trim:true},
    dropdown: {type: Boolean},
    dropdownList: {type: Array}
}

这是通过 $scope.$apply 传递的(因为它是在回调中收到的,)并且在 HTML 中收到,如下所示:

{
    href: {},
    text: {trim:true},
    dropdown: {},
    dropdownList: {}
}

拥有数据类型对我的实现来说极其重要。有什么想法吗?

在您的对象中,您尝试分配 StringArrayBoolean.. 并注意 这些值不是字符串值 这些只是关键字。如果你有数字你可以这样做,所以你需要使用这些值作为 string values

{
    href: {type: 'String'},
    text: {type: 'String', trim:true},
    dropdown: {type: 'Boolean'},
    dropdownList: {type: 'Array'}
};

这是一个demo

如果你不关心猴子修补函数对象,你可以这样做。

在服务器甚至客户端浏览器中 res.json 代码 运行 之前的任意位置添加以下内容。

Function.prototype.toJSON = function() { return this.name; }

用节点测试

# node

> var schema = {
...     href: {type: String},
...     text: {type: String, trim:true},
...     dropdown: {type: Boolean},
...     dropdownList: {type: Array}
... }
undefined

> schema
{ href: { type: [Function: String] },
  text: { type: [Function: String], trim: true },
  dropdown: { type: [Function: Boolean] },
  dropdownList: { type: [Function: Array] } }

> JSON.stringify(schema)
'{"href":{},"text":{"trim":true},"dropdown":{},"dropdownList":{}}'

> Function.prototype.toJSON = function() { return this.name; }
[Function]

> JSON.stringify(schema)
'{"href":{"type":"String"},"text":{"type":"String","trim":true},"dropdown":{"type":"Boolean"},"dropdownList":{"type":"Array"}}'
>