Goutham Nithyananda
Goutham Nithyananda

Reputation: 939

Dropdown plus input Text in angularjs and bootstrap

I want to have a single field which acts as a drop down and also as a input text field , Where user can either select value from drop down or input a text.

I found something similar , below is the code snippet of the same.

<input type="text" name="city" list="cityname">
<datalist id="cityname">
  <option value="Boston">
  <option value="Cambridge">
</datalist>

How can use the datalist in angular and fetch the options from a rest api call?

refer the below link for working model of datalist plain -->https://www.w3schools.com/tags/tryit.asp?filename=tryhtml5_datalist

Upvotes: 3

Views: 4030

Answers (2)

Stanislav Kvitash
Stanislav Kvitash

Reputation: 4622

Use $http service to fetch the list of the options from the server and then use ngRepeat on option element to populate the list of the options in the template. See the example below:

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

Upvotes: 2

Cupkek05
Cupkek05

Reputation: 468

Did you try with ng-submit on form tag ?

Exemple :

<form ng-submit="submit()">

And on JS code :

        $scope.submit = function () {
        ///DO STUFF
    };

Upvotes: 0

Related Questions