Is there a cleaner way of delegating focus to an element when a checkbox is clicked. Here's the dirty version I hacked:
HTML
<div ng-controller="MyCtrl">
<input type="checkbox" ng-change="toggled()">
<input id="name">
</div>
JavaScript
var myApp = angular.module('myApp',[]);
function MyCtrl($scope, $timeout) {
$scope.value = "Something";
$scope.toggled = function() {
console.debug('toggled');
$timeout(function() {
$('#name').focus();
}, 100);
}
}
JSFiddle: http://jsfiddle.net/U4jvE/8/
how about this one ? plunker
$scope.$watch('isChecked', function(newV){
newV && $('#name').focus();
},true);
@asgoth and @Mark Rajcok are correct. We should use directive. I was just lazy.
Here is the directive version. plunker I think one good reason to make it as directive is you can reuse this thing.
so in your html you can just assign different modals to different sets
<input type="checkbox" ng-model="isCheckedN">
<input xng-focus='isCheckedN'>
directive('xngFocus', function() {
return function(scope, element, attrs) {
scope.$watch(attrs.xngFocus,
function (newValue) {
newValue && element.focus();
},true);
};
});
Another directive implementation (that does not require jQuery), and borrowing some of @maxisam's code:
myApp.directive('focus', function() {
return function(scope, element) {
scope.$watch('focusCheckbox',
function (newValue) {
newValue && element[0].focus()
})
}
});
HTML:
<input type="checkbox" ng-model="focusCheckbox">
<input ng-model="name" focus>
Fiddle.
Since this directive doesn't create an isolate scope (or a child scope), the directive assumes the scope has a focusCheckbox
property defined.
If you want to make it more interesting, and support for any expression to be evaluated (not only variables), you can do this:
app.directive('autofocusWhen', function ($timeout) {
return {
link: function(scope, element, attrs) {
scope.$watch(attrs.autofocusWhen, function(newValue){
if ( newValue ) {
$timeout(function(){
element.focus();
});
}
});
}
};
});
And your html can be a little more decoupled, like that:
<input type="checkbox" ng-model="product.selected" />
{{product.description}}
<input type="text" autofocus-when="product.selected" />
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