doque
doque

Reputation: 2733

AngularJS inheritance - overwrite $scope.method()

I have a ParentController and a ChildController, which look like this:

ParentController:

app.controller("ParentController", function($scope) {

    // define preload method, expose to template
    $scope.preload = function() {
        console.log("parent");
    };

    // call preload function
    $scope.preload();
});

ChildController:

app.controller("ChildController", function($scope) {
    $controller("ParentController", {
        $scope: $scope,
    });

    // override preload method here
    $scope.preload = function() {
        console.log("child")
    };
});

As you can see, both Controllers define $scope.preload(), which is called upon instantiation in the ParentController. My goal is for ChildControllerto overwrite this method, so that when it is called, it logs a different string to the console.

Is this possible? If not, how else would I go about reusing all methods defined in ParentControllerin my ChildController?

Upvotes: 1

Views: 96

Answers (1)

harishr
harishr

Reputation: 18055

To share the data among independent controllers, Services can be used. Create a service with the data model that needs to be shared. Inject the service in the respective controllers.

In the following example, Service is used to store the variable x. The independent controllers will check the value of X whenever needed.

angular.module('myApp', [])
    .service('myService', function () {
        var x=5 ;
        return {
            increase : function() {
                x++;
            },
            getX : function() {
                return x;
            }
       };
    })

function ControllerA($scope, myService) {
    $scope.x = 1;
    $scope.incrementDataInService= function() {
        myService.increase();
    }
    $scope.syncDataWithService= function() {
        $scope.x = myService.getX();
    }        
}

function ControllerB($scope, myService) {
   $scope.x = 1;
    $scope.incrementDataInService= function() {
        myService.increase();            
    }
    $scope.syncDataWithService= function() {
        $scope.x = myService.getX();
    }    
}​

Upvotes: 4

Related Questions