Having an input with a $watch function that updates a search query in real time through AngularJS, I am encountering an issue. Despite setting the initial value of the model to empty, it automatically triggers the search and displays results.
My concern is how can I ensure that the search is triggered only when the user types something into the input field? I've attempted creating a function that activates the $watch on ng-click, but have had no success so far. I also tried using ng-init without luck. Perhaps implementing a condition within ng-repeat to only run if the name is not empty could work?
Do you have any ideas for a possible workaround?
Below is my JavaScript code:
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 = '';
}
Here's my HTML snippet:
<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>
If you want to view a working example, check out this JSFiddle.
I would greatly appreciate any assistance! Thank you, Eric