AngularJs"控制器"语法 - 澄清? [英] AngularJs "controller as" syntax - clarification?

查看:230
本文介绍了AngularJs"控制器"语法 - 澄清?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

阅读从angularJS新的语法关于控制器XXX

语法 InvoiceController为发票告诉角度来实例
  控制器并保存在当前的可变发票
  范围。

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

可视化:

好了,我不会有参数 $范围在我的控制器和code将在控制干净多了。

Ok , so I wont have the parameter $scope in my controller and the code will be much cleaner in the controller.

但是

我将在视图中指定另一个别名

I will have to specify another alias in the view

所以,到现在为止我所能做的:

So Until now I could do :

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

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

而现在我能做的:

And now I can do :

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

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

什么是做它的目标是什么?从一个地方取出并添加到另一个地方?

What is the goal of doing it ? removing from one place and add to another place ?

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

I will be glad to see what am I missing.

推荐答案

有关于它的几件事情。

有些人不喜欢 $范围语法(不要问我为什么)。他们说,他们可以只使用这个。这是目标之一。

Some people don't like the $scope syntax (don't ask me why). They say that they could just use this. That was one of the goals.

这就很清楚,其中一个属性来自确实是有用的。

Making it clear where a property comes from is really useful too.

您可以嵌套控制器和读取HTML时,它是pretty不清楚的地方每个属性来了。

You can nest controllers and when reading the html it is pretty clear where every property comes.

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

You can also avoid some of the dot rule problems.

例如,有两个控制器,这两个名称相同的名称,你可以这样做:

For example, having two controllers, both with the same name 'name', You can do this:

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

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

您可以修改这两个父母和孩子,没问题的。但是,你需要使用 $父看到父母的名字,因为你在你的孩子的控制器阴影吧。在巨大的HTML code $父可能是有问题的,你不知道这个名字的由来。

You can modify both parent and child, no problem about that. But you need to use $parent to see the parent's name, because you shadowed it in your child controller. In massive html code $parent could be problematic, you don't know where that name comes from.

使用控制器你可以这样做:

<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>

同样的例子,但它是非常更加清晰易读。

Same example, but it is much much clearer to read.

  • $scope plunker
  • controller as plunker

这篇关于AngularJs&QUOT;控制器&QUOT;语法 - 澄清?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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