guy mograbi
guy mograbi

Reputation: 28638

How to get root element for scope in angular?

I usually need the element's scope which is something like $(element).scope() or angular.element(..).scope()

But now I have the opposite problem - I have a scope, and I need to find which element generated it.

How can I find out from the developers' console which element it is?

Why do I need this?

I am working on someone else's code, fixing a bug.

I am still trying to figure out some stuff, but some of the code is quite hard to follow. Very generic and a lot of copy-paste, so searches don't always help.

There's a lot of ng-includes and directives that use the parent scope.

There's a view calling a service somehow - it is unclear how yet..

I do have a reference to a scope, which is different from the one in the view that triggers the function.

So if I find the element from which that scope came from, it could sort out the relation between them etc.. At least give me some lead.

Obviously some refactoring and best practices are required in the future, but I have to focus on this bug first.

Upvotes: 0

Views: 690

Answers (1)

Chas Brown
Chas Brown

Reputation: 396

I know of nothing 'out-of-the-box', but every $scope variable has a unique $id property; and in addition, every element that has a $scope gets marked with the 'ng-scope' class. So something along the lines of the following VERY UGLY METHOD! may help (I'm assuming you have jQuery; otherwise substitute angular's jqueryLite methods):

function findById(id) {
    var els = $('.ng-scope'); 
    for (var i=0; i<els.length; i++) {
        if ($(els[i]).scope().$id===id) {
            return els[i];
        }
    } 
    return null;
}

And if this is actually helpful, then I feel your debugging pain.

Upvotes: 1

Related Questions