Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
222 views
in Technique[技术] by (71.8m points)

javascript - AngularJs "controller as" syntax - clarification?

I read about the new syntax from angularJS regarding 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.

Visualization :

enter image description here

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

But

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

Question

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.

Question&Answers:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

There are several things about it.

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.

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>

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.

With controller as you can do:

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


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...