我有一个相当简单的问题但到目前为止还没有找到答案。我有一个mongoose架构,其结构如下:
var mongoose = require('mongoose');
var schema = mongoose.Schema;
var family = new schema({
_id : String,
members : {
parent: [{
name: String,
age : Number
}],
child: [{
name: String,
age : Number
}]
}
});
以下是表单本身:
<form name="familyForm" id="familyForm">
<fieldset>
<select ng-model="familyDropdown" ng-click="populateFamily()" id="familyDropdown">
<option value="new">New Family</option>
<option ng-repeat="family in familyList track by family._id" bn-log-dom-creation="With" ng-model="family._id" value="{{family._id}}">{{family._id}}</option>
</select>
<input type="text" id="newFamily" placeholder="Create New Family" ng-model="family._id" ng-minlength="2" />
<input type="text" id="newParent" placeholder="Add a Parent to {{ family._id }}" ng-model="family.members.parent[0].name" ng-minlength="2" />
<span class="family-box-buttons">
<button type="submit" class="green-button" ng-click="addFamily(family)" ng-disabled="familyForm.$invalid">
<i class="fa fa-check"></i>
</button>
<button type="button" class="red-button" ng-click="cancelForm()">
<i class="fa fa-times"></i>
</button>
</span>
</fieldset>
</form>
以下是此难题的其他服务器端部分:
来自我的app.js
var mongoose = require('mongoose');
var express = require('express');
var app = express();
app.get('/family', api.getFamily);
app.post('/family/:_id', api.postFamily);
app.delete('/family/:_id', api.deleteFamily);
app.listen(3000, function(){
console.log('connected!');
});
从我的API
var Family = require('./family.js');
exports.getFamily = function(req, res){
Family.find({}, function(err, family){
if(err){
res.send('Family not found');
}
res.send(family);
});
};
exports.postFamily = function(req, res){
if(req.body){
console.log(req.body);
var family = new Family(req.body);
family.save(function(err, family){
if(err){
res.send('There was an error adding this Family');
}
res.send(family);
});
}
};
我的问题是,对于ng-model
封装的任何内容,使用[]
映射到架构时似乎有些困难。如果我只用family._id
我尝试过像ng-model="family.members.parent.name"
这样的事情但是意识到了这一点。符号专门授予访问对象模型而不是数组模型的权限。
我还尝试了ng-model="family.members.parent[].name
和ng-model="family.members.parent[name]
等内容。
我意识到这一定是一个相当简单的错误。如果有更好的方法,请指出正确的方向。任何指导都将不胜感激。
答案 0 :(得分:0)
尝试:
ng-model="family.members.parent[0].name"
基本上是一个数组:
var arr = [ "a", 23, { b: "bee" } ]
索引(即数组中项目的编号,从0开始)将访问一个元素。您必须使用括号表示法。
arr[0] // "a"
arr[1] // 23
arr[2] // { b: "bee }
arr.a // undefined
arr.b // undefined
对于某个对象,您可以使用 点表示法或括号表示法:
var obj = { a: "donkey", b: 23, c: { cat: "fish", rabbit: "ears" } }
obj.a // "donkey"
obj['b'] // 23
obj.c.cat // "fish"
obj['c']['rabbit'] // "ears"
obj.c['rabbit'] // "ears"
obj[0] // undefined