Base Controller with AngularJS

1 בינואר 2015

There are two ways writing controllers in AngularJS Function based Class based For some reason, the first method is more popular (probably, because Angular's tutorials are written that way) (function (angular) {     angular.module("MyApp").controller("HomeCtrl", function ($scope) {         $scope.sayHello = function () {             alert("Hello");         }     }); })(angular); And the corresponding template <div ng-controller="HomeCtrl">     <button ng-click="sayHello()">Say Hello</button> </div> The other method is more elegant. You write the controller just as any other JavaScript class (function (angular) {     function HomeCtrl() {     }     HomeCtrl.prototype.sayHello = function () {         alert("Hello");     }     angular.module("MyApp").controller("HomeCtrl", HomeCtrl); })(angular); However, Angular does not support this style out of the box. You need to update the template <div ng-controller="HomeCtrl as ctrl">      <button ng-click="ctrl.sayHello()">Say Hello</button> </div> From my POV the big advantage using the later implementation is that it allows you to use a base controller class var MyApp = MyApp || {}; MyApp.BaseCtrl = (function () {     function BaseCtrl($scope) {         var me = this;         me.$scope = $scope;         me.$scope.$on("$destroy", function () {             me.onDispose();         });     }     BaseCtrl.prototype.onDispose = function () {         var me = this;         console.log(me.name + ".dtor");     }     return BaseCtrl; })(); The BaseCtrl is a great place to store common methods required by all controllers. In my sample above I register to...