1

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

Mohamed El Mahallawy
  • 13,024
  • 13
  • 52
  • 84

1 Answers1

1

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

Tom A
  • 944
  • 1
  • 6
  • 16
  • 1
    far better to recommend a service than even thinking about `$rootScope`. – charlietfl Sep 26 '14 at 18:52
  • 1
    Updated to show it as a service. Thanks charlieftl for the suggestion – Tom A Sep 26 '14 at 19:06
  • This is PERFECT! Except one last thing :) It doesnt solve the parent parent then sibling of that's scope. – Mohamed El Mahallawy Sep 26 '14 at 22:13
  • 1
    sibling scopes won't be inherited in the traditional way. i would recommend moving anything that must be shared into the parent controller. there are other ways to get things like events (`$broadcast`) but sibling scopes sharing data is usually a sign that the parent scope should instantiate the data instead – Tom A Sep 26 '14 at 22:35