我想要一个既可以作为下拉菜单又可以作为输入文本字段的字段,用户可以从下拉菜单中选择值或输入文本。
我发现了类似的东西,下面是相同的代码片段。
<input type="text" name="city" list="cityname">
<datalist id="cityname">
<option value="Boston">
<option value="Cambridge">
</datalist>
如何以 Angular 使用数据列表并从 rest api 调用中获取选项?
请参阅以下链接了解数据列表普通工作模型 --> https://www.w3schools.com/tags/tryit.asp?filename=tryhtml5_datalist
最佳答案
使用$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>
关于javascript - 下拉加上angularjs和bootstrap中的输入文本,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46037590/