0

In Angular controllers are build with new keyword. If we attach properties and functions to this inside of controller, we can get new object calling the constructor with new keyword. So in the end it seems that constructors are classes. Only problem is that javascript don't have classes so we are just really pretending that controllers are classes.

My question is, is there any drawback if I define controllers so they return a object (like factory do) because when calling new with function that already returns a object we get the object function returns. This way I can forget about this and new and everything seems more elegant.

Example:

angular
    .module('myapp', [])
    .controller('testController', function() {
      var vm = this;
      vm.title = 'testController';
    });

without this

angular
    .module('myapp', [])
    .controller('testController', function() {
      var vm = {};
      vm.title = 'testController';
      return vm;
    });
Sim
  • 375
  • 2
  • 12
  • Yes, You can do that, but the problem is angular practices suggest to use one-view-one-controller. So in this case if you are having controller as a factory/service or whatever, you can't share data between controllers. Controllers have their own purpose(to control data flow) read more here: http://stackoverflow.com/questions/15666048/angularjs-service-vs-provider-vs-factory – Vishal Rajole Dec 11 '15 at 09:06
  • What do you think by not being able to share data between controller? This is almost the same as using the $scope syntax. – Sim Dec 11 '15 at 09:10

0 Answers0