0

I have a scenario where I have a parent controller and multiple child controllers that can exist on a page based on some business logic.

The controllers are specified on elements in the dom, and the child controllers are on elements that are controlled by ngSwitch.

e.g. Here is a rather contrived example of what I'm doing.

Parent Controller

app.controller('parentCntrl',function($scope){
 $scope.model = {};
 $scope.model.foo = 42;
 //More stuff
});

Child Controller

app.controller('childCntrl',function($scope){
 $scope.model.bar = 24;
 $scope.myFunction = function() {
 return "The answer is: " + $scope.model.foo;
 };
});

As you can see, the child controller depends on the $scope.model object to already exist and relies on traversing up the prototype chain to find it.

Is there a way to specify on the child controllers that they require a particular parent controller in order for them to work? My child controllers need to look at properties on the parent scope. Or should I be following some sort of other best practice?

Thanks

asked Mar 27, 2014 at 23:10
2
  • if we are talking about model while defining controllers(parent, child) on DOM level that's fine. but when the point is about code, for such thing you have to use shared factory,or service and pass it as dependency for both controller. keep there all shared data. and you will be OK. Commented Mar 27, 2014 at 23:19
  • I think somebody answered already.. but services are the best practice for sharing data between controllers. Commented Mar 27, 2014 at 23:25

1 Answer 1

1

The best way to do it is to relay on an external to both controllers service, which can allow you to communicate effectively between those controllers, and where your $scope.model can be kept nicely and safely.

For example:

yourapp.factory('myextprovider', function(){
 // Your code where to updare the $scope.model
})
yourapp.controller('parentctrl', function(myextprovider, $scope){
 $scope.model = myextprovider.somemethods
})
yourapp.controller('childctrl', function(myextprovider, $scope){
 $scope.model = myextprovider.othermethods
})

Another way is, depending on the case to use directives, where you can effectively require an external parent directive for the child one, and share the scopes.

I hope I give you an idea of how to proceed in cases like them.

answered Mar 27, 2014 at 23:19

Comments

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

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.