javascript - 我们什么时候使用 $scope 什么时候在 AngularJS 中使用 var ?

标签 javascript angularjs angularjs-scope

使用 var 比使用 $scope 更好吗?在函数内部的 AngularJS 变量中?

我提出这个问题的原因并不像看起来那么简单。我最近读到有关 $watch、$digest、$apply 的内容。虽然我没有完全理解,但我明白 $digest 是循环工作的。 这篇文章解释得很好。

How do I use $scope.$watch and $scope.$apply in AngularJS?

因此,如果您在 Controller 中定义了 $scope.myVar,您就是在明确告诉 Angular 监视 myVar 上的更改。此事件不会减慢整个系统的速度吗?

最佳答案

简短回答:是的,最好将任何纯粹在 Controller 内部的变量声明为 javascript 变量(“var”),而不是将其添加到 Angular 范围。

Angular 作用域对象提供了许多不错的特性,允许它们充当模型- View -*(MV*) 架构中的模型(例如 data binding )。或者换一种说法,如 Angular guide to scopes说“范围是应用程序 Controller 和 View 之间的粘合剂”。

最好只将您需要的对象放在您的模型中,您需要绑定(bind)到 DOM 和您的 Controller /服务/...,因为这些功能确实会以性能成本为代价,正如您所指出的出去。如果您的范围被实际上不属于您的模型的变量“困惑”,它也可能会让阅读您的代码的其他人感到困惑。

这是来自 Angular scope docs 的范围的具体功能:

Scopes provide APIs ($watch) to observe model mutations.

Scopes provide APIs ($apply) to propagate any model changes through the system into the view from outside of the "Angular realm" (controllers, services, Angular event handlers).

Scopes can be nested to limit access to the properties of application components while providing access to shared model properties. Nested scopes are either "child scopes" or "isolate scopes". A "child scope" (prototypically) inherits properties from its parent scope. An "isolate scope" does not. See isolated scopes for more information.

Scopes provide context against which expressions are evaluated. For example {{username}} expression is meaningless, unless it is evaluated against a specific scope which defines the username property.

关于javascript - 我们什么时候使用 $scope 什么时候在 AngularJS 中使用 var ?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20774898/

相关文章:

javascript - "Object doesn' t 支持属性或方法 'push' "

AngularJS 结合使用两个具有共享范围的自定义指令

javascript - 给innerHTML赋值会不会异常?

javascript - 我怎样才能拥有一个表现得像 anchor 但又不是 anchor 的 HTML 元素?

javascript - 如何在没有按钮的情况下使用 jQuery UI 图标?

angularjs - 使用 AngularJS 引导 DateTimePicker : Passing directive ngModel value to controller

javascript - 为什么我无法获取 $sceProvider?

javascript - 将 'n' 项添加到本地存储(项从 json 文件获取)

javascript - AngularJS 绑定(bind)值更改时触发 ng-animate

javascript - 如果 angularjs 模板中的其他条件