I use AngularJS with the ng-repeat directive to show an array of objects as a list.
<li ng-repeat="cue in cues" class="form-inline">
<input type="text" ng-model="cues[$index].text" class="input-xlarge"/>
{{cue.isNewest}}
</li>
The property "isNewest" is true on only one element of the array. I would like to set the keyboard focus on the text input of that item. How can I do that with AngularJS?
Here is another directive implementation that uses attrs.$observe:
myApp.directive('focus', function () {
return function (scope, element, attrs) {
attrs.$observe('focus', function (newValue) {
newValue === 'true' && element[0].focus();
// or, if you don't like side effects (see @Christophe's comment):
//if(newValue === 'true') element[0].focus();
});
}
});
Note that an interpolated DOM attribute value (i.e., {{cue.isNewest}}
) always evaluates to a string, hence the reason newvalue
is compared to the string 'true'
rather than keyword true
.
HTML:
<input type="text" ng-model="cues[$index].text" focus="{{cue.isNewest}}"
class="input-xlarge" />{{cue.isNewest}}
This fiddle also has a method to toggle which item in the array should have the focus.
Note that if you do not load jQuery, we need to use element[0].focus()
in the link function (not element.focus()
) becaues jqLite doesn't have a focus() method.
Since you would be manipulating the DOM, you will need to create a directive. Something like:
var app = angular.module('quirli', []);
app.directive('focusable', function() {
return {
restrict: 'A',
scope: {
focusable: '@'
},
link: function(scope, elm, attrs) {
scope.$watch('focusable', function (value) {
if (value) {
elm[0].focus();
}
});
}
};
});
Html:
<html ng-app="quirli" lang="en">
....
<input type="text" ng-model="cues[$index].text" class="input-xlarge" focusable="{{cue.isNewest}}"/>
Note: untested.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With