javascript - 使用 ng-options 生成下拉列表时,如何设置所选选项?

标签 javascript angularjs ng-options

这是plnker demo

script.js 中,我创建了一个变量 info 来存储选项。所选选项应为“西类牙语”,因为,

 {
     "name": "Spanish", 
     "value": 3082, 
     "selected": true //It's true here.
 }

如何解决这个问题?

最佳答案

您需要添加ng-model。根据您的 info.value.lang,您可以将 selected : true 设置为模型值。

function MyCntrl($scope) {
    $scope.info = info;
    $scope.selectedItem = null;

    angular.forEach(info.value.lang, function(lang) {
      if (lang.selected === true){
        $scope.selectedItem = lang.value;
      }
    });
}

<div ng-controller="MyCntrl">
  <select ng-model="selectedItem" ng-options="option.value as option.name for option in info.value.lang" >
  </select>
</div>

演示:http://plnkr.co/edit/RMr19uwuOH3EEjMd7cRL

关于javascript - 使用 ng-options 生成下拉列表时,如何设置所选选项?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29642567/

相关文章:

javascript - 如何在 ng-options 中设置默认值

javascript - AngularJS:为什么使用 ng-options 时 $element.find ('option' ) 返回一个空数组?

javascript - SimpleTemplate 可以忽略模板文件中的变量吗?

javascript - 我不断收到此错误 "Uncaught TypeError: name.push is not a function at <anonymous>:10:7"

javascript - 将 CodeMirror 添加到自定义元素的 Shadow Dom 中?

asp.net-mvc - 使用 Angular VS Razor 进行 ASP.Net MVC 验证

html - 如果我在 AngularJS 中使用数组中的链接,为什么音频不播放?

javascript - Angular JS 和指令链接和 $timeout

javascript - RegEx 替换返回意外结果,没有 .*

angularjs - 以编程方式选择绑定(bind)到对象数据源的 ng-options