AngularJS $scope vs Controller Inheritance

I wrote this article because I was confused about what 'Controller Inheritance' actually was.  First let's look at $scope inheritance.

Example1 - $scope inheritance

Note) The ChildCtrl is nested within MainCtrl in the html.  AngularJS responds to this by ensuring that the $scope passed to ChildCtrl inherits properties and methods from the $scope passed to and decorated by MainCtrl.

Also Note) AngularJS does not introduce any inheritance (prototypical or otherwise) between the actual controllers themselves.

If you want your controllers to actually inherit properties and/or methods (that are not exposed on the $scope), then you can do this perfectly well by employing standard, non-AngularJS javascript prototypical inheritance between the controllers.

Example 2 - Rolling your own Controller Inheritance

   Note) I changed for the way I create my controllers from an anonymous approach utilising the controller method to a named function approach.  This is necessary because you need the named function in order to access and extend its prototype.

Also Note)  I forced the ChildCtrl to inherit from the main MainCtrl using prototypical inheritance. I was then able to do is extend the $scope of the ChildCtrl with a method that made use of the inherited method.

comments powered by Disqus