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?
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.
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.
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.
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.
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.
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...
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With