简体   繁体   中英

use filter function using http request in angular

I am using typeahead of UI-bootstrap for search filter, now I am using data from controller but I want data from JSON using $http. But I am not able to take data from $http request in filter function.

current code

// Search Control
vm.searchCtrl = "";
var searchitems = [{
      "name": "Adventure",
      "category": "Activities"
    }, {
      "name": "Cycling",
      "category": "Activities"
    }, {
      "name": "Local guided tours",
      "category": "Activities"
    }, {
      "name": "Delux room",
      "category": "Accommodations"
    }, {
      "name": "Super Delux room",
      "category": "Accommodations"
    }, {
      "name": "Goa",
      "category": "Destinations"
    }, {
      "name": "Bengaluru",
      "category": "Destinations"
    }];

    vm.getSearchitems = function (search) {
        var filtered = filterFilter(searchitems, search);
        var results = _(filtered).groupBy('category').map(function (g) {
            g[0].firstInCategory = true;
            return g;
        }).flatten().value();

        return results;
    }

But Now I want like this

$http.get('../assets/data/search.json').then(function (response) {
    return vm.searchitems = response;
});
vm.getSearchitems = function (search) {
    var filtered = filterFilter(searchitems, search);
    var results = _(filtered).groupBy('category').map(function (g) {
        g[0].firstInCategory = true;
        return g;
    }).flatten().value();

    return results;
}

But "searchitems" are not getting.

You want to invoke your function only after you have the data from $http. So move your call to getSearchItems so it gets called from the $http.

$http.get('../assets/data/search.json').then(function (response) {
    return vm.getSearchitems(response);
});
vm.getSearchitems = function (search) {
  var filtered = filterFilter(searchitems, search);
  var results = _(filtered).groupBy('category').map(function (g) {
    g[0].firstInCategory = true;
    return g;
  }).flatten().value();
  return results;
}

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