OdeToCode IC Logo

Constructor Functions and Controllers in AngularJS

Wednesday, November 12, 2014

AngularJSThere are a few points in “AngularJS: The Bad Parts” I’d be happy to debate, but let’s focus on “Bad Idea #4”, talking about controller constructor functions:

That’s right, these constructors never create new instances. They are “applied” to a scope object.

Let’s use the following example. A simple controller that is setup to use controller as syntax from the view.

var module = angular.module("app", []);

var MainController = function() {
      
    this.message = "Hello";
    
    this.changeMessage = function() {
        this.message = "Bonjour!";
    };

    this.isMainController = function(object) {
        return object instanceof MainController;
    };

    this.isObject = function(object) {
        return object instanceof Object;
    };

};

module.controller("MainController", MainController);

If we place the following markup in a view:

<div>
    {{ main.isMainController(main) }}
    {{ main.isObject(main) }}
</div>

.. we’ll see the output true and true. The first true is a good indication that Angular does use the controller function as a constructor function, in other words, Angular invokes the function using the new keyword. In fact, we can even rewrite a controller using the everyday constructor function and prototype object approach of JavaScript, and everything just works.

var MainController = function() {
    this.message = "Hello";         
};

MainController.prototype = {
       
   changeMessage: function() {
       this.message = "Bonjour!";
   },

   isMainController: function(object) {
       return object instanceof MainController;
   },

   isObject: function(object) {
       return object instanceof Object;
   }

};

The above is actually a good example of why I like working with Angular. You can write plain, simple JavaScript objects using established conventions and terminology, then plug the objects into Angular to achieve a goal. There is no magic required or intrusions from the framework. You can even start writing controllers using ES 6 class syntax, but that’s a topic for a future post.