Search code examples
angularjsangularjs-scopeangularjs-ng-model

Angular.js searching API URL with user input


I am trying to search for an URL using user input. Currently I can search through textinput where the first three letters of a city is in the URL. For example; if I search for "sto" the URL is "find?q=sto&type"; sto being the three letters in this case.

controllers.controller('mainCtrl', function($rootScope, $http) {
  var url = "http://api.openweathermap.org/data/2.5/find?q=sto&type=like";
  var id = "&appid=d436c04d23a5a44329eb8255190a84be&callback=JSON_CALLBACK";
  var query = $rootScope.q = "";
  var apiCall = url += query += id;
  var promise = $http.jsonp(apiCall)
  promise.success(function(data){
      $rootScope.data = data;
      console.log($rootScope.data)
  });
});

<input type="text" data-ng-model="q"></input>

Is there a way to not be limited to the three letters ""find?q=sto&type" in the URL? Enabling searches on user input on any letters.


Solution

  • You can use ng-change directive and make dynamic API call for every single user input.

    Consider the following change to your code.

    <input type="text" data-ng-model="q" ng-change="searchData()"></input>
    
    
    controllers.controller('mainCtrl', function($rootScope, $http) {
    
    $scope.searchData = function(){
      var url="http://api.openweathermap.org/data/2.5/find?q="+$scope.q+"&type=like";
      var id = "&appid=d436c04d23a5a44329eb8255190a84be&callback=JSON_CALLBACK";
      var query = $rootScope.q = "";
      var apiCall = url += query += id;
      var promise = $http.jsonp(apiCall)
      promise.success(function(data){
        $rootScope.data = data;
        console.log($rootScope.data)
      });
    }
    
    });
    

    If you want to have a limitation for minimum characters, just check for the length of $scope.q before making an API call.

    You can also use $watch on the scope variable and achieve this.