Siddharth Pandey
Siddharth Pandey

Reputation: 669

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"
      }
 }

Upvotes: 5

Views: 17214

Answers (4)

Erazihel
Erazihel

Reputation: 7605

I recommend you to use the Angular Directive ng-options.

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

Associated plunker: http://plnkr.co/8LGz5o0d2gDRoRHYr4pQ

Upvotes: 2

Sunil Jakhar
Sunil Jakhar

Reputation: 229

if you use ng-Selected and ng-Model together was never really specified. It looks like at some point ng-Model took priority over ng-Selected.

Upvotes: 4

Ren&#233; Wolferink
Ren&#233; Wolferink

Reputation: 3548

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.

Upvotes: 11

Bwaxxlo
Bwaxxlo

Reputation: 1880

Your option tag should be:

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

Upvotes: 8

Related Questions