为什么 AngularJS 文档不在模型指令中使用点? [英] Why don't the AngularJS docs use a dot in the model directive?

查看:19
本文介绍了为什么 AngularJS 文档不在模型指令中使用点?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在视频中AngularJS MTV Meetup:最佳实践(2012/12/11),Miško 解释说..如果你使用 ng-model,那么在某处必须有一个点.如果你没有一个点,你就做错了.."

然而,Angular.JS 网站中的第一个例子(基础知识)似乎与它相矛盾.是什么赋予了?自 MTV 聚会以来,Angular.JS 是否发生了变化,现在它对 ng-model 更加宽容了?

解决方案

在处理范围继承的复杂性时,这个小点非常重要.

egghead.io 视频The Dot" 有一个非常好的概述,这也是非常流行的堆栈溢出问题:AngularJS 中范围原型/原型继承的细微差别是什么?

我会在这里总结一下:

Angular.js 使用范围继承来允许子范围(例如子控制器)查看父范围的属性.因此,假设您有如下设置:

<input type="text" ng-model="foo"/><div ng-controller="ChildCtrl"><input type="text" ng-model="foo"/>

(在 JSFiddle 上一起玩)

首先,如果您启动应用程序,并在父级输入中输入,子级会更新以反映它.

但是,如果您编辑子作用域,与父作用域的连接现在已断开,两者不再同步.另一方面,如果您使用 ng-model="baz.bar",则链接将保留.

发生这种情况的原因是因为子作用域使用原型继承来查找值,所以只要它永远不会在子作用域上设置,那么它就会服从父作用域.但是,一旦设置,它就不再查找父级.

当您改用对象 (baz) 时,不会在子作用域上设置任何内容,并且继承仍然存在.

有关更深入的详细信息,请查看 StackOverflow 答案

In the video AngularJS MTV Meetup: Best Practices (2012/12/11), Miško explains "..if you use ng-model there has to be a dot somewhere. If you don't have a dot, you're doing it wrong.."

However, the very first example (The Basics) in the Angular.JS website seems to contradict it. What gives? Has Angular.JS changed since the MTV meetup that it's now more forgiving with ng-model?

解决方案

That little dot is very important when dealing with the complexities of scope inheritance.

The egghead.io video "The Dot" has a really good overview, as does this very popular stack overflow question: What are the nuances of scope prototypal / prototypical inheritance in AngularJS?

I'll try to summarize it here:

Angular.js uses scope inheriting to allow a child scope (such as a child controller) to see the properties of the parent scope. So, let's say you had a setup like:

<div ng-controller="ParentCtrl">
    <input type="text" ng-model="foo"/>
    <div ng-controller="ChildCtrl">
        <input type="text" ng-model="foo"/>
    </div>
</div>

(Play along on a JSFiddle)

At first, if you started the app, and typed into the parent input, the child would update to reflect it.

However, if you edit the child scope, the connection to the parent is now broken, and the two no longer sync up. On the other hand, if you use ng-model="baz.bar", then the link will remain.

The reason this happens is because the child scope uses prototypical inheritance to look up the value, so as long as it never gets set on the child, then it will defer to the parent scope. But, once it's set, it no longer looks up the parent.

When you use an object (baz) instead, nothing ever gets set on the child scope, and the inheritance remains.

For more in-depth details, check out the StackOverflow answer

这篇关于为什么 AngularJS 文档不在模型指令中使用点?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆