AngularJS。当选择器有ng-model属性时,ng-selected无效。

6

我正在尝试在我的 option 元素中设置 ng-selected 属性,将 selected 属性设置为 true 时,但是该选项仍未被选中。当我从 select 中移除 ng-model 时,所有操作都可以正常工作。

问题: 如何在使用模型时使 option 被选中?

这里是我的 plunker(此处未能正常工作)

我的代码如下:

var app = angular.module("plunker", []);

app.controller("TestController", ["$scope", function($scope) {
  $scope.test = 1;
  $scope.array = [
        {"id": 1, "name": "first"}, 
        {"id": 2, "name": "second"}, 
        {"id": 3, "name": "third"}
      ];
}]);

我的模板:

  <body ng-controller="TestController">
    Selected item must be {{ array[test-1].name }}
    <select ng-model="myModel">
      <option value="">Choose item..</option>
      <option ng-repeat="item in array" 
              ng-value="item.id" 
              ng-selected="item.id == test">
        {{ item.name }} ({{item.id == test}})
      </option>
    </select>
  </body>

非常感谢您的帮助!

1
ng-selected和ng-model互斥。您的模型应该与选项ID匹配。 - Raulucco
1
对于选择,我认为你需要使用ng-options。请参考https://docs.angularjs.org/api/ng/directive/ngOptions。 - Pablo Ortuño
一旦从选择器中移除了ng-model,它就会选择要选择的值。看看这个分支 - http://plnkr.co/edit/u5bYQo7IgNmiABDZSyIQ?p=preview - Venkat.R
2个回答

7
不要在ngRepeat中使用ngSelected,应该使用ngOptions:
  <body ng-controller="TestController">
    Selected item must be {{ array[test-1].name }}
    <select ng-model="myModel" ng-options="item.id as item.name for item in array">
      <option value="">Choose item..</option>
    </select>
  </body>

我正要写这个!:P 我认为这是正确的答案!! - Pablo Ortuño
但是如果我必须基于ng-repeat值保留所选值怎么办?请查看此链接:https://stackoverflow.com/questions/50305993/how-to-use-select-inside-ng-repeat-and-keep-value-selected-on-api-call-data?noredirect=1#comment87628318_50305993 - Sudarshan Kalebere

2

不要在ngModel中使用ngSelected

文档中指出:

注意:ngSelected与


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接