Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

AngularJS - Focusing an input element when a checkbox is clicked

Tags:

angularjs

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/

like image 350
kolrie Avatar asked Dec 28 '12 22:12

kolrie


3 Answers

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);
      };    
});
like image 57
maxisam Avatar answered Nov 13 '22 19:11

maxisam


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.

like image 38
Mark Rajcok Avatar answered Nov 13 '22 20:11

Mark Rajcok


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" />
like image 26
ViniciusPires Avatar answered Nov 13 '22 20:11

ViniciusPires