Reputation: 4716
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
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