Mihaly KR Mihaly KR - 6 months ago 32
Javascript Question

Angular.js best practice - extending controllers, overriding controller defaults

Here is a real-life Angular problem I can't wrap my head around.
I love Angular, but this issue is bugging me a lot right now.

What is the best practice to extend an existing controllers's functions, and use the extended controller on an other page of my application?
In other words: How to do controller inheritance in Angular?

Edited out - 23/09/2014, dont think the description of my original usecase helps the visitors to understand it better what I'm after here. I think it disctracts people from the real issue.


After half a year I think I understand completely what's going on. As it is pointed out in a comment to this post, the simplest answer is services.

In the most optimal case, all your scope variables are values gathered from a factory/service. Still, you might want to use the exact same controller with one extra function: $scope.someFunction(){}, and keep the rest. In this case, you do have a 'thin' controller logic, which is the desirable controller design - but may still end up a hundred or more lines of code. You don't want that being duplicated in an other controller, just because you need some extra controller logic (like $scope.someFunction() )

What do you do then?

The answer is this:

  1. Make sure that you did everything in order to solve the situation with factories
  2. if you are abolutely certain you did, go for the controller injection:

    .controller('childController', function ($scope, $controller) {
      'use strict';
      $controller('parentController', {$scope: $scope});

It's that simple. -- again, usually, things can be solved with factories..

Hope you find this useful ;)