membersound
membersound

Reputation: 86935

How to inherit and override controller methods in angularjs (java pendent)?

I have a simple controller, and would like to introduce a very similar additional controller, but without copying too much code.

angular.module('test').controller('parentController', parentController);
parentController.$inject = ['$scope', '$location', 'someService'];

function myController($scope, $location, someService) {
    var params = getQueryString();
    var rsp = executeQuery(params);

    processResponse(rsp);

    function getQueryString() {
        return "?param=1&someparam=2";
    }

    function executeQuery(params) {
        ...
    }

    function processResponse(rsp) {
           //process rsp, convert some parts, and populate model properties, like
           $scope.model.prop1 = rsp.data.prop1;
    }
};

Now I'd like to create a controller that is 90% equal to the code of the parentController. The main differences:

Coming from java, I'd solve this for example with inheritance and overridden methods, like:

public cass ParentClass {
    String getQueryString() {
        return "?param=1&someparam=2";
    }
}

public class CustomClass extends ParentClass {
    @Override
    String getQueryString() {
        return "?customparam=1";
    }

    @Override
    void processResponse(rsp) {
         super.processResponse(rsp);
         //read "rsp.paramX" additionally
    }
}

But how can I achieve similar with angularjs?

Upvotes: 0

Views: 549

Answers (2)

Abdel Raoof Olakara
Abdel Raoof Olakara

Reputation: 19353

you could use the $injector to bring in parent controller properties to the child controller.. your child controller will be something like this:

function childController($injector, $scope, someService) {
    // override the method
    this.getQueryString() {
        // new query will be returned
    }

    $injector.invoke(myController, this, {
          $scope: $scope,
          someService: someService
     });
};

You can find details of this approach here: https://www.exratione.com/2013/10/two-approaches-to-angularjs-controller-inheritance/

Upvotes: 0

Tomer
Tomer

Reputation: 17940

Lets assume you have this structure:

<div ng-controller="parentCtrl">
   ...
   <div ng-controller="childCtrl"></div>
</div> 

Since the child controller is under the parent controller scope, it can access all methods/varialbe of the parent's controller, as long as they are defined on the $scope of the parent controller (i.e. $scope.someVar).

UPDATE

If the 2 controllers don't have a parent/child relationship, you'll need to use a service, where you will put the shared logic, and then you can define an init function on the service that starts the sequence.

So in you're controllers all you have to do is call myService.init() (and maybe pass some parameters)

Upvotes: 1

Related Questions