angular-ui-select - 如何将对象属性绑定到ng-model

Tam*_*hen 6 javascript angularjs angular-ui angular-ui-select

我在一个简单的用户注册表单中使用angular-ui-select:

<ui-select ng-model="user.countryCode" convert-to-string theme="selectize" class="dropdown">
    <ui-select-match placeholder="{{::strings('userDetails.countryPlaceholder')}}">{{$select.selected.name}}
    </ui-select-match>
    <ui-select-choices repeat="country in countries">
        <span ng-bind-html="country.name | highlight: $select.search"></span>
    </ui-select-choices>
</ui-select>
Run Code Online (Sandbox Code Playgroud)

这是我的国家/地区数组定义:

$scope.countries = [
            {name: 'Afghanistan', code: 'AF'},
            {name: 'Albania', code: 'AL'},
            {name: 'Australia', code: 'AU'},
            {name: 'Austria', code: 'AT'},
            {name: 'Azerbaijan', code: 'AZ'},
            {name: 'Belarus', code: 'BY'},
            {name: 'Belgium', code: 'BE'},
            {name: 'Belize', code: 'BZ'},
            {name: 'Benin', code: 'BJ'}
];
Run Code Online (Sandbox Code Playgroud)

我正在我的html中创建用户对象,每个字段都有一个绑定到用户某些属性的ng-model.当我使用诸如firstName的简单输入时,它很容易:

<input class="form-control" type="text" name="firstName" ng-model="user.firstName"/>
Run Code Online (Sandbox Code Playgroud)

但是使用下拉列表 - 我希望国家/地区名称显示在下拉列表选项中,并将其代码放在用户对象中.我想避免在控制器中编写代码.(即$ scope.user.countryCode = $ scope.country.selected.code;)

Joa*_*eal 12

我想你可以这样做:

<ui-select-choices repeat="country.code as country in countries">
    <span ng-bind-html="country.name | highlight: $select.search"></span>
</ui-select-choices>
Run Code Online (Sandbox Code Playgroud)

从文档:https: //github.com/angular-ui/ui-select/wiki/ui-select-choices

示例:绑定单个属性

在重复ui-select-choices时,标识要绑定的属性; repeat="item.id as item in cards">.