Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
How to set focus on a text input in a list with AngularJS and HTML5
To set focus on a text input in a list with AngularJS, you need to create a custom directive that observes a focus attribute and programmatically sets focus when the condition is met.
Creating the Focus Directive
First, create a custom directive that will handle the focus functionality:
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.9/angular.min.js"></script>
</head>
<body ng-app="myApp" ng-controller="MyController">
<input type="text" ng-model="cue.text" focus="{{cue.isNewest}}"
class="input-xlarge" placeholder="Enter text..." />
<span>Focus state: {{cue.isNewest}}
<button ng-click="addNewCue()">Add New Item</button>
<script>
var app = angular.module('myApp', []);
app.directive('focus', function () {
return function (scope, element, attrs) {
attrs.$observe('focus', function (newValue) {
newValue === 'true' && element[0].focus();
});
}
});
app.controller('MyController', function($scope) {
$scope.cues = [
{ text: 'First item', isNewest: false },
{ text: 'Second item', isNewest: false }
];
$scope.addNewCue = function() {
// Reset all items
$scope.cues.forEach(function(cue) {
cue.isNewest = false;
});
// Add new item with focus
$scope.cues.push({
text: '',
isNewest: true
});
};
});
</script>
</body>
</html>
How the Directive Works
The directive uses attrs.$observe to watch for changes in the focus attribute value. When the value becomes 'true', it calls element[0].focus() to set focus on the input element.
HTML Template Structure
The HTML template uses the custom focus directive with data binding:
<input type="text" ng-model="cue.text" focus="{{cue.isNewest}}"
class="input-xlarge" />
Key Points
- The directive observes the
focusattribute for string value'true' - Use
element[0]to access the native DOM element from jqLite/jQuery wrapper - The
$observemethod is used for interpolated attributes like{{cue.isNewest}} - Only one input in the list should have
isNewest: trueat a time
Alternative Using $timeout
For better reliability, especially when dealing with dynamic lists, you can add a small delay:
app.directive('focus', function ($timeout) {
return function (scope, element, attrs) {
attrs.$observe('focus', function (newValue) {
if (newValue === 'true') {
$timeout(function() {
element[0].focus();
}, 0);
}
});
}
});
Conclusion
This approach provides a clean, reusable way to set focus on text inputs in AngularJS lists. The directive watches for attribute changes and automatically focuses the appropriate input element when needed.
