AngularJS controller return value

The controller-like technique for AngularJS is 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 string return vm; ? The code works without it.

+6
source share
1 answer

When angular creates your controller, it will use the new keyword for the function you passed. Thus, it will build a new object using the constructor you submitted. Building objects using the constructor function will always return an instance of the newly created object.

There are some details about the build process (see this SO answer)

  • When the returned object matches this , it can be omitted since it will be returned by default.
  • If you return some primitive type, zero, or something else (described in another SO answer), this is also returned.
  • When an instance is returned, a link to that instance will be returned.
+6
source

Source: https://habr.com/ru/post/969878/


All Articles