Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Angular js input box typing and paused

Am new to angular js and using xmpp service with angular js,I have a situation where i need to send typing when user starts typing in input box and pause when user stops typing.

I have basic idea that i need to use $timeout,and have one variable like vm.isTyping = false;

i also have written some sort of platform for the same.

vm.isTyping = false;
vm.checkTyping = function(){
    $timeout(function() {
        vm.isTyping = true;
    },2000);

    if(!vm.isTyping){
        vm.sendTyping();
    } else{
        //
    }
};

This is the input field code:

<input type="text" placeHolder="Type a message here" 
    ng-model="vm.newMessage" 
    ng-blur="focusRemove(vm.newMessage,vm.contact)" 
    ng-change="vm.checkTyping()"
    ng-model-options="{'debounce': 500}" 
    ng-keydown="vm.onKeyDown($event)" auto-focus />

The problem i am facing is that i cannot send typing everytime when user presses any key,one typing is sent on first key press then i should send pause when user stop typing.

Can any one help me to implement code in angular js to achieve this.

like image 845
Pratswinz Avatar asked Oct 30 '22 21:10

Pratswinz


1 Answers

What you can try is have ng-keyup attribute included in you input tag. So when the user starts typing you set the flag vm.isTyping = true. When the user stops typing have a timeout in your ng-keyup handler, that will set vm.isTyping = false after a certain period. Refer the below code snipet

function myappCtrl($scope, $timeout) {
    var timoutPromise = null;
		$scope.newMessage = "";
    $scope.isTyping = false;
    
    $scope.checkTyping = function() {
    	$scope.isTyping = true;
      if(timoutPromise) {
          $timeout.cancel(timoutPromise);
      }
    }
    
    $scope.stoppedTyping = function() {
    	timoutPromise = $timeout(function() {
        $scope.isTyping = false;
      }, 2000)
    	
    }
}
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<div ng-app>
 <div ng-controller="myappCtrl">
  <input  type="text" placeHolder="Type a message here" ng-model="newMessage" ng-change="checkTyping()"  ng-keyup="stoppedTyping()"/>
  <div ng-if="isTyping">
    typing
  </div>
</div>
</div>
like image 162
Ananth Pai Avatar answered Nov 11 '22 13:11

Ananth Pai