2014-12-02 64 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

相關問題