4

In example $ctrl is used on view

<b>Heroes</b><br>
<hero-detail ng-repeat="hero in $ctrl.list" 
             hero="hero" 
             on-delete="$ctrl.deleteHero(hero)" 
             on-update="$ctrl.updateHero(hero, prop, value)">
</hero-detail>

When to use $ctrl and when to use $scope for interacting with view?

https://docs.angularjs.org/guide/component

Aleksey Solovey
  • 4,153
  • 3
  • 15
  • 34
  • it's *controllerAs* syntax, e.g. `ng-controller="myCltr as $ctrl"`. This allows you to bind data to `this` instead of `$scope`, e.g. `var vm = this; vm.list = [];` – Aleksey Solovey Oct 22 '18 at 09:54
  • There is a similar question here about the _controllerAs_ syntax: https://stackoverflow.com/q/40952006/5640649 – lealceldeiro Oct 22 '18 at 14:42

1 Answers1

5

In views, you can bind an alias to your controller to make it easy to reference $scope variables.

This is useful when you nest controllers and you don't want to reference something from a different controller. since $scope follows a hierarchical data structure.

So in order to scope your controller you can use this syntax.

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

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

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

this makes it easy to reference the scope variables.

<b>Heroes</b><br>
<hero-detail ng-repeat="hero in $ctrl.list" 
             hero="hero" 
             on-delete="$ctrl.deleteHero(hero)" 
             on-update="$ctrl.updateHero(hero, prop, value)">
</hero-detail>

After Angulajs 1.5, if you are using components, the default alias is $ctrl and of course you can override it.

ruffin
  • 16,507
  • 9
  • 88
  • 138
hannad rehman
  • 4,133
  • 3
  • 33
  • 55