0

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;
}; 
sturoid
  • 2,501
  • 4
  • 20
  • 36

2 Answers2

3

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.

pk1m
  • 286
  • 1
  • 4
  • 12
0
$('a').on('click', '#options', function(){
    $('input').focus();
});
Clayton
  • 444
  • 1
  • 6
  • 12