【问题标题】:AngularJS - Can I bind an object to an entire form?AngularJS - 我可以将对象绑定到整个表单吗?
【发布时间】:2015-06-24 19:31:11
【问题描述】:

您可能认为这已经是 Angular 的一部分,但我找不到它。您可以使用 ng-model 将表单 fields 绑定到 $scope 中的变量。但我们不断地绑定,就像这样,100 个字段:

<form>
  <input name="foo" ng-model="object.foo" />
  <input name="foo2" ng-model="object.foo2" />
  <!-- and so on ... -->
</form>

Angular 是否提供了一种绑定表单并让每个字段绑定到它对应的对象属性的方法?像这样?

<form ng-model="object>
  <input name="foo" />
  <input name="foo2" />
  <!-- and so on ... -->
</form>

你认为应该存在这样的东西,对吧?手动单独绑定违反DRY。如果模型发生变化,它也很不灵活。

【问题讨论】:

  • 不,ng-model 只适合输入元素。
  • 违反 DRY 就是一遍遍地复制表格。不是因为您需要将ng-model 绑定到每个输入。虽然你建议的功能会很酷..

标签: angularjs forms


【解决方案1】:

正如 fals 所说,您的方法似乎很混乱。 我假设您可能想要重复一个模型并动态创建一个表单。

使用 ng-form,您可以在 $scope 上动态重复模型绑定 ng-model。 非常棒的部分是您甚至可以进行验证!

<div class="form-group" ng-repeat="human in people">
               <ng-form name="customform{{$index}}">
            <input type="text" id="email{{$index}}" ng-model="human.email" id="email{{$index}}" required>
            </ng-from>
</div>

Demo

【讨论】:

  • 你假设太多了,@Theodore。 :-) 我不想动态创建表单。我想创建一个表单,而不必重复“ng-model='whatever-the-property-is-named'。您认为 Angular 可以根据 推断每个对象属性。所以......非常酷的想法你有!但不是我要问的。(+1 的想法和 jsFiddle)。
猜你喜欢
  • 2014-04-22
  • 1970-01-01
  • 2011-03-02
  • 2021-09-23
  • 2017-12-12
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多