brazorf brazorf - 4 months ago 72
AngularJS Question

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.

Answer

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

Comments