在角度引导类型中清除选定的输入

时间:2014-03-17 06:02:07

标签: javascript jquery angularjs twitter-bootstrap bootstrap-typeahead

我使用http://angular-ui.github.io/bootstrap/#/typeahead作为简单的数组查找示例。

当我清空list()字段并按回车键时,我想触发input。目前我可以编写另一个Clear按钮来执行此操作。但是当输入为空时如何允许按键?我希望用户从列表中选择或仅清除它。不应该有其他价值。

HTML

<!doctype html>
<html ng-app="plunker">

<head>
  <script src="http://ajax.googleapis.com/ajax/libs/angularjs/1.2.8/angular.js"></script>
  <script src="http://angular-ui.github.io/bootstrap/ui-bootstrap-tpls-0.10.0.js"></script>
  <script src="example.js"></script>
  <link href="//netdna.bootstrapcdn.com/bootstrap/3.0.3/css/bootstrap.min.css" rel="stylesheet">
</head>

<body>

  <script type="text/ng-template" id="customTemplate.html">
    < a > < img ng - src = "http://upload.wikimedia.org/wikipedia/commons/thumb/{{match.model.flag}}"
    width = "16" > < span bind - html - unsafe = "match.label | typeaheadHighlight:query" > < /span>
  </a >
  </script>
  <div class='container-fluid' ng-controller="TypeaheadCtrl">

    <h4>Static arrays</h4>
    <pre>Model: {{selected | json}}</pre>
    <input type="text" typeahead-on-select="list()" ng-model="selected" typeahead="state for state in states | filter:$viewValue | limitTo:8" class="form-control">
    <button ng-click="clear()">Clear</button>
  </div>
</body>

</html>

的Javascript

angular.module('plunker', ['ui.bootstrap']);
function TypeaheadCtrl($scope, $http) {

  $scope.selected = undefined;
  $scope.states = ['Alabama', 'Alaska', 'Arizona', 'Arkansas', 'California', 'Colorado', 'Connecticut', 'Delaware', 'Florida', 'Georgia', 'Hawaii', 'Idaho', 'Illinois', 'Indiana', 'Iowa', 'Kansas', 'Kentucky', 'Louisiana', 'Maine', 'Maryland', 'Massachusetts', 'Michigan', 'Minnesota', 'Mississippi', 'Missouri', 'Montana', 'Nebraska', 'Nevada', 'New Hampshire', 'New Jersey', 'New Mexico', 'New York', 'North Dakota', 'North Carolina', 'Ohio', 'Oklahoma', 'Oregon', 'Pennsylvania', 'Rhode Island', 'South Carolina', 'South Dakota', 'Tennessee', 'Texas', 'Utah', 'Vermont', 'Virginia', 'Washington', 'West Virginia', 'Wisconsin', 'Wyoming'];

  $scope.list = function() {
    alert($scope.selected);
  }

  $scope.clear = function() {
    $scope.selected = undefined;
    $scope.list();
  }
}

http://plnkr.co/edit/roushmavR67rhXTJNc8K?p=preview

1 个答案:

答案 0 :(得分:1)

预先输入的目的是提供可能选择的提示,但也允许非选择(默认情况下无论如何)。你想要做的只是一个选择框:

<select ng-options='state for state in states'></select>

但是如果你想模拟这个选择框的想法,只允许输入一个类型中的选项,那么你需要使用ng-keypress指令并传递$ event内部变量:

控制器添加:

$scope.testAllowed = function( evt ){
    if( evt.keyCode === 13 && 
        $scope.selected && 
        $scope.states.indexOf( $scope.selected ) < 0){

      $scope.selected = '';
    }
  }

输入html添加:

ng-keypress="testAllowed($event)"

Example plunkr