Suppose I have a ponent like this
appponent('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 ponent more than once. How can I get the DOM just for the input in this ponent - either by restricting scope of inputbox
or using some other mechanism?
Suppose I have a ponent like this
app.ponent('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 ponent more than once. How can I get the DOM just for the input in this ponent - either by restricting scope of inputbox
or using some other mechanism?
- 2 controller: ['$element', function($element) { – Petr Averyanov Commented Mar 14, 2017 at 12:23
- stackoverflow./questions/25633139/… – Daniel Lizik Commented Mar 14, 2017 at 12:23
-
@PetrAveryanov so what would the
var inputbox
line look like with your suggestion? – Sideshow Bob Commented Mar 14, 2017 at 12:27 - @Daniel_L that seems to solve the opposite problem, triggering functions on focus not focus from a function? – Sideshow Bob Commented Mar 14, 2017 at 12:28
- To avoid the ID problem, remove the ID and tag it with a class, even just a dummy empty one, and select on that using querySelector or $element. Note that in Angular 1, where we didn't have template ref vars, this was the "remended" internal practice. In general I was told never to use IDs, use classes, even dummy ones. I hated doing it but it did solve the problem. – Tim Consolazio Commented Mar 14, 2017 at 12:33
1 Answer
Reset to default 4You could inject the element that triggered the ponent 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').ponent('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./ajax/libs/angularjs/1.5.5/angular.min.js"></script>
<div ng-app="myApp">
<test></test>
</div>
发布者:admin,转转请注明出处:http://www.yc00.com/questions/1744920594a4601109.html
评论列表(0条)