AngularJs “controller as” syntax - clarification?

后端 未结 6 570
面向向阳花
面向向阳花 2020-11-22 14:08

I read about the new syntax from angularJS regarding controller as xxx

The syntax InvoiceController as invoice tells Angular

6条回答
  •  北海茫月
    2020-11-22 14:39

    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:

    
         {{name}}
    
        
    {{name}} - {{$parent.name}}

    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:

    
         {{parent.name}}
    
        
    {{child.name}} - {{parent.name}}

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

    • $scope plunker
    • controller as plunker

提交回复
热议问题