Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Angular Get Controller from Element

Is there a way to find the controller for an element through Chrome's console? I can get a reference to the component by selecting the element in the Elements Panel and using

var c = angular.element($0);

c has a controller property (looks like a constructor), but I'm not sure what to do with this. Is there any way to find the controller's name from here?

like image 948
reergymerej Avatar asked Feb 24 '14 17:02

reergymerej


People also ask

How do you get the $scope in console?

scope(); $('#elementId'). scope(). $apply(); Another easy way to access a DOM element from the console (as jm mentioned) is to click on it in the 'elements' tab, and it automatically gets stored as $0 .

What is angular element this scope ()?

The angular. element() Function in AngularJS is used to initialize DOM element or HTML string as an jQuery element. If jQuery is available angular. element can be either used as an alias for jQuery function or it can be used as a function to wrap the element or string in Angular's jqlite.

What is jqLite?

jqLite is a tiny, API-compatible subset of jQuery that allows AngularJS to manipulate the DOM in a cross-browser compatible way. jqLite implements only the most commonly needed functionality with the goal of having a very small footprint. To use jQuery , simply ensure it is loaded before the angular.

What is $scope in AngularJS?

The $scope in an AngularJS is a built-in object, which contains application data and methods. You can create properties to a $scope object inside a controller function and assign a value or function to it. The $scope is glue between a controller and view (HTML).


Video Answer


2 Answers

If you do angular.element($0).scope() or just $scope(if you installed Batarang Chrome extension), you should be able to get access to selected element's scope's functions and properties. This should also include any functions/attributes that a controller has exposed on the scope.

There is no way to get the controller's name, though.

like image 153
Vlad Gurovich Avatar answered Sep 29 '22 06:09

Vlad Gurovich


Assuming you're not using anonymous functions for a controller you can use something like this:

angular.element(element).controller().constructor.name

codepen - http://codepen.io/jusopi/pen/jWYWzv?editors=101

At least as of Angular 1.2.27, per their documentation you can do this. Look under the JQLite Extras Method section - https://docs.angularjs.org/api/ng/function/angular.element

like image 14
jusopi Avatar answered Sep 29 '22 05:09

jusopi