AngularJS Scope Doesn't Update After New Request -
i'm new angularjs still have been reading lot of material , started test out things learning. i'm trying write code uses service reaches last.fm api , returns list of similar artists. i'm returning result fine api , can see results if send them console. said, after 1 search subsequent searches don't update scope properly. code follows:
controller
.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; }); }; });
view
<form role="form"> <div class="form-group"> <label for="artist">search music artist , see similiar artists</label> <input type="text" name="artist" class="form-control" ng-model="artist" placeholder="type 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>
service
.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; } }; });
as said, when initial search result displays, subsequent searches don't update scope. tried $scope.$apply said running command. ideas?
in factory, define deferred. deferred resolved on first call getsimilar, not on each call (because factories singletons). furthermore, don't need deferred because $http returns promise itself. remove deferred initialization in factory, , return $http call in getsimilar. if need deferred, initalize inside getsimilar.
Comments
Post a Comment