如何通过ui-select值设置ng-model值

时间:2014-07-31 17:27:59

标签: javascript angularjs angularjs-directive angular-ui angular-ui-bootstrap

我目前正在项目中使用angular-ui / ui-select。我能够将ui-select的值绑定到一个没有问题的对象,但是它绑定了正在迭代的整个item。我想只根据item.codeId进行绑定,这样我就可以保留正确的数据,并在加载页面时在下拉列表中显示正确的值。

如何设置ui-select来执行此操作?

<ui-select ng-model="myObject.stateCode" id="stateCode">
    <ui-select-match placeholder="Select a state...">{{$select.selected.codeDescription}}</ui-select-match>
    <ui-select-choices repeat="item in constants.states | filter: $select.search" value="{{$select.selected.codeId}}">
        <div ng-bind-html="item.codeDescription | highlight: $select.search"></div>
        <small ng-bind-html="item.codeId | highlight: $select.search"></small>
    </ui-select-choices>
</ui-select>

2 个答案:

答案 0 :(得分:16)

我相信你要做的是使用repeat=子句并删除value属性。这里有一个例子: http://plnkr.co/edit/htm8UNxVOlC076LVVezE?p=preview

我从中复制过: https://github.com/angular-ui/ui-select/blob/master/examples/demo-bind-to-single-property.html

<ui-select ng-model="myObject.stateCode" id="stateCode">
    <ui-select-match placeholder="Select a state...">{{$select.selected.codeDescription}}</ui-select-match>
    <ui-select-choices repeat="item.codeId as item in constants.states | filter: $select.search">
        <div ng-bind-html="item.codeDescription | highlight: $select.search"></div>
        <small ng-bind-html="item.codeId | highlight: $select.search"></small>
    </ui-select-choices>
</ui-select>

答案 1 :(得分:8)

您的代码很好,但是在使用子数组(constants.states)时出现了一个导致此问题的错误。

我刚刚在https://github.com/angular-ui/ui-select/pull/131解决了这个问题,特别是this commit

新版本v0.5.1已发布。 如果您正在使用凉亭,请运行bower update

相关问题