简体   繁体   中英

Defining an empty value on ng-model in AngularJS

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

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