2015-12-02 60 views
6

我正在使用angular bootstrap typeahead指令。有没有办法在我使用typeahead时选择要在我的ng-model中设置的整个选定对象而不是字符串?角度自举typeahead设置ng-model到对象不是单个字段

例如

mycontroller.js

var getStates = function() { 
    // calls rest service that pulls in states.json from some angular factory 
} 
var StateCtrl = function ($scope) { 
    $scope.states = getStates(); 

    $scope.submit = function() { 
     // Should expect an Object and not the name of the state 
     console.log($scope.states); 
    } 
} 
angular.module('StateCtrl', []).controller(['$scope', StateCtrl]); 

states.json

[ 
// i don't want just state.name i want everything 
{name: Alabama, stateCode: 123, salesTax: .06}, 
{name: Arkansas, stateCode: 122, salesTax: .06}, 
{name: New York, stateCode: 120, salesTax: .10}, 
... 
] 

的index.html

<input ng-model="selectedstate" uib-typeahead="state.name for state in states"> 
<!--- i want selectedState to be {{state}} and not {{state.name}} --> 
<button ng-click="submit()">submit</button> 

回答

7

更换uib-typeahead="state.name for state in states"uib-typeahead="state as state.name for state in states"。这应该为你做的工作。这是一个工作plunker

+0

我认为结局部分应该是'国家状态' –

+1

是的,你说得对。这就是它的例子。我在答案中忘了它。感谢您的注意。 –

+0

此语法的相关文档:https://angular-ui.github.io/bootstrap/#/typeahead和https://docs.angularjs.org/api/ng/directive/select –