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

angular- ui-select - how to bind object property to ng-model

我在一个简单的用户注册表中使用 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>

这是我的国家数组定义:

$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'}
];

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

<input class="form-control" type="text" name="firstName" ng-model="user.firstName"/>

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

我认为你可以做到:

<ui-select-choices repeat="country.code as country in countries">
    <span ng-bind-html="country.name | highlight: $select.search"></span>
</ui-select-choices>

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

示例:绑定单个 属性

在 ui-select 的重复选项中确定您要绑定的 属性; repeat="item.id as item in cards">.

//in your view(aaa.html) part /
<select 
ng-model="Choices" 
ng-options="choice.code as choice.name for choice in countries ">

// 在你的控制器文件中 $scope.user.countryCode = "Choices";

您可以使用自定义过滤器 "transparently" 将对象转换为数组:

https://code.angularjs.org/1.4.7/docs/error/filter/notarray

https://github.com/petebacondarwin/angular-toArrayFilter