SamSamet SamSamet - 4 months ago 6x
AngularJS Question

Access Angular Controller Defined Element

Is there a way to access the div which is in the controller div or the controller defined div without defining them with and class or id JUST using the $scope.

<div ng-controller="gridController">
<div></div> // < -- I want to access this element

To be a bit more specific does angular saves and gives access to the element DOM info which the ng-controller was called ?


You can access the element the controller is defined on by injecting the angular variable $element into your controller

  .controller('SomeCtrl',['$scope', '$element', function($scope, $element) {

  $scope.buttonClick = function () {
    $element.find('div').css('background-color', '#f00');

If jQuery is included in your project, $element will be a jQuery object of the element your controller is defined on (the outer div in your example). You can use standard jQuery directives to access its sub elements. Accessing an unnamed child div would require you to know its position, or use some other criteria to target it.

If jQuery is not installed, angular includes jqlite which is a subset of jQuery allowing you to use most jQuery selectors to target elements, but lacking most of the other manipulation features.

However, it is generally considered bad practice to access, and especially manipulate the DOM from within a controller. Because of the way jQuery binds variables to html, if you make changes to the DOM from certain functions, angular may not pick these changes up and overwrite them when it next does a binding cycle. To avoid this, you should do most of your DOM manipulation from inside an angular directive. Sometimes however, its just easier to do it from the controller... If you are going to do this, you should learn about $apply and $digest.