Search code examples
javascripthtmlangularjsdrop-down-menuangularjs-service

Get hardcoded dropdown values from service instead of directly displaying in html


I have this html code.

<select ng-model="Type">
 <option value=""></option>
 <option value="10D">10 Days</option>
 <option value="20D">20 Days</option>
 <option value="30D">30 Days</option>
</select>

Instead of directly coding the dropdown values in html, i am trying to get this values from angualrjs service.

I created the following service

DayServiceMod.service('DayService', ['$http', '$q', function ($http, $q, $scope) {
this.getDayDetails =function() {

    return [
    {DayValue: '10D' , DayDisplay: '10 Day'},
    {DayValue: '20D' , DayDisplay: '20 Day'},
    {DayValue: '30D' , DayDisplay: '30 Day'}

    ];
}

}]);

In the controller by providing proper injections of service. i tried to get day types as follows.

$scope.DayType = DayService.getDayDetails();

In the Html

<select ng-model="Type">
<option value="" disabled>Select Volume...</option>
<option ng-repeat="DayValue in DayType" value="{{DayValue}}">{{DayDisplay}}</option>
</select>

Can someone please let me know what i did wrong here.


Solution

  • You need to change your ng-repeat to something like this where you actually access the JSON property while setting the value and display name of the <option>. Everything is same, just for simplicity i have hard coded the option array inside the controller. The main change for you is the HTML.

    HTML

    <div ng-app="myapp" ng-controller='FirstCtrl'>
    <select ng-model="Type">
      <option value="" disabled>Select Volume...</option>
      <option ng-repeat="Day in DayType" value="{{Day.DayValue}}">{{Day.DayDisplay}}</option>
    </select>
    </div>
    

    Controller

    var myapp = angular.module('myapp', []);
    myapp.controller('FirstCtrl', function ($scope) {
      $scope.selectedRegione = 'Mike';
        $scope.DayType =[
        {DayValue: '10D' , DayDisplay: '10 Day'},
        {DayValue: '20D' , DayDisplay: '20 Day'},
        {DayValue: '30D' , DayDisplay: '30 Day'}
    
        ];
    });
    

    For your simplicity and further experiment with this code here is the link to JSFIDDLE