Reputation: 13862
I want to access or manipulate a scope's parent's parent without getting too too complicated. The controller as fashion allows for naming the parent controller as such: this.applicationCtrl.something
given applicationCtrl > parent1Ctrl > child1Ctrl - siblingOfChild1Ctrl
To give you a better example, I have an applicationCtrl on the <body>
tag, I have a side panel with sidePanelCtrl
and the content with contentCtrl
with a nested contentChildCtrl
With the controller as model, I can call or change things on the sidePanelCtrl
by calling this.sidePanelCtrl
, can I do the same if I just want to use $scope
method?
This is specifically for the contentChildCtrl
where I do not want to write $scope.$parent.$parent
which still will only get me to the applicationCtrl
and not the sidePanelCtrl
Upvotes: 1
Views: 435
Reputation: 964
If you don't know the nesting level of the parent scope, or don't want to type $scope.$parent.$parent
etc you can attach something like this to a service:
angular.module('app').service('inherit', function () {
var inherit = function(scope, item)
if (!scope) return;
if (scope[item]) return scope[item];
return inherit(scope.$parent, item);
}
return inherit;
}
If your namespacing isn't great then it might not help much, but if you're looking to modify, say, the sidebar contents from a grandchild scope, you could call var sidebarNav = inherit($scope, 'sidebarNav');
in the grandchild controller.
Edit - Better to put this in a service than on $rootScope
as the comment below has mentioned
Edit: updated to use service
Upvotes: 1