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

2
  • 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 = []; Commented Oct 22, 2018 at 9:54
  • There is a similar question here about the controllerAs syntax: stackoverflow.com/q/40952006/5640649 Commented Oct 22, 2018 at 14:42

1 Answer 1

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.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.