我有JSON文件,如下所示
var LocationList = [
{"id":1,"value":"ABC"},
{"id":2,"value":"XYZ"},
.
.
.
]
我正在尝试动态填充HTML下拉列表
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>
问题: 当我从下拉列表中选择一个选项并转到下一页并再次返回到同一页面时,ng-model不起作用。预期的行为是下拉列表应设置为用户选择的值,但下拉列表会显示1选项。
如果我没错,ng-model在ng-bind-html之前运行,所以如果没有填充下拉列表,那么将如何选择该值。
有没有办法延迟ng-model,所以列表首先填充,然后绑定发生。
我可以知道我哪里出错了。
提前致谢
答案 0 :(得分:1)
你应该阅读ng-options,你不需要你的html绑定,你可以这样做:
控制器:
$scope.LocationList = LocationList;
HTML:
<select id="location"
ng-model="Location.location"
ng-options="location as location.value for locaiton in LocationList"
></select>