使用$http
service獲取的來自服務器的選項列表,然後使用ngRepeat
option
元素來填充的列表模板中的選項。看下面的例子:
(function (angular) {
'use strict';
angular.module("demo", [])
.service('CountriesService', ['$http', function CountriesService($http) {
var countriesService = this;
var countriesResult = null;
countriesService.getCountries = getCountries;
function getCountries() {
if (!countriesResult) {
countriesResult = $http({
method: 'GET',
url: '//restcountries.eu/rest/v2/all'
}).then(function (res) {
return res.data;
});
}
return countriesResult;
}
return countriesService;
}])
.controller('Demo', ['CountriesService', function Demo(CountriesService) {
var vm = this;
vm.$onInit = onInit;
vm.countryChanged = countryChanged;
function onInit() {
CountriesService.getCountries().then(function (res) {
vm.countries = res;
});
}
function countryChanged(selectedCountry) {
console.log(selectedCountry);
}
}]);
})(angular);
<script src="//ajax.googleapis.com/ajax/libs/angularjs/1.6.4/angular.min.js"></script>
<div ng-app="demo" ng-controller="Demo as vm">
<hr/>
<input type="text" name="country" list="countryname" ng-model='vm.selectedCountry' ng-change="vm.countryChanged(vm.selectedCountry)">
<datalist id="countryname">
<option ng-repeat="country in vm.countries track by country.name" value={{::country.name}}></option>
</datalist>
<hr/>
{{vm.selectedCountry}}
</div>
是你能解決這個問題? –