首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >在Angular JS中,我们应该使用什么来分配模型数据?

问在Angular JS中,我们应该使用什么来分配模型数据?
EN

Stack Overflow用户
提问于 2016-04-20 21:15:40
回答 2查看 67关注 0票数 3

我想知道使用Angular JS为每个表单元素分配模型名称的更好方法。

我可以使用单独的作用域变量来赋值它。

代码语言:javascript
复制
<input type="text" ng-model="firstName"/>
<input type="text" ng-model="lastName"/>

我也可以使用单例对象来赋值。

代码语言:javascript
复制
<input type="text" ng-model="contact.firstName"/>
<input type="text" ng-model="contact.lastName"/>

就内存和执行时间而言,哪种处理表单数据的方法更好?

EN

回答 2

Stack Overflow用户

发布于 2016-04-20 21:24:57

您应该选择第二个选项,以避免作用域继承问题,请参见the doc

作用域继承通常很简单,您甚至不需要知道它正在发生……直到您尝试将双向数据绑定(例如,表单元素、ng-model)到父作用域中定义的基元(例如,数字、字符串、布尔值)。

票数 2
EN

Stack Overflow用户

发布于 2016-04-20 23:50:22

据AngularJS的创建者Miško Hevery说:

当你有ng-

的时候,一定会有一个点在那里。如果你没有点,你就做错了。

问题是为什么?

因为ng-switch、ng-repeat等创建了自己的作用域。例如,have a look at this plnkr

代码语言:javascript
复制
      <form ng-submit='addName()'>

          Name 1: <input type='text' ng-model='name'/>
          <input type='submit' value="Submit"/>
      </form>

      <p ng-switch='true'>
          Name 2: <input type='text' ng-switch-when="true"  ng-model='name'/>
      </p>
      <p>
          Name 3: <input type='text' ng-model='name'/>
      </p>

输出:

​

​

在Name 1文本框中键入内容时,该值将立即显示在所有文本框中。这和预期的一样。问题是,现在当您在Name 2文本框中键入内容时,它的值将断开连接,并且三个框值不再同步。This is because of the way that JavaScript’s prototypal inheritance works。

为了避免这种情况,我们应该在ng-model中使用dot。例如,have a look at this plnkr

代码语言:javascript
复制
      <form ng-submit='addName()'>

          Name 1: <input type='text' ng-model='contact.name'/>
          <input type='submit' value="Submit"/>
      </form>

      <p ng-switch='true'>
          Name 2: <input type='text' ng-switch-when="true"  ng-model='contact.name'/>
      </p>
      <p>
          Name 3: <input type='text' ng-model='contact.name'/>
      </p>

输出:

​

​

现在,代码始终与这三个文本框保持同步。

来源:

  1. AngularJS MTV Meetup: Best Practices (2012/12/11)
  2. 5 AngularJS Antipatterns & Pitfalls
  3. Why ng-model value should contain a dot
  4. Nested Scopes in AngularJS
  5. AngularJS: dot in ng-model
  6. What are the nuances of scope prototypal / prototypical inheritance in AngularJS?
  7. Does my ng-model really need to have a dot to avoid child $scope problems?
  8. AngularJS: If you are not using a .(dot) in your models you are doing it wrong?
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/36745041

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档