0

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.

2
  • are you using routing in your app? Commented Oct 17, 2016 at 9:28
  • Not right now, will be using it for another view though. Commented Oct 17, 2016 at 10:33

1 Answer 1

1

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.

Sign up to request clarification or add additional context in comments.

3 Comments

Hmm getting a syntax error in console and no text showing in the inputfield.
nvm, worked when $scope.q was set outside of searchData and query = $scope.q
Good to know that.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.