Angular - ui-select - how to associate an object property with ng-model

I use 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 is my definition of an array of countries:

 $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 create a user object in my html, each field had an ng model attached to some property of the user. When I use simple input like firstName, then this is easy:

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

But with a drop-down menu - I want the country name to be displayed in the drop-down list of parameters and its code, which should 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;)

+6
source share
3 answers

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: Single Property Binding

In repeating the selection, ui-select is the identification of the property to which you want to bind; repeat="item.id as item in cards"> .

+12
source

You can use your own filter to transparently convert your object into an array:

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

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

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

// in your controller file $ scope.user.countryCode = "Select";

-3
source

Source: https://habr.com/ru/post/989629/


All Articles