【问题标题】:How to save an Array with angular如何用角度保存数组
【发布时间】:2018-01-02 03:20:54
【问题描述】:

我是平均堆栈的新手,我正在构建一个电话簿系统。每个人可以有多个电话号码,我可以将它保存到下面的模型中。当我使用邮递员时,我可以保存它,如下所示:

邮递员

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

当我尝试使用 angular 来实现它时,我的问题就出现了……我可以为 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][类型] 值:“移动”

谢谢大家

【问题讨论】:

  • - person 在该保存功能中的输出是什么?另外,请检查请求标头,它应该会告诉您是否要发送其他电话号码。
  • 另外,你的 ng-model 设置为 ng-model="person.phones.type".. 那是行不通的。它需要是person.phones[$index].type,或类似的......我想这是你的问题。您正在尝试对多个输入使用相同的模型。
  • 如果我只输入 1 个数字,它可以工作(在请求标头中看到),但除此之外,没有任何内容被传输。当我使用 person.phones[$index].type.... 相同的结果...什么都没有...
  • 您是否遇到任何控制台错误?要使 person.phones[$index].type 之类的东西起作用,必须存在 person.phones[$index] 对象。
  • 电话条目看起来像电话:[]

标签: angularjs node.js mongoose


【解决方案1】:

我根据这个演示解决了我的问题

https://coderwall.com/p/r7bl4w/ng-repeat-index-for-a-form-field-array-ie-add-new-option

最后,我将我的新数组复制到空数组中,享受吧!

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2019-11-05
    • 2015-09-05
    • 1970-01-01
    • 2017-12-27
    • 2019-09-29
    • 1970-01-01
    • 2021-06-07
    • 2019-10-30
    相关资源
    最近更新 更多