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

Tamar Cohen picture Tamar Cohen · Jun 23, 2015 · Viewed 8.6k times · Source

i'm using the angular-ui-select in a simple user registration form:

<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>

Here's my countries array definition:

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

I'm creating the user object in my html, every field had an ng-model binded to some property of the user. When i'm using simple input such as firstName then it's easy:

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

But with the dropdown - I want the country name to be displayed in the dropdown list options and the its code to be placed in the user object. I want to avoid writing code in the controller for this. (i.e. $scope.user.countryCode = $scope.country.selected.code; )

Answer

Joao Leal picture Joao Leal · Jun 23, 2015

I think you can do:

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

From the documentation: https://github.com/angular-ui/ui-select/wiki/ui-select-choices

Example: Binding Single Property

In the repeat of the ui-select-choices identify the property you are wanting to bind to; repeat="item.id as item in cards">.