繁体   English   中英

如何在下拉列表中选择一个选项angularjs

[英]How to select an option in a dropdown list angularjs

我正在使用AngularJS指令,并且需要在模板中设置下拉列表的选定选项。

<select id="energySource" ng-options="o.name for o in energyOptions" ng-model="energy" ng-selected="energy" ng-change="energyChange();"></select>

选项列表的内容取决于页面加载时服务器发送的资源。

var energyChosen = "All";


      angular.element(document).ready(function () {

          $.get('/Dashboard/GetResources', function (data) {

              scope.Resources = data;

              scope.energyOptions = [{ name: scope.Resources.Electricity, id: "Electricity" }, { name: scope.Resources.Gas, id: "Gas" },
               { name: scope.Resources.Water, id: "Water" }, { name: scope.Resources.Solar, id: "Solar" }];

              scope.energy = scope.energyOptions[0];
              energyChosen = scope.energy.id;

              scope.$apply();

          });

它起作用,除了预先选择了空白选项,当我选择一个我希望能够预选一个选项时,该选项会消失。 我认为

scope.energy = scope.energyOptions[0];

会成功的,但是没有。 在这种情况下,如何预选一个选项?

您执行ng-options会将ng-options名称存储在scope.energy而不是整个选项中。 进行以下操作时,您处在正确的轨道上:

scope.energy = scope.energyOptions[0];

但这是行不通的,因为它希望scope.energy是名称而不是整个选项。 您想在ng-options操作如下:

<select id="energySource" ng-options="o as on.name for o in energyOptions" ng-model="energy" ng-selected="energy" ng-change="energyChange();"></select>

重要的变化是将o as o.name 左侧的“ o”实际上是将选择并存储在您的scope.energy ,而as o.name是将在下拉as o.name中显示的文本。

确保scope.energy在初始化之外。

 $scope.energyOptions = [
    { name: "test1", id: "Electricity" }, 
    { name: "test2", id: "Gas" },
    { name: "test3", id: "Water" }, 
    { name: "test4", id: "Solar" }];
  $scope.energy = $scope.energyOptions[2];

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM