Вопрос

I've an input with a $watch that updates a search query in real time, all using AngularJS. My problem is that even having defined the initial value of the model as empty, it triggers the search and displays results by default.

So my question is, aiming to have an empty value by default, is there some way to actually trigger the search only when the user types something into the input? I've tried creating a function that triggers the $watch on ng-click, but so far no luck, same with ng-init. Maybe creating a condition on the ng-repeat making it run only if name != ''?

Any idea about a possible workaround?

Here's my JS:

function Ctrl($scope, $http) {
var get_results = function(name) {
        $http.get('http://api.discogs.com/database/search?type=artist&q='+ name +'&page=1&per_page=30').
    success(function(data3) {
        $scope.results = data3.results;
    });
}
$scope.$watch('name', get_results, true);
$scope.name = '';

}

My HTML:

<div ng-controller="Ctrl">
  <h1>Search Artist</h1>
  <input type="text" ng-model="name"/>
  <ul>
    <li ng-repeat="result in results">{{result.title}}</li>
  </ul>
</div>   

And a working JSFiddle.

Any help would be highly appreciated! Thanks, Eric

Это было полезно?

Решение

Use if condition inside get_results function to check weather the name is empty or not and do the request when it is non-empty string.

var get_results = function(name) {
  if (name) {
    $http.get('http://api.discogs.com/database/search?type=artist&q='+ name +'&page=1&per_page=30').
       success(function(data3) {
         $scope.results = data3.results;
    });
  }
}

JSFiddle

Лицензировано под: CC-BY-SA с атрибуция
Не связан с StackOverflow
scroll top