简体   繁体   中英

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?

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> 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM