Angular JS下拉列表未显示ng-selected =“selected”的值

时间:2016-10-06 07:56:34

标签: javascript angularjs

我是AngularJS的新手,面对ng-option的问题,selected='selected'未在组合框中显示。

以下是选择HTML元素和数据源:

<select class="form-control" id="numberOfRows" ng-model="prefferedLanguage"
       ng-change="changePreference(prefferedLanguage)">
    <option my-repeat="language in sirCommonService.LOVData.LanguagePreference" value="{{language.LanguageISOCode}}"
            ng-selected="{{language.IsDefault == true}}">
        {{language.LanguageName}}
    </option>
</select>

sirCommonService.LOVData.LanguagePreference

"LanguagePreference": [
    {
      "LanguageISOCode": "EN",
      "LanguageName": "English",
      "IsDefault": true
    },
    {
      "LanguageISOCode": "FR",
      "LanguageName": "French",
      "IsDefault": false
    }
  ]

我想根据Load页面上的Model“IsDefault”设置组合框值。但它没有用。

生成的HTML是:

<select class="form-control ng-pristine ng-valid ng-empty ng-touched" id="numberOfRows" ng-model="prefferedLanguage" ng-change="changePreference(prefferedLanguage)"><option value="? undefined:undefined ?"></option>
    <!-- ngRepeat: language in sirCommonService.LOVData.LanguagePreference --><option my-repeat="language in sirCommonService.LOVData.LanguagePreference" value="EN" ng-selected="true" ng-repeat="language in sirCommonService.LOVData.LanguagePreference" class="ng-binding ng-scope" selected="selected">
        English
    </option><!-- end ngRepeat: language in sirCommonService.LOVData.LanguagePreference --><option my-repeat="language in sirCommonService.LOVData.LanguagePreference" value="FR" ng-selected="false" ng-repeat="language in sirCommonService.LOVData.LanguagePreference" class="ng-binding ng-scope">
        French
    </option><!-- end ngRepeat: language in sirCommonService.LOVData.LanguagePreference -->
</select>

3 个答案:

答案 0 :(得分:2)

处理选择的最佳方法是使用选择指令 ngOptions

https://docs.angularjs.org/api/ng/directive/select https://docs.angularjs.org/api/ng/directive/ngOptions

<select ng-options="item as item.label for item in items track by item.id" ng-model="selected"></select>

我遇到了和以前一样的问题。它与ngRepeat和选项不兼容。

答案 1 :(得分:1)

我刚刚在这里创建了一个plnkr: https://plnkr.co/edit/rCQzEhojZP0iHvoI1KlO?p=preview

你应该使用带有ng-options的select,类似这样的

 <select
        ng-model="defaultlanguage" 
        ng-options="lan.LanguageISOCode for lan in LanguagePreference">
 </select>

答案 2 :(得分:0)

ng-selected 指令将表达式作为参数。因此,请按以下方式更改您的代码:

ng-selected="language.IsDefault == true"