简体   繁体   中英

How to populate md-autocomplete dropdown list?

I'm trying use md-autocomplete with $http(), I can see the values in the console, but I can't display the data returned from the api request to the autocomplete. I tried using the return keyword to return values stored in the JSON array.

      <md-autocomplete 
          md-autoselect=true
          placeholder="Search for films"
          md-items="item in querySearch(searchText)"
          md-item-text="item.title"
          md-min-length="2"
          md-search-text="searchText"
          md-selected-item="selectedItem">
        <md-item-template>
          <span class="films-title">
            <span md-highlight-flags="^i" md-highlight-text="searchText">
              {{item.title}}
            </span>
          </span>
        </md-item-template>
        <md-not-found>
          No match found.
        </md-not-found>
      </md-autocomplete>

The data I want to display is stored in a JSON array and the contents can be seen in the console:

'use strict';

filmApp.controller('SearchController',function ($scope, $http){
    $scope.results = {
      values: []
    };

    $scope.querySearch = function (query) {
     $http({
        url: 'https://api.themoviedb.org/3/search/movie?include_adult=false&page=1',
        method: 'GET',
        params: { 
                 'query': query,
                 'api_key': apiKey
        }
      }).success(function (data, status) {

            for (var i = 0; i < data.results.length; i++) {
        $scope.results.values.push({title: data.results[i].original_title});

                    console.log($scope.results.values);      
                  return $scope.results.values;

                }
                console.log("STATUS: "+status);

            }).error(function (error) {
                console.log("ERROR: "+error);
            });
        };
    });

querySearch method should return a promise & from the promise.then you should be returning a data. So in your case you used .success / .error callbacks(thought they are already deprecated) which is disallow promise to be return from your querySearch method

$scope.querySearch = function (query) {
  return $http.get('https://api.themoviedb.org/3/search/movie?include_adult=false&page=1', {
         params: { 
             'query': query,
             'api_key': apiKey
         }
  }).then(function (data, status) {
       var data= response.data;
       for (var i = 0; i < data.results.length; i++) {
           $scope.results.values.push({title: data.results[i].original_title});
           console.log($scope.results.values);      
       }
       return $scope.results.values;
    })
};

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