我是平均堆栈的新手,我正在建立一个电话簿系统。每个人可以拥有多个电话号码,我可以将其保存到下面的模型中。当我使用邮递员时,我能够保存它:
邮差
key:phones[1][type]
value:"mobile"
key:phones[1][number]
value:"123-123-1234"
key:phones[2][type]
value:"home"
key:phones[2][number]
value:"987-987-9876"
模式
const PhonesSchema = new Schema({
type: { type: String},
number: { type: String}
});
const PersonSchema = new Schema({
first_name: { type: String},
last_name: { type: String},
email: { type: String, unique: true},
phones: [PhonesSchema]
});
module.exports = mongoose.model('Person', PersonSchema);
当我尝试用角度来实现它时,我的问题出现了...我能够为1个电话号码做到这一点,但是当我想要添加更多的电话号码时却没有......当我试图传递person.phones [时] $ index] [type]它既不工作......
<form ng-submit="save(person)">
<fieldset data-ng-repeat="Phonefield in Phonefields track by $index">
<select name="type[$index]" ng-model="person.phones.type" class="form-control">
<option>Mobile </option>
<option>Home </option>
<option>Urgence</option>
</select>
<input type="text" placeholder="Phone" name="number[$index]" ng-model="person.phones.number" class="form-control">
<button class="btn btn-danger" ng-show="$last" ng-click="removePhonefield()">-</button>
<button class="btn btn-primary" ng-click="addNewPhonefield()">Add fields</button>
</fieldset>
<button type="submit" class="btn btn-primary" ng-click="save($index, person)">Create</button>
</form>
我的手机字段是使用此代码动态添加的(效果很好)
$scope.Phonefields = [{id: '0'}];
$scope.addNewPhonefield = function() {
var newItemNo = $scope.Phonefields.length+1;
$scope.Phonefields.push({'id':newItemNo});
};
$scope.removePhonefield = function() {
var lastItem = $scope.Phonefields.length-1;
$scope.Phonefields.splice(lastItem);
};
这是我的保存功能
$scope.save = function(index,person) {
$http.post('http://localhost:3001/api/person', person)
.then(function(response) {
$scope.persons.push(response.data);
});
如何转换我在Angular中传递的邮递员值?
项:电话[1] [式]
值: “移动”
谢谢大家
答案 0 :(得分:0)
我在此演示中解决了我的问题
https://coderwall.com/p/r7bl4w/ng-repeat-index-for-a-form-field-array-ie-add-new-option
最后,我将我的新阵列复制到空的阵列中,享受!