简体   繁体   中英

AngularJS autocomplete from web service

I'm using REST Countries web service and I want to have an autocomplete feature when user is starting to type in input field, and when some country was selected to display an info about it. Want to do it with factories or maybe a directive, don't know what solution is the best Here is what I have for now:

REST service link: https://restcountries.eu/

HTML:

<div class="container" ng-controller="CountriesController">
    <h3 id="title">Countries Database</h3>
    <input type="text" id="countrySearch" ng-model="selected" typeahead="country for country in countries | limitTo:8" />

    <ng-view></ng-view>
</div>

Template:

<div ng-controller="CountriesController">
<ul>
    <li ng-repeat="country in countries" id="countryInfo">
        <p><b>Country:</b> {{country.name}}</p>
        <p><b>Native Name:</b> {{country.nativeName}}</p>
        <p><b>Capital:</b> {{country.capital}}</p>
        <p><b>Region:</b> {{country.region}}</p>
        <p><b>Subregion:</b> {{country.subregion}}</p>
        <p><b>Borders:</b> {{borders}}</p>
        <p><b>Languages:</b> {{languages}}</p>
        <p><b>Population:</b> {{country.population}} people</p>
        <p><b>Area:</b> {{country.area}} sq.km</p>
        <p><b>Currencies:</b> {{currencies}}</p>
        <p><b>Timezones:</b> {{timezones}}</p>
        <p><b>Calling Code:</b> +{{callingCodes}}</p>
    </li>
</ul>

Controller:

app.controller('CountriesController', function ($scope, CountriesFactory) {

CountriesFactory.getCountry().then(function (data) {
    $scope.selected = undefined;
    $scope.countries = data;
    console.log($scope.countries);

    $scope.timezones = data[0].timezones.toString();
    $scope.languages = data[0].languages.toString();
    $scope.currencies = data[0].currencies.toString();
    $scope.borders = data[0].borders.toString();
    $scope.callingCodes = data[0].callingCodes.toString();
});

});

Factory:

app.factory('CountriesFactory', function ($http, $q) {
return {
    getCountry: function () {
        var input = $('#countrySearch').val();
        var request = 'https://restcountries.eu/rest/v1/name/';
        var url = request + input;

        return $http.get(url);
    }
}
});

Checkout bootstrap UI's autocomplete widget

Look at the source code to see how it is implemented

If you go to rest countries here you can see the example how to get the rest countries like: example The restcountries.eu/rest/v1/name is not working because they don't expose that page.

Try to make sure you have something into input. Try to check if

$('#countrySearch').val();

is not null or empty first.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM