Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What does 'var vm = this;' mean in angular controllers?

Tags:

angularjs

I was browsing some stuff on github and I saw inside controller.js, someone had put the following:

function ImageController ($scope, $timeout) {
   var vm = this;
}

What is this used for?

like image 710
Ram Mudaliar Avatar asked Nov 16 '15 16:11

Ram Mudaliar


People also ask

What does VM mean in angular?

Instead of the $scope variable provided by Angular we simply declare a vm variable (which stands for view model) and assign this to it (i.e. the instance of the controller function). All variables will now be assigned to the vm object instead of $scope.

What is controller in angular8?

AngularJS Controllers AngularJS applications are controlled by controllers. The ng-controller directive defines the application controller. A controller is a JavaScript Object, created by a standard JavaScript object constructor.

What are controllers used for in angular?

AngularJS application mainly relies on controllers to control the flow of data in the application. A controller is defined using ng-controller directive. A controller is a JavaScript object that contains attributes/properties, and functions.

What are nested controllers in angular?

Nested Controllers: AngularJS allows using nested controllers. It means that you have specified a controller in an HTML element which is a child of another HTML element using another controller.


2 Answers

The vm in this case means viewmodel.

It is a shortcut, so instead of writing this.someMethod() you can use vm.someMethod().

Very common when you use Controller As syntax, so you don´t use the $scope by "accident".

Also, the this keyword can be messy to use, since it may reference different things depending on where it is used.

like image 71
Fedaykin Avatar answered Oct 16 '22 08:10

Fedaykin


Why?: Helps avoid the temptation of using $scope methods inside a controller when it may otherwise be better to avoid them or move the method to a factory, and reference them from the controller.

you can check full John Papa Angular Style to learn deeper...

like image 22
Poyraz Yilmaz Avatar answered Oct 16 '22 08:10

Poyraz Yilmaz