gpt4 book ai didi

javascript - AngularJs "controller as"语法 - 澄清?

转载 作者:IT王子 更新时间:2023-10-29 02:39:12 25 4
gpt4 key购买 nike

read about the new syntax来自 angularJS 关于 controller as xxx

The syntax InvoiceController as invoice tells Angular to instantiate the controller and save it in the variable invoice in the current scope.

可视化:

enter image description here

好的,所以我的 Controller 中不会有参数 $scope 并且 Controller 中的代码会更清晰。

但是

我将不得不在 View 中指定另一个别名

所以直到现在我可以做:

<input type="number" ng-model="qty"  />

....controller('InvoiceController', function($scope) {
// do something with $scope.qty <--notice

现在我可以做:

 <input type="number" ng-model="invoic.qty"  /> <-- notice 

....controller('InvoiceController', function() {
// do something with this.qty <--notice

问题

这样做的目的是什么?从一个地方移除并添加到另一个地方?

我会很高兴看到我错过了什么。

最佳答案

关于它有几件事。

有些人不喜欢 $scope 语法(别问我为什么)。他们说他们可以只使用 this。这是目标之一。

弄清楚属性的来源也非常有用。

您可以嵌套 Controller ,当阅读 html 时,每个属性的位置都非常清楚。

您还可以避免一些点规则问题。

例如,有两个 Controller ,都具有相同的名称“name”,您可以这样做:

<body ng-controller="ParentCtrl">
<input ng-model="name" /> {{name}}

<div ng-controller="ChildCtrl">
<input ng-model="name" /> {{name}} - {{$parent.name}}
</div>
</body>

您可以同时修改父项和子项,这没问题。但是您需要使用 $parent 来查看父级的名称,因为您在子 Controller 中隐藏了它。在大量 html 代码中,$parent 可能会有问题,您不知道该名称的来源。

使用 controller as 你可以:

<body ng-controller="ParentCtrl as parent">
<input ng-model="parent.name" /> {{parent.name}}

<div ng-controller="ChildCtrl as child">
<input ng-model="child.name" /> {{child.name}} - {{parent.name}}
</div>
</body>

同样的例子,但读起来更清晰。

关于javascript - AngularJs "controller as"语法 - 澄清?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21287794/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com