Monday, May 20, 2024
 Popular · Latest · Hot · Upcoming
72
rated 0 times [  74] [ 2]  / answers: 1 / hits: 17273  / 9 Years ago, thu, april 2, 2015, 12:00:00

Am facing problem in displaying selected value in angular dropdown.
it works when i give like this



$scope.selectedItem = $scope.items[1];


not working, if i give directly that value



$scope.selectedItem = { name: 'two', age: 27 };


HTML:



<html ng-app=app>
<body>
<div ng-controller=Test>
<select ng-model=selectedItem ng-options=item.name for item in items>
</select>
</div>
</body>
</html>


JS:



var app = angular.module('app',[]);
app.controller('Test',function($scope){
$scope.items = [{name: 'one', age: 30 },{ name: 'two', age: 27 },{ name: 'three', age: 50 }];
$scope.selectedItem = $scope.items[1];
});


CODEPEN:
http://codepen.io/anon/pen/zxXpmR



SOLUTION:



Thank you samir-das. I fixed as per your suggestion.



var choosen_value = { name: 'two', age: 27 };
angular.forEach($scope.items, function(item){
if(angular.equals(choosen_value, item)){
$scope.selectedItem = item;
}
});

More From » arrays

 Answers
18

Well, because



$scope.items[1] and { name: 'two', age: 27 } is totally different thing.



{ name: 'two', age: 27 } is a totally different object whereas $scope.items[1] is part of the object $scope.items



When you put something in the template using {{}}, angular add it in its watcher list.



SO when angular put it in the watch list, it was an object (i.e. { name: 'two', age: 27 } ) that is different than $scope.items.



selectedItem is attached with the object that you set in the controller. In summary while dirty checking, angular will checks selectedItem against { name: 'two', age: 27 } NOT against $scope.items



Hope you understand what I mean


[#67224] Monday, March 30, 2015, 9 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
wyattkennyc

Total Points: 650
Total Questions: 102
Total Answers: 90

Location: Monaco
Member since Mon, May 23, 2022
2 Years ago
;