使用数组(在本例中为 $scope.dataselect =[])将保留从 API 获取的数据。并将其绑定到您的模板选项元素,如下所示:
<select ng-model="locationForm.country">
<option ng-repeat="data in dataselect" value="{{data.code}}">{{data.value}}</option>
</select>
在控制器上,在成功回调中设置或推送数据到当前作用域上的数组($scope.dataselect)。如果数据发生更改,则视图将自动更新。您无需手动更新视图。你也可以使用$http服务。
app.controller('myCtrl', function($scope, $http) {
$scope.fetchCountries = function() {
$scope.dataselect = []; // something [{code:"1",value:"data1"},{code:"2",value:"data2"}]
$http.get("http://.../someurl/dropdown?typ=Countries")
.then(function(data) {
angular.forEach(data, function(val, key) {
var elem = {key:val.code,value:val.value};
$scope.dataselect.push(elem);
})
}, function(response) {
//handles error
$scope.dataselect = [{code:"-1",value:"Not available"}]
});
});
});
var app = angular.module("myApp",[]);
app.controller('MainCtrl', function($scope,$http) {
$scope.dataselect =[];
$scope.update = function() {
console.log("changed "+$scope.locationForm.country);
}
$scope.fetchCountries = function() {
$scope.dataselect =[];
$scope.dataraw ={"code1":"value1","code2":"value2"}; //dummy from API
angular.forEach($scope.dataraw, function(val, key) {
var elem = {key:key,value:val};
$scope.dataselect.push(elem);
})
}
});
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<div ng-app="myApp" ng-controller="MainCtrl ">
{{locationForm.country}}
<select ng-change="update()" id="countryListId" ng-model="locationForm.country">
<option ng-repeat="data in dataselect" value="{{data.key}}">{{data.value}}</option>
</select>
<button ng-click="fetchCountries()">Fetch</button>
</div>
解决方案2:(为了解释)
但是,如果您只想使用jQuery#html 函数,那么您应该按如下方式创建包装器元素:
<div id="select-container-js">
<select id="countryListId"></select>
</div>
现在您可以使用它了。但在这种情况下,您还需要调用 $compile 来编译带有新元素的 DOM 并将其链接到当前范围。
$('#select-container-js').html('<select id="countryListId" ng-model="locationForm.country"></select>');
//you should set $selectCountry just before using it because of reference losing.
var $selectCountry = $('#countryListId');
$.each(data, function(key, val) {
$selectCountry.append('<option value="' + val.code + '">' + val.value + '</option>');
})
$compile($selectCountry)($scope);
不是:不要忘记将 $compile 服务注入您的控制器。
app.controller('MainCtrl', function($scope,$compile) {}