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
1 Answer 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.
shared factory,or service
and pass itas dependency
for both controller.keep there all shared data
. and you will be OK.