Sideshow Bob
Sideshow Bob

Reputation: 4716

Angular: get element within component

Suppose I have a component like this

app.component('test',{
    template: '<input type="text" id="inputbox"></input>',
    controller: function() {
        ctrl.focusInput = function(){
                var inputbox = document.getElementById("inputbox");
                inputbox.focus();
            }
        };
    }    
});

I would like to get the DOM element for the input so I can focus it whenever I want. However inputbox falls in global scope which will be a problem if I use this component more than once. How can I get the DOM just for the input in this component - either by restricting scope of inputbox or using some other mechanism?

Upvotes: 2

Views: 8416

Answers (1)

Gangadhar Jannu
Gangadhar Jannu

Reputation: 4454

You could inject the element that triggered the component to controller function like below:

Since $element is jqLite wrapped object, you can use jQuery DOM traversal methods like children and find to find the input element.

angular
  .module('myApp', []);
angular
  .module('myApp').component('test', {
    template: '<input type="text" id="inputbox"></input>',
    controller: function($scope, $element, $attrs) {
      var ctrl = this;
      ctrl.focusInput = function() {
        $timeout(function() {
          $element.find('input').focus();
        }, 0);
      };
    }
  });
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.5.5/angular.min.js"></script>

<div ng-app="myApp">
  <test></test>
</div>

Upvotes: 4

Related Questions