Siddharth Pandey Siddharth Pandey - 1 year ago 141
AngularJS Question

ng-selected not working

My problem is that

ng-selected
is set as
true
but the option is not getting selected

This is my controller code

.controller("PendingInvoiceCtrl", function($scope, $location, safeApply, dataService) {
var userData = dataService.data();
var mauth_token = userData.mauthToken;
var mauth_acntId = userData.thisApartment.account;
var apt_id = userData.thisApartment.id;

$scope.house_list = userData.thisApartment.house;
$scope.selectedHouseId = $location.search().houseId;

console.log($scope.selectedHouseId);
});


This is my HTML code

<select ng-model="selectedHouseId">
<option ng-repeat="house in house_list" ng-selected="{{ house.house_id == selectedHouseId }}" value="{{ house.house_id }}">
{{ house.house_display_name }}
</option>
</select>


And below is my data format

{
house:[0]:{
house_display_name: "paras, 101",
house_id: "520755"
}
}

Answer Source

The ng- attributes don't need the extra curly braces. Try:

<option ng-repeat="house in house_list" ng-selected="house.house_id == selectedHouseId" ng-value="house.house_id">
    {{house.house_display_name}}
</option>

A better approach would be to use the ng-options possibility of the select tag. This would result in:

<select
    ng-model="selectedHouseId"
    ng-options="house.house_id as house.house_display_name for house in house_list">
</select>

And then you don't need to manually worry about the selected attribute for the options, as it will select the one depending on the value of the model.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download