2014-12-02 33 views
0

我们有要求在用户输入“@”时显示下拉菜单。如何查找何时在textarea中输入特定字符

我打算有一个指令如下:

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

请问这个行吗?

+0

作为参考,你可以在这里看看:https://github.com/fraserxu/ng-textcomplete – 2014-12-02 05:55:10

回答

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>

Plunkr demo

相关问题