How to handle $ctrl. in AngularJS?

Gabriel W. picture Gabriel W. · Oct 10, 2017 · Viewed 17.3k times · Source

I have a Methode from an API. It returns a promise which resolves to an $ctrl(?) object. This objects should contain a measurement and will be updated whenever it receive a new data.

getMeasurements.latest(filter)     //only a object to filter through all measurements
    .then(function (latestMeasurement) {
        $ctrl.latestMeasurement = latestMeasurement;
});

My problem is that I don't know how to work with this data or display it in my html file. How does $ctrl work?

Here the documentation of the API

Answer

Amir Suhail picture Amir Suhail · Oct 11, 2017

$ctrl is the view model object in your controller. This $ctrl is a name you choose (vm is another most common name), if you check your code you can see the definition as $ctrl = this;, so basically its the this keyword of the controller function.

So now if you are using $ctrl.latestMeasurement = 'someValue', then its like you are adding a property latestMeasurement to controller function.

Now how to use it in HTML?

To access the latestMeasurement property in HTML your code must have <h1>{{$ctrl.latestMeasurement}}</h1> (H1 tag is just an example.)

Here $ctrl is different from what I explained above on controller part. Here $ctrl is the value used for controllerAs property of the controller. But $ctrl is the default value of the controllerAs property, so your code may not have the controllerAs property defined, so Angular will take default value $ctrl in HTML.

This is where most people gets confused. So let me explain,

Assume in your new controller you have declared your this keyword to variable vm, and you set your controllerAs property to myCtrl, i.e;

controllerAs: 'myCtrl' while defining controller properties.

var vm = this; in your controller function.

In this case in js you have to use vm for setting values, and in HTML you have to use myCtrl. For example,

in JS controller function vm.test = 'Hello world';

in HTML <span ng-bind="myCtrl.test"></span>

The result Hello world will be displayed in your page.

Why $ctrl and not $scope?

The view model object model concept is introduced in AngularJS 1.5, it is actually part of migrating to Angular 2 where $scope no longer exsist. So in 1.5 they introduced new approch but did not removed $scope completely.

Hope the answer helped.

For basic Javascript concepts you can see http://javascriptissexy.com/16-javascript-concepts-you-must-know-well/

For more detailed AngularJS $ctrl concept you can see https://johnpapa.net/angularjss-controller-as-and-the-vm-variable/