AngularJS - An Alternative Approach to Controllers

The initial setup:

<div ng-app="phoneApp">
  <div ng-controller="AppCtrl">
    <div class="button" ng-click="sayHi()">Click me!</div>
  </div>
</div>
var app = angular.module('phoneApp', []);

app.controller("AppCtrl", function ($scope) {
  $scope.sayHi = function () {
    alert("hi");
  };
});

In this basic setup, it is trivial to derive that the sayHi() method is bound to the mouseclick event, but merely examining the view doesn’t yield any information about where the sayHi() method lives or how the element is provided access to that method.

Instead of declaring the method on the controller scope, we can instead provide a kind of wrapping for the method by declaring the method on ‘this’, and returning the controller as an attribute on the scope, as follows:

app.controller("AppCtrl", function ($scope) {
  this.sayHi = function () {
    alert("hi");
  };

  return $scope.AppCtrl = this;
});

In doing this, it is now possible to invoke methods defined on ‘this’ by calling them on the controller attribute in the scope:

    <div class="button" ng-click="AppCtrl.sayHi()">Click me!</div>

Now, in the view, we can assess where the method is defined immediately without altering functionality in any way.