2013-10-29 33 views
1

我在查询数据的YouTube API后遇到问题。这个问题在这个jsfiddle中复制,以防你想尝试它jsfiddle.net/YBvQJ/4/AngularJS不会更新从承诺返回的数组

问题如下:第一次搜索结果显示正确。但是,如果我执行第二次搜索,即使搜索已正确执行,结果也不会在视图中更新。

我有一个服务,使用$ http调用youtube API来执行给定参数的搜索。返回值是一个承诺:

.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'] 
]) 

该服务在控制器中使用这样的:

.controller('SearchCtrl', ['$log', '$scope', 'youTubeSearchService' 
    , ($log, $scope, youTubeSearchService) -> 
     $scope.search = -> 
     $scope.results = youTubeSearchService.search($scope.query) 
    ]) 

的数据视图中使用这样的:

<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> 

我有将日志调用放入服务中以显示youtube API返回一个新数组。

我认为这个问题可能与范围没有在视图中更新有关。不应该这样,因为承诺会调用$ digest循环,ng-click指令也会这样。

帮助将不胜感激!先谢谢你。

回答

3

您的搜索正在返回服务承诺。因此,您将$scope.results设置为承诺。

$scope.results = youTubeSearchService.search($scope.query) 

相反,你应该处理的承诺,并设置结果:

youTubeSearchService.search($scope.query).then(function(results) { 

    $scope.results = results;  
}, function(error) { 

    $scope.error = error; 
}); 

在CoffeeScript的:

youTubeSearchService.search($scope.query).then ((results) -> 
    $scope.results = results 
), (error) -> 
    $scope.error = error 
+1

加入咖啡为你 – jcollum

+0

@jcollum谢谢! –