2017-07-26 38 views
0

我是新的平均堆栈,我正在构建电话簿系统。每个人可以有多个电话号码,我可以在下面将它保存到模型中。我能救它,当我使用邮递员如下:如何使用角度保存阵列

邮差

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

我的问题来了,当我尝试用角去实现它?我能够做到这一点的电话号码,但不是当我想添加更多然后...当我试图通过person.phones [$索引] [类型]它也不工作......

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

    }); 

我如何转换内角邮递员值我通过,但?
键:手机[1] [类型] 值: “移动”

谢谢大家

+1

- 该保存功能中“person”的输出是什么?另外,请检查请求标题,它应该告诉你是否发送了其他电话号码。 – KFE

+0

此外,你的ng模型被设置为'ng-model =“person.phones.type”'..这不会起作用。它需要是'person.phones [$ index] .type'或类似的...我想象那是你的问题。您正在尝试为多个输入使用相同的模型。 – KFE

+0

如果我只输入1个数字(在请求标题中看到),但不止如此,则不会传输任何内容。当我用person.phones [$ index] .type ....相同的结果...什么都没有... – Dryan

回答