sturoid
sturoid

Reputation: 2721

Return to text box after click

I have a text box and an options list where options can be added to the current text that is in that box. The problem I'm having is that when I click on an option, and that option is added to the text, I want the cursor to be put back into the text box so the user can continue typing. Any help is much appreciated.

Text field:

input type='text' ng-model='comment.text' ng-change='userList(comment.text)'

JS:

$scope.addUserToComment = function(user) {
  $scope.comment.text += user + " ";
  $scope.usersShow = false;
}; 

Upvotes: 0

Views: 64

Answers (2)

pk1m
pk1m

Reputation: 286

Avoid modifying the DOM in the controllers.

edit: but to answer your question, ng-focus was me being lazy.

I would create a directive

angular.module('focus-me', []).
  .directive('focusMe', function(){ 
    return {
      scope: { watch_this: '=' },
      link: function(scope, element, attrs){ 
              scope.$watch('watch_this', function(){
                 $(element).focus();
              }
            }
    }                  
});

this gives you two options

input type='text' focus-me='comment.text' ng-model='comment.text' ng-change='userList(comment.text)'

or

input type='text' focus-me='some_obj_attr_you_toggle' ng-model='comment.text' ng-change='userList(comment.text)'

1st will call the watcher function more times than necessary, when you are typing as well (not really a big deal).

2nd will only call the watcher function when you toggle the attr in your addUserTo function.

A simpler way (although you are modifying the dom in the controller) would be:

$scope.addUserToComment = function(user, $event) {
  $($event.target).find('css selector to navigate to textbox').focus();
  $scope.comment.text += user + " ";
  $scope.usersShow = false;
}; 

in your ng-click add another parameter

ng-click='addUserToComment(user, $event)'

PS. Code might not be 100% correct but you get the idea.

Upvotes: 3

Clayton
Clayton

Reputation: 444

$('a').on('click', '#options', function(){
    $('input').focus();
});

Upvotes: 0

Related Questions