0

I am trying to set the first option to be set selected by default.

<div class="row" ng-controller='ctrl1'>
    <div class ="form_group">
        <select class="form-control" ng-options='item as item.hotel_name for item in hotels.data' ng-model='current_Hotel' ng-click="selectHotel()" ng-selected="selectedOptions.length[0]"></select>
    </div>

    <div class="col-md-6">      
        <h1>{{current_Hotel.hotel_name}}</h1>
        <p>{{current_Hotel.hotel_description}}</p>
        <img id="hotelImg" class="img img-responsive" ng-src="{{current_Hotel.image_url}}">
        <btn class="btn btn-primary" ng-click="selectRoom()">Book a room </btn>
    </div>

</div>

I tried using ng-selected but It doesn't work.

Here is my controller

var app = angular.module('myApp', []);
app.controller('ctrl1', function ($scope, $http) {
     $scope.current_Hotel = {
        hotel_id: "",
        hotel_name: "",
        hotel_description: "",
        exterior_image: "",
        image_url: ""
    };

$http({
    url: '',
    method: "POST",
    data: 'postData',
    headers: {
        'Authorization': ''
    }
}).then(function (response) {
            $scope.hotels = response.data;
        });       

$scope.selectHotel = function () {
    $http({
        method: 'GET',
        url: '' + $scope.current_Hotel.exterior_image
    }).then(function (response) {

                var imgdata = response.data;
                var imgdata1 = imgdata.data.image_name;
                $scope.current_Hotel.image_url = "" + imgdata1;
            });
};

When you select one of the options the value in h1 and p tags get displayed. I want the first option to be selected when the page is loaded so that the values in h1 and p tags are also shown by default.

DragonBorn
  • 1,809
  • 5
  • 20
  • 44
  • Possible duplicate of [How to have a default option in Angular.js select box](http://stackoverflow.com/questions/18194255/how-to-have-a-default-option-in-angular-js-select-box) – Ankh Mar 17 '17 at 11:08
  • 1
    set your ng-model to fisrt value of your options – Jayant Patil Mar 17 '17 at 11:11

1 Answers1

2

You can initialize your model like $scope.current_Hotel = $scope.hotels.data[0]; as soon as you get response in $scope.hotels object array.

$http({
    url: '',
    method: "POST",
    data: 'postData',
    headers: {
        'Authorization': ''
    }
}).then(function (response) {
            $scope.hotels = response.data;
          $scope.current_Hotel = $scope.hotels.data[0];
        });
Irfan Muhammad
  • 715
  • 2
  • 8
  • 20