Sunday, 12 November 2023

Getting a parent object by name in parent scope chain in AngularJs

I still work with some legacy solutions in AngularJs. I want to look in parent scope for a object which I know the name of, but it is some levels up by calling multiple $parent calls to get to the correct parent scope. Here is a small util method I wrote the other day to access a variable inside parent scopes by known name. Note : Select an element via F12 Developer tools and access its AngularJs scope. In the browser this is done by running in the console : angular.element($0).scope() Here is the helper method I wrote :


angular.element($0).scope().findParentObjByName = function($scope, objName) {
 var curScope = $scope;
var parentLevel = 0;
 //debugger
 while ((curScope = curScope.$parent) != null && !curScope.hasOwnProperty(objName) && parentLevel < 15){
     parentLevel++;
 }
 return curScope.hasOwnProperty(objName) ? curScope[objName] : null;  
}



We can then look for a property in the parent scopes like in this example :

angular.element($0).scope().findParentObjByName($scope, 'list')

This returns the object, if found and you can further work on it , for example in this particular example I used :

angular.element($0).scope().findParentObjByName($scope, 'list').listData[0]

No comments:

Post a Comment