Search code examples
javascriptangularjsangularjs-scope

Using angular's $scope.info varible inside a service


I want to use this method (which ouputs a message if a user is typing) with a service. the method is updating a info varible (set its text to "typing" or blank).

I thought about using this method as a service to my angular model. the problem is that this method needs access to the text varible {{info}} with sits inside the view (some html).

How can I do that? my code is below.... Thanks

js file

mymodule.controller("cntrlChat", ['$scope','isUserTypingService',
  function($scope,isUserTypingService){ 

  $scope.isUserTyping=function(){
    isUserTypingService($scope.info);

  }

}]);

mymodule.factory('isUserTypingService',['$q','$timeout', function($q,$timeout) {

  var isUserTyping= function(info) {
     runTwoFunctionWithSleepBetweenThem(function (){info='user is typing...';},function (){info='';},3500);
  };

  var runTwoFunctionWithSleepBetweenThem=function(foo1, foo2, time) {
    $q.when(foo1()).then(() => $timeout(foo2, time));
  }
  return isUserTyping;
}]);

index.html

 <html>
 <head>

    <script data-require="[email protected]" src="https://code.angularjs.org/1.4.9/angular.js" data-semver="1.4.9">
    </script>
    <script src="http://ajax.googleapis.com/ajax/libs/angularjs/1.2.25/angular-route.js"></script>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/angular-ui-router/0.3.1/angular-ui-router.min.js"></script>
    <script src="/socket.io/socket.io.js"></script>
    <script src="script.js"></script>

    <link rel="stylesheet" type="text/css" href="../css/style.css">
 </head>

 <div ng-app="mymodule" ng-view>
 </div>


 </html>

chat.html

{{info}} 

Solution

  • you could do something like this:

    <input ng-model="userInput" ng-change="runWhenTyping()" />
    

    in your controller:

    $scope.userInput = '';    
    $scope.runWhenTyping = function () { isUserTypingService($scope.userInput) }
    

    Each time they type runWhenTyping will be called and in turn it will call your service.