如何在textarea中键入特定字符的时间

时间:2014-12-02 05:37:01

标签: angularjs

当用户输入“@”时,我们要求显示下拉列表。

我打算制定如下指令:

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;
            }
          });
        }
    }   
});

这样可以吗?

1 个答案:

答案 0 :(得分:1)

这是一个简单的指令,它允许您指定一个表达式,以便在按下给定键或按下一个键数组时进行评估。

请注意,这是一条单行道。一旦检测到按键,即使用户按下退格键,也无法返回。



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>
&#13;
&#13;
&#13;

Plunkr demo