AngularJS TypeAhead - 为 ng-model 采用不同的属性

AngularJS TypeAhead - take a different attribute for ng-model

http://jsfiddle.net/H7LA4/275/

我想在输入框上方显示所选状态的id,而不是状态名称。如何重构代码以显示所选状态的 ID?

<div ng-app="myApp">
    <div class='container-fluid' ng-controller="TypeaheadCtrl"> <pre>State: {{selected}}</pre>

        <input class="input-large" type="text" ng-model="selected" typeahead="state.name for state in states | filter:$viewValue | limitTo:8">
    </div>
</div>

JS

angular.module('myApp', ['ui.bootstrap']);

function TypeaheadCtrl($scope) {

    $scope.selected = undefined;
    $scope.states = [{name: 'Alabama',id: 1}, {name: 'New York',id: 2}, {name: 'Calafornia',id: 3}];
}

你应该更换

<input class="input-large" type="text" ng-model="selected" typeahead="state.name for state in states | filter:$viewValue | limitTo:8">

<input class="input-large" type="text" ng-model="selected" typeahead="state.id as state.name for state in states | filter:$viewValue | limitTo:8">

我会用

提前输入select

回调以获得更多控制并在需要时进行额外计算

HTML

<div ng-app="myApp">
    <div class='container-fluid' ng-controller="TypeaheadCtrl"> 
      <pre>State: {{selectedId}}</pre>

        <input 
        class="input-large" 
        type="text" 
        ng-model="selected" 
        typeahead="state.name for state in states | filter:$viewValue | limitTo:8"
        typeahead-on-select="onSelect($item)">
    </div>
</div>

JS

angular.module('myApp', ['ui.bootstrap']);

function TypeaheadCtrl($scope) {

    $scope.selected = undefined;
    $scope.states = [{name: 'Alabama',id: 1}, {name: 'New York',id: 2}, {name: 'Calafornia',id: 3}];

    $scope.onSelect = function ($item, $model, $label, $even) {
        $scope.selectedId = $item.id
    }
}

我同意接受的答案,如果有人想在没有额外回调的情况下实现这一点,您可以使用

<input class="input-large" type="text" ng-model="selected" typeahead="state as state.name for state in states | filter: $viewValue | limitTo:8">

这会将整个对象绑定到 selected 模型,因此您可以使用 selected.idselected.name.
然后如果你想通过id禁用过滤器,只需将filter: $viewValue更改为filter: {name: $viewValue}