I'm new to angular, and I'm beginning to struggle up that learning curve.
I'm working my way through a FreeCodeCamp Zipline to make a wikipedia search application. One of the features needed is a live search with article title suggestions, but I can't seem to make it work.
I've created a factory to make the wiki API call. The factory will only work once, and not update when any changes are made to the search field. I assume it's not working because the factory isn't being called when changes have been made to the input field, but everything I've tried to fix that doesn't seem to work.
HTML
<section id="container" ng-app="wikiSearch" ng-controller="searchPanel" class="center">
<h1>Wikipedia Viewer</h1>
<input id="search" type="text" placeholder="search" ng-model="searchTerm" ng-model-options="{debounce: 300}"/>
<section id="results"><a href="#" target="_blank" class="wiki-entry"> </a>
<!-- test code-->
<div>{{searchTerm}}</div>
<div>{{titleSearch}}</div>
</section>
</section>
Javascript
var app = angular.module('wikiSearch', []);
app.controller('searchPanel', [ '$scope', 'API', function ($scope, API) {
$scope.searchTerm = 'einstein';
$scope.titleSearch = {};
$scope.searchResults = {};
var api_base = "https://en.wikipedia.org/w/api.php?";
var fullParams = "format=json&action=query&generator=search&gsrnamespace=0&gsrlimit=30&prop=extracts&exintro&explaintext&exsentences=2&exlimit=max&gsrsearch="
//var titles = "format=json&action=query&generator=search&gsrnamespace=0&gsrlimit=8&gsrsearch="
var callback = "&callback=JSON_CALLBACK"
API.search(api_base + fullParams + $scope.searchTerm + callback).success(function (data) {
$scope.titleSearch = data;
});
}]);
app.factory('API', [ '$http', function ($http) {
return {
search: function(targetUrl) {
console.log(targetUrl);
return $http.jsonp(targetUrl);
}
}
}]);
Here is the original codepen to look at: Codepen Project
You can see that any changes to the search field do not yield any changes in the returned json data. The factory is being called only once.
I don't have a great understanding of how angular works, but my assumption was that the factory would get updated in the scope with every change made to the input field. Obviously, I'm wrong, but I'd love to know exactly why, and how to fix it.
Issue with your code is that your're not firing API call on change of your search input. You need to listen for change
event on your text field and fire the API call like below.
HTML
<input id="search" type="text" ng-change="update()" placeholder="search"
ng-model="searchTerm" ng-model-options="{debounce: 300}" />
Controller
$scope.update = function(){
API.search(api_base + fullParams + $scope.searchTerm +callback)
.success(function (data) {
$scope.titleSearch = data;
});
}
Here's your updated CodePen fork with above changes.