javascript - 下拉加上angularjs和bootstrap中的输入文本

标签 javascript html angularjs twitter-bootstrap-3

我想要一个既可以作为下拉菜单又可以作为输入文本字段的字段,用户可以从下拉菜单中选择值或输入文本。

我发现了类似的东西,下面是相同的代码片段。

<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从服务器获取选项列表,然后使用 ngRepeatoption 元素上填充模板中的选项列表。请参见下面的示例:

(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/

相关文章:

javascript - 是否可以使用 jQuery 突出显示段落标记内的特定行

php - HTML/PHP - 我需要创建一个 10 x 10 的网格,其中包含 100 个框,每个框都需要可选择

javascript - ng-show/hide 延迟图像动画

angularjs - 如何在 CSP 中使用 Angular Material ?

javascript - 在 Javascript 中操作 DOM 的简单方法

javascript - 使用 onsubmit 或 onclick 打开窗口基于使用输入

javascript - 如何使用jquery获取一行中的列

html - 防止输入将包含的 div 推到同一行中其他 div 的下方

javascript - 如何在 Angular JS 中连接 localStorage 中的对象

javascript - JWT 身份验证和授权