I'm have an issue after querying youtube API for data. The problem is replicated in this jsfiddle in case you want to try it jsfiddle.net/YBvQJ/4/
The problem is as follows: the first time I search something the results are displayed correctly. But, if I perform a second search, the results will not be updated in the view, even though the search has been performed correctly.
I have a service that calls youtube API using $http to do the search given a parameter. The return value is a promise:
.service('youTubeSearchService', ['$log', '$http', '$q', ($log, $http, $q) ->
apiKey = 'myApiKey'
url = 'https://www.googleapis.com/youtube/v3/search'
deferred = $q.defer()
return service =
search: (query) ->
$http.get(url, params: {
key: apiKey
type: 'video'
maxResults: '6'
part: 'id,snippet'
fields: 'items/id,items/snippet/title'
q: query
})
.success (data) ->
$log.info "In success"
$log.info data
deferred.resolve data.items.map (item) ->
videoId: item.id.videoId
title: item.snippet.title
.error (data) ->
$log.info "In error"
$log.info data
deferred.reject data
return deferred.promise
])
.config(['$httpProvider', ($httpProvider) ->
# Disable this header or the youtube API won't work
delete $httpProvider.defaults.headers.common['X-Requested-With']
])
This service is used in the controller like this:
.controller('SearchCtrl', ['$log', '$scope', 'youTubeSearchService'
, ($log, $scope, youTubeSearchService) ->
$scope.search = ->
$scope.results = youTubeSearchService.search($scope.query)
])
The data is used in the view like this:
<input type="text" ng-model="query" value="ejemplo">
<button ng-click="search()">Search in YouTube</button>
<li ng-repeat="item in results">
<p><a target="blank" href="//www.youtube.com/watch?v={{item.videoId}}">
{{item.title}}
</a></p>
</li>
I have put log calls in the service to show that the youtube API gives back a new array.
I think the problem might have something to do with the scope not being updated in the view. Shouldn't it be, because the promise will call a $digest cycle, and so will the ng-click directive.
Help would be much appreciated! Thank you in advance.