Mr. Pacific
Mr. Pacific

Reputation: 43

ng-bind-html and ng-model together in select dropdown

I have JSON file as below

var LocationList = [
{"id":1,"value":"ABC"},
{"id":2,"value":"XYZ"},
.
.
.
]

I'm trying to dynamically populate dropdown on my HTML as below

Angular Code: .factory('locationService', function($filter){

     var Location = {};
     Location.Template = "";

     Location.getLocation = function(){

        var template = '<option direction="ltr" value="" id="theOption2">' + $filter('translate')('lSummary_Location_text') + '</option>';

        LocationList.forEach(function(loc){
                         var value = loc.value + ' / ID: ' + loc.id;
                         template += '<option direction="ltr" value="' + value + '">' + loc.value + '</option>';
                      });

        Location.Template = template;
     },
     Location.getTemplate = function(){
        return Location.Template;
     }

     return Location;

     })

.controller('secondInfoCtrl',function($scope, locationService, $sce){
$scope.locationList =$sce.trustAsHtml(locationService.getTemplate());

//RETURNS THE DATA FROM LOCAL STORAGE  
$scope.Location = SecondScreenService.getInfo();
})

HTML:

<select id="location" ng-model="Location.location" ng-bind-html="locationList"></select>

Problem: When I select an option from dropdown and move to next page and come back again to same page, ng-model is not working. Expected behavior is that the dropdown should be set to the value selected by the user, but the dropdown shows 1 option as selected.

If I'm not wrong, ng-model runs before ng-bind-html, so if the dropdown is not populated how the value will be selected.

Is there any way to delay ng-model, so that the list gets populate first and binding happens after that.

May I know where I'm going wrong.

Thanks in advance

Upvotes: 1

Views: 1502

Answers (1)

Mathew Berg
Mathew Berg

Reputation: 28750

You should read up on ng-options, none of your html binding is needed you can just do this:

Controller:

$scope.LocationList = LocationList;

HTML:

<select id="location" 
    ng-model="Location.location" 
    ng-options="location as location.value for locaiton in LocationList"
></select>

Upvotes: 1

Related Questions