Creating AngularJS Controllers in ES6

I am currently in the process of migrating one of our apps (previous post) to ES6 and here are a few ways I learnt to create AngularJS controllers in ES6.

Inject a $scope into a function and then tack on properties and methods like I always did (before Controller As) but this time with some ES6 goodness:

export let ScopeInjectedCtrl = function($scope) {
  $scope.msg1 = "Hi from ScopeInjectedCtrl";

  $scope.updateMsg2 = function() {
    $scope.msg2 = "Hello! from ScopeInjectedCtrl";
  }
}

Inject a $scope into an anonymous function and tack on properties and methods. This approach is just a shorthand for the above. Being an anonymous function, this has to be declared right where the controller is created.

app.controller('ScopeInjectedAnonymousCtrl', $scope => {
    $scope.msg1 = "Hi from ScopeInjectedAnonymousCtrl";

    $scope.updateMsg2 = function() {
      $scope.msg2 = "Hello! from ScopeInjectedAnonymousCtrl";
    };
  });

And finally, my favorite – pure ES6 classes with methods, getters and setters. This pairs very well with Controller as syntax.

export class PureClassCtrl {

  constructor() {
    this._msg1 = "Hi from PureClassCtrl";
    this._msg2 = "";
  }
  get msg1() {
    return this._msg1;
  }

  get msg2() {
    return this._msg2;
  }

  updateMsg2() {
    this._msg2 = "Hello! from PureClassCtrl";
  }
}

The pure class style feels very clean (to me personally), just like the current Controller As does. However, remember that the same rules apply as today’s Controller As syntax when it comes to adding a $watch or dealing with events using $on, ‘$emit’ or $broadcast – the $scope will need to be injected – so method 1 or 2 are going to be better options (unless there is a better way of handling it with class that I am not aware of).

A plunk that shows the above mentioned ways of creating controller here

Advertisements

3 thoughts on “Creating AngularJS Controllers in ES6

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s