2014-03-24 47 views
0

我对angularJS仍然很陌生,但一直在阅读大量资料,最后开始测试我正在学习的东西。我目前正在尝试编写使用达到last.FM API的服务的代码,并返回类似艺术家的列表。我从API返回的结果很好,如果我将它们发送到控制台,可以看到结果。也就是说,在我执行一次搜索后,所有后续搜索都不会正确更新范围。我的代码如下:AngularJS示波器在新请求后不会更新

控制器

.controller('lastFMController', function($scope, lastFM) { 
    $scope.search = function(artist) { 
     lastFM.getSimilar(artist).then(function(result) { 
      $scope.artists = result.similarartists.artist; 
     }, function(error) { 
      $scope.error = error; 
     }); 
    }; 
}); 

查看

<form role="form"> 
<div class="form-group"> 
    <label for="artist">search for a music artist and see similiar artists</label> 
    <input type="text" name="artist" class="form-control" ng-model="artist" placeholder="type an artist's name"> 
</div> 
<button type="submit" class="btn btn-default" ng-click="search(artist)">search</button> 
</form> 

<hr ng-if="artists" /> 

<div class="row"> 
    <div class="col-sm-6 col-md-4 fade in" ng-repeat="artist in artists"> 
     <h3>{{ artist.name }}</h3> 
     <p><a target="_blank" href="http://{{ artist.url }}" class="btn btn-primary" role="button">view on last.fm</a></p> 
    </div> 
</div> 

服务

.factory('lastFM', function($q, $http) { 
    var deferred = $q.defer(), 
     self = this, 
     apiKey = "KEY"; 

    return { 
     getSimilar: function(artist) { 
      this.url = 'http://ws.audioscrobbler.com/2.0/?method=artist.getsimilar&artist=' + artist + '&api_key=' + apiKey + '&format=json&autocorrect=1'; 
      this.error = false; 

      $http.get(this.url).success(function(data) { 
       if (data.error) { 
        deferred.reject(data.error.message); 
       } 
       else if (!angular.isUndefined(data.similarartists) && angular.isObject(data.similarartists.artist)) { 
       deferred.resolve(data); 
       } 
       else { 
        deferred.reject('Something went wrong'); 
       } 
      }); 

      return deferred.promise; 
     } 
    }; 
}); 

正如我所说的,W如果我进行初步搜索,我会得到一个显示的结果,但所有后续搜索都不会更新范围。我尝试了$ scope。$ apply,但它表示它已经在运行该命令。有任何想法吗?

回答

1

在您的工厂中,您定义了一个延期。延迟的第一次调用getSimilar时解析,而不是每次调用(因为工厂是单例)。此外,您不需要延期,因为$ http本身会返回一个承诺。因此,删除工厂中的延迟初始化,并在getSimilar中返回$ http调用。如果您确实需要额外的延期,请在getSimilar中初始化它。

+0

谢谢,这是有道理的。我没有意识到一旦解决工厂问题就会永久解决。现在所有的作品。 – dansackett

相关问题