The 'controller as' technique for AngularJS was described by John Papa as:
myApp.controller("MainCtrl", [
function () {
var vm = this; // convention - ViewModel
vm.person = { name: "Bob" };
return vm;
}]);
What is the purpose of the return vm;
line? The code works without it.
When Angular is creating your controller, it will use the new
keyword on the function you passed in. Thus, it will construct a new object using the constructor you passed in. Returning objects from your constructor function will cause the Angular to use that instance of your newly created object as with any other use of a JavaScript constructor.
There are some details about the constructing process (see this SO answer) to keep in mind:
this
it can be omitted, as this
will be used by default.null
(essentially anything that's null
or not an Object
, as described in the SO answer linked to earlier), this
will be utilized as well.Saying this
will be used in 1 & 2 is a trivial oversimplification. Again, see this answer regarding construction for specific details.
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