【问题标题】:ng-model property is undefined in arrayng-model 属性在数组中未定义
【发布时间】:2019-11-17 04:28:14
【问题描述】:

我有一些带有ng-model="award.questions.propertyName" 的文本区域。我需要将这些输入值放入具有这种结构的数组中:

questions: [{
 key: value,
 key: value,
 ...
}] 

但是console.log 在我提交表单时将此值返回为未定义。 当我将问题定义为对象{} 时,它的作用就像一个魅力并且所有值都很好,但是当我将它放入数组时,它就没有任何作用。

查看

<textarea name="short-Description" ng-model="award.questions.shortDescription"></textarea>
<textarea name="consumer" ng-model="award.questions.consumer"></textarea>
<textarea name="advantages" ng-model="award.questions.advantages"></textarea>

控制器

$scope.award = {
  questions: [{
    shortDescription: $scope.shortDescription,
    consumer: $scope.consumer,
    advantages: $scope.advantages,
  }],
};

$scope.onSubmit = (award, awardForm) => {
  $scope.data = angular.copy(award);
  console.log($scope.data);
}

【问题讨论】:

  • 我不确定我是否完全理解这种情况。 textareas 在 ng-repeat 里面?你能显示你提到的form吗(onSubmit)。

标签: javascript arrays angularjs object


【解决方案1】:

因为您的 award 变量没有 question 属性。

您应该将代码更改为:

<textarea name="short-Description" ng-model="award.questions[0].shortDescription"></textarea>
<textarea name="consumer" ng-model="award.questions[0].consumer"></textarea>
<textarea name="advantages" ng-model="award.questions[0].advantages"></textarea>

如果您有多个问题,请联系ng-repeat

<div ng-repeat="question in award.questions track by $index">
  <textarea name="short-Description" ng-model="question.shortDescription"></textarea>
  <textarea name="consumer" ng-model="question.consumer"></textarea>
  <textarea name="advantages" ng-model="question.advantages"></textarea>
</div>

【讨论】:

  • 只有第一个元素被添加到那个 ng-model
  • 如果您有多个问题,请使用我提到的ng-repeat
【解决方案2】:

award.questions 是一个数组 - 所以它没有名为 consumer 的属性或任何其他变量(注意它是 questions 而不是 question)。使用[0] 获取数组中的第一项。

<textarea name="short-Description" ng-model="award.questions[0].shortDescription"></textarea>

但是,使用这种格式,使用一个对象会更容易。查看:

<textarea name="short-Description" ng-model="award.question.shortDescription"></textarea>

控制器:

$scope.award = {
  questions: {
    key: value,
    ...
  }
}

【讨论】:

    猜你喜欢
    • 2015-02-01
    • 2015-11-06
    • 1970-01-01
    • 1970-01-01
    • 2016-03-15
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多