Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What are $ctrl in angularjs? when to use $ctrl vs $scope on view?

Tags:

angularjs

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

like image 700
abhijeet shende Avatar asked Nov 01 '25 17:11

abhijeet shende


1 Answers

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.

like image 174
hannad rehman Avatar answered Nov 04 '25 14:11

hannad rehman