8

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.

TrueWill
  • 25,132
  • 10
  • 101
  • 150
  • From my POV vm is returned to produce a [chained method](http://stackoverflow.com/q/7570635/1959948) – Dalorzo May 26 '14 at 21:17
  • 1
    I don't think it has anything to do with chained methods (but I've been wrong before) and I don't see how it changes the default behaviour (which is to return `this`). – gkalpak May 26 '14 at 21:38
  • 1
    To quote the author of the article: "That’s just my convention" – a better oliver May 27 '14 at 12:04

1 Answers1

6

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:

  1. When the returned object is the same as this it can be omitted, as this will be used by default.
  2. If returning some primitive type or 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.
  3. If returning an instance, the reference to this instance will be returned.

Saying this will be used in 1 & 2 is a trivial oversimplification. Again, see this answer regarding construction for specific details.

ruffin
  • 16,507
  • 9
  • 88
  • 138
Luke
  • 8,235
  • 3
  • 22
  • 36
  • 5
    I agree, but I don't see an explicit answer to the actual question. – gkalpak May 26 '14 at 21:36
  • 1
    the answer is the content I have written in point 1. As vm is the same as this, it can be omitted because it will be returned anyways... – Luke Aug 30 '16 at 14:37