javascript - AngularJS controller return value - Stack Overflow

The 'controller as' technique for AngularJS was described by John Papa as:myApp.controller(&q

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.

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.

Share Improve this question asked May 26, 2014 at 21:05 TrueWillTrueWill 25.6k10 gold badges103 silver badges155 bronze badges 3
  • From my POV vm is returned to produce a chained method – Dalorzo Commented May 26, 2014 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 Commented May 26, 2014 at 21:38
  • 1 To quote the author of the article: "That’s just my convention" – a better oliver Commented May 27, 2014 at 12:04
Add a ment  | 

1 Answer 1

Reset to default 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.

发布者:admin,转转请注明出处:http://www.yc00.com/questions/1742412814a4439157.html

相关推荐

  • javascript - AngularJS controller return value - Stack Overflow

    The 'controller as' technique for AngularJS was described by John Papa as:myApp.controller(&q

    2天前
    30

发表回复

评论列表(0条)

  • 暂无评论

联系我们

400-800-8888

在线咨询: QQ交谈

邮件:admin@example.com

工作时间:周一至周五,9:30-18:30,节假日休息

关注微信