저는 아직 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를 시도했지만, 이미 그 명령을 실행하고 있다고 말했습니다. 어떤 아이디어?
감사합니다. 일단 공장을 해결하면 영구적으로 해결된다는 것을 깨닫지 못했습니다. 모든 작품은 지금. – dansackett