1

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?

2
  • 4
    reusable components should go in services/factory and not in controller. Commented Oct 25, 2014 at 18:01
  • Could you elaborate further, please? Commented Oct 25, 2014 at 18:01

1 Answer 1

4

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();
    }    
}​
Sign up to request clarification or add additional context in comments.

3 Comments

What about working with $scope.member inside the service? Will I have to pass it as a parameter or can I reuse whatever $scope is inside the Controller?
pass it as a parameter, but not $scope, pass the parameter you are working with...
dont pass $scope, pass the parameter on which the logic depends.. passing $scope is a code smell

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.