0

what I am trying to do here is to create a similar controller but not exactly the same, a few aspects of the controller need to be override. if it is the case in java then I probably just subclass and override the method I needed. but here in AngularJs not sure what is the best way to achieve this.

I really don't want to duplicate the code. refactoring the existing code is preferred but due to timeline issue have to delay that a bit.

so what is the correspondence of subclass and override in AngularJS

zinking
  • 5,561
  • 5
  • 49
  • 81

2 Answers2

0

You can create a service and inherit its behaviour in any controller just by injecting it.

app.service("reusableCode", function() {

    var reusableCode = {};

    reusableCode.commonMethod = function() {
        alert('Hello, World!');
    };

    return reusableCode;
});

Then in your controller that you want to extend from the above reusableCode service:

app.controller('MainCtrl', function($scope, reusableCode) {

    angular.extend($scope, reusableCode);

    // now you can access all the properties of reusableCode in this $scope
    $scope.commonMethod()

});

DEMO PLUNKER: http://plnkr.co/edit/EQtj6I0X08xprE8D0n5b?p=preview

Raghavendra
  • 5,281
  • 4
  • 36
  • 51
0

When you really need controller inheritance (including $scope), I think your question is best answered here: What's the recommended way to extend AngularJS controllers?

Community
  • 1
  • 1
hupfis
  • 128
  • 7