角度 ng 选择在 1.3 >版本中不起作用

Angular ngSelected not working in version > 1.3

本文关键字:版本 不起作用 ng 选择 角度      更新时间:2023-09-26

Markup:

<!DOCTYPE html>
<html ng-app="test">
  <head>
    <script data-require="angular.js@1.5.6" data-semver="1.5.6" src="https://code.angularjs.org/1.5.6/angular.min.js"></script>
    <link rel="stylesheet" href="style.css" />
    <script src="script.js"></script>
  </head>
  <body ng-controller="ctrl">
    <h1>Hello Plunker!</h1>
    <select ng-model="user.item_id">
      <option ng-selected="i.id == user.item_id" ng-repeat="i in items" value={{i.id}}>{{i.name}}</option>
    </select>
  </body>
</html>

.JS:

var module = angular.module("test", []);
module.controller('ctrl', function($scope){
  $scope.items = [
    {id: 1, name: 'foo'},
    {id: 2, name: 'bar'},
    {id: 3, name: 'baz'},
  ];
  $scope.user = {};
  $scope.selectedItem = {id: 1};
  $scope.user.item_id = $scope.selectedItem.id;

});

普伦克:https://plnkr.co/edit/7oi4KwzMhGi3kdltSklg?p=preview

问题:如果您检查select的 html 代码,您将看到 HTML selected属性放置正确。

但是,它不会显示为突出显示的选项。为什么?

== 编辑 ==

该 plunker 代码在 angular 1.3.20 上按预期工作,但在 1.4.x 或 1.5.x 中被破坏

工作压榨机:https://plnkr.co/edit/0ApQeZ6Kar2yQisELXfT?p=preview

== 编辑2 ==

我已经在angularjs队列上发出了一张票:https://github.com/angular/angular.js/issues/14876#issuecomment-231010972

基本上,他们说我们应该坚持使用ngOptions,尽管他们不知道为什么ngSelected被破坏了。

好吧,你可以改用ng-options...

<select ng-model="user.item_id" ng-options="i.id as i.name for i in items">
</select>

在这里查看 https://plnkr.co/edit/G4Hu4ZpShaUPCE5zTsdV

我没有看到这适用于您提到的任何版本。无论如何,检查这个 plunker

https://plnkr.co/edit/V0ybr70kRpkcaxLKBHTK?p=preview

您编写选择的方式,我可以在任何输入上重现相同的内容。原因是因为角度绑定不是如何工作的,你的选择对他的模型一无所知,除非你改变模型(即使用ng-init)。

使用这种方式:

<option ng-selected="i.id == user.item_id" ng-repeat="i in items" value={{i.id}}>{{i.name}}</option>

并不意味着您的模型将更新,它只会更新 DOM 元素。