[javascript] Angularjs: Get element in controller

I am new to angularjs, I know that $scope represent a connection between the controller and the view, But is there a way besides looking for class="ng-scope" to get the scope element, I mean something like that:

function someControllerFunc($scope){
       $scope.element;
}

I know that same controller can be assigned to multiple scopes, So maybe it is not possible.

This question is related to javascript angularjs

The answer is


$element is one of four locals that $compileProvider gives to $controllerProvider which then gets given to $injector. The injector injects locals in your controller function only if asked.

The four locals are:

  • $scope
  • $element
  • $attrs
  • $transclude

The official documentation: AngularJS $compile Service API Reference - controller

The source code from Github angular.js/compile.js:

 function setupControllers($element, attrs, transcludeFn, controllerDirectives, isolateScope, scope) {
    var elementControllers = createMap();
    for (var controllerKey in controllerDirectives) {
      var directive = controllerDirectives[controllerKey];
      var locals = {
        $scope: directive === newIsolateScopeDirective || directive.$$isolateScope ? isolateScope : scope,
        $element: $element,
        $attrs: attrs,
        $transclude: transcludeFn
      };

      var controller = directive.controller;
      if (controller == '@') {
        controller = attrs[directive.name];
      }

      var controllerInstance = $controller(controller, locals, true, directive.controllerAs);

Create custom directive

masterApp.directive('ngRenderCallback', function() {
    return {
        restrict: "A",
        link: function ($scope, element, attrs) {
            setTimeout(function(){ 
                $scope[attrs.ngEl] = element[0];
                $scope.$eval(attrs.ngRenderCallback);               
            }, 30);
        }
    }
});

code for html template

<div ng-render-callback="fnRenderCarousel('carouselA')" ng-el="carouselA"></div>

function in controller

$scope.fnRenderCarousel = function(elName){
    $($scope[elName]).carousel();
}

I dont know what do you exactly mean but hope it help you.
by this directive you can access the DOM element inside controller
this is sample that help you to focus element inside controller

.directive('scopeElement', function () {
    return {
        restrict:"A", // E-Element A-Attribute C-Class M-Comments
        replace: false,
        link: function($scope, elem, attrs) {
            $scope[attrs.scopeElement] = elem[0];
        }
    };
})

now, inside HTML

<input scope-element="txtMessage" >

then, inside controller :

.controller('messageController', ['$scope', function ($scope) {
    $scope.txtMessage.focus();
}])