Angular UI Select2, why does ng-model get set as JSON string?

夙愿已清 提交于 2019-12-05 02:08:05

You need to use ng-options on your select if you want to have object values. Actually creating the options yourself using an ng-repeat will only allow you to have string values for the various options:

<select ui-select2
    ng-model="adminModel.selectedType"
    ng-change="roleTypeChanged()"
    data-placeholder="Select Role Type" ng-options="type.displayName for type in adminModel.roleTypes">
  <option value=""></option>
</select>

http://plnkr.co/edit/UydBai3Iy9GQg6KphhN5?p=preview

Thanks Karl! I have struggled a day with this

as a note for others having similar problems as I did, when using an ng-model not accessible and defined in the controller/directive I solved it like this.

//country.Model has Code and Name nodes

* HTML *

 <select 
name="country" data-ng-model="country.Model"  
    data-ui-select2=""  
    data-ng-change="countryChanged(country.Model)"  <!--only for test, log to console-->
    data-ng-options="country as CodeAndName(country) for country in countries"
    data-placeholder="{{placeholderText(country.Model, '- - Select Country - -')}}" >
    <option value=""></option>
</select>  

* JS *

 function controller($scope, $q, $location, $routeParams) {

    $scope.countryChanged = function(item) { // for test                
      console.log('selectedType is: ', item);
    };

    //returns the item or the text if no item is selected
    $scope.placeholderText = function (item, text){ 
        if (item == undefined)
            return text;
        return $scope.CodeAndName(item);
    };

    // returns a string for code and name of the item, used to set the placeholder text
    $scope.CodeAndName = function (item) { 
        if (item == undefined)
            return '';
        return item.Code + ' - ' + item.Name;
    };
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!