How can I specify that a controller should be a child of another controller in the JavaScript rather than the HTML?
For example, on pageCtrl, I have a method called modalBlog that opens a blog post in a modal (Angular-UI.) I would like to specify the controller to be BlogCtrl, the same as I'm using on the actual blog page. I'd like to pass it input though (i.e. the blog post ID.) Is there a way to do something like:
$scope.modalBlog = function(postId) {
var modalInstance = $modal.open({
templateUrl: '...',
controller: function(..) {
// Set some variables
// ...
// set BlogController as a child controller to this
}
};
Right now, by setting controller: 'BlogCtrl', it's parent is the route scope (from ui.router's $state), or visually:
So, the hierarchy is:
+-Root
|---- PageCtrl
|---- BlogCtrl
But when I specify an anonymous function, I get:
+-Root
|--+- PageCtrl
+--+- <Anonymous function>
Is there a way (in just JavaScript) to achieve this hierarchy?
+-Root
|--+- PageCtrl
+--+- <Anonymous function>
+--+- BlogCtrl
The motivation is to re-use the code in the BlogCtrl to download the post.
I suppose completely alternative methods to achieve the same functional/end-of-the-day goals would be to:
- create a
BlogServicewhich both this anonymous function and theBlogCtrlcould use, - or even load a view that has a tag that specifies the
BlogCtrlas a controller
And while I think these would be better methods in this particular case, I'm curious if there is a way to specify the hierarchical structure of scopes in AngularJS via JavaScript (as opposed to setting it in the HTML which is rather straight forward.)
Update:
I think the second option I gave is best (I had only thought of it while writing this question) way to implement the functionality I required.
So, my function is:
$scope.modalBlog = function(postId) {
var modalInstance = $modal.open({
templateUrl: '...',
controller: function(..) {
// Set some variables and functions
}
};
And instead of pointing at views/blog.html, I point to views/blog-modal.html, whose top tag is:
<section ng-controller="BlogCtrl">
Which gives me the designed structure, where the controller function above is the parent of BlogCtrl.
This leads to the view being somewhat duplicated, as I'm not sure how to conditionally set the controller (e.g. ng-controller="modal?BlogCtrl:not BlogCtrl"), but it's not too bad. I'd still be curious on how to set the structure in purely Javascript though.