简体   繁体   中英

Angular ngSelected not working in version > 1.3

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;


});

Plunker: https://plnkr.co/edit/7oi4KwzMhGi3kdltSklg?p=preview

Problem: if you inspect the html code of the select , you will see that the HTML selected attribute is properly placed.

However, it doesn't show as the highlighted option. Why?

== EDIT ==

That plunker code is working as expected on angular 1.3.20, but it's broken in 1.4.x or 1.5.x

Working plunker: https://plnkr.co/edit/0ApQeZ6Kar2yQisELXfT?p=preview

== EDIT2 ==

I've issued a ticket on angularjs queue: https://github.com/angular/angular.js/issues/14876#issuecomment-231010972

Basically, they say we should stick to ngOptions, though they don't know why ngSelected got broken.

Well, you could use ng-options instead...

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

Check here https://plnkr.co/edit/G4Hu4ZpShaUPCE5zTsdV

I don't see this working on any version that you mention. Anyway, check this plunker

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

The way that you wrote the select, i can reproduce the same thing on any input. And the reason is because it is not how angular binding works, your select doesn't know anything about his model, unless you change the model (ie using ng-init ).

Using this way:

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

doesn't mean that your model will update, it only updates the dom element.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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