angularjs - How to find when a specific character is typed in textarea -


we have requirement show drop down when user enters "@".

i planning have directive following:

app.controller('mainctrl', function($scope) {       $scope.values = ['@'];     $scope.valuesentered = false; });  app.directive('identifier', function ($parse) {     return {         scope: {           values: '=values'         },         link: function (scope, elm, attrs) {           elm.bind('keypress', function(e){             var char = string.fromcharcode(e.which||e.charcode||e.keycode), matches = [];             angular.foreach(scope.values, function(value, key){               if(char === value) matches.push(char);             }, matches);             if(matches.length !== 0){               $scope.valuesentered = true;             }           });         }     }    }); 

will ok ?

here simple directive made allow specify expression evaluate when given key pressed or 1 of array of keys pressed.

note one-way street. there no going once have detected keypress, if user pressed backspace.

var app = angular.module('sample', []);    app.controller('mainctrl', function($scope) {    $scope.values = ['@', '!'];    $scope.valuesentered = false;    $scope.valuesentered2 = false;  });    app.directive('whenkeypressed', function($parse) {    return {      restrict: 'a',      scope: {        action: '&do'      },      link: function(scope, elm, attrs) {        var charcodestomatch = [];        attrs.$observe('whenkeypressed', function(keys) {          if (angular.isarray(keys))            charcodestomatch = keys.map(function(key) {              if (angular.isstring(key))                return key.charcodeat(0);            });          else if (angular.isstring(keys))            charcodestomatch = keys.split('').map(function(ch) {              return ch.charcodeat(0);            });        });          elm.bind('keypress', function(e) {          var charcode = e.which || e.charcode || e.keycode;          if (charcodestomatch.indexof(charcode) > -1)            scope.action();        });      }    }  });
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>    <div ng-app="sample">    <div ng-controller="mainctrl">      <p>values "@" entered? {{valuesentered}}</p>      <textarea ng-model="str" when-key-pressed="@" do="valuesentered = true"></textarea>        <p>values {{values}} entered 2: {{valuesentered2}}</p>      <textarea ng-model="str2" when-key-pressed="{{values}}" do="valuesentered2 = true"></textarea>    </div>  </div>

plunkr demo


Comments

Popular posts from this blog

ruby on rails - RuntimeError: Circular dependency detected while autoloading constant - ActiveAdmin.register Role -

c++ - OpenMP unpredictable overhead -

javascript - Wordpress slider, not displayed 100% width -