【问题标题】:Angular ngSelected not working in version > 1.3Angular ngSelected 在版本 > 1.3 中不起作用
【发布时间】:2016-07-06 14:52:31
【问题描述】:

标记:

<!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;


});

Plunker: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

== EDIT2 ==

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

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

【问题讨论】:

  • 我看不出带有角度 1.3x 和角度 1.5x 的 plnkr 之间有任何区别。

标签: javascript html angularjs


【解决方案1】:

嗯,你可以改用 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

【讨论】:

  • 使用 ng-options 非常棒
  • 是的,我可以,谢谢 - 但这不是我的意思,我想了解为什么 ng-selected 似乎被破坏了。
  • 问题出在使用 $scope.selectedItem = {id: 1};试试这个 $scope.selectedItem = {id: '1'};它工作正常...您正在将 id 字符串与 id 号进行比较,因此它不匹配
  • 我明白了。请检查更新的 plunker 版本,在选项标签中,你会看到匹配是真的。还是一头雾水
【解决方案2】:

我没有看到这适用于您提到的任何版本。无论如何,检查这个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 元素。

【讨论】:

猜你喜欢
  • 2015-05-09
  • 2014-12-17
  • 2020-05-29
  • 1970-01-01
  • 1970-01-01
  • 2023-03-13
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多