Angular JS:将对象数组写入$scope变量



我正在做一个应用程序,它从iTunes获取API并将其显示在我的HTML中。但在 $scope.bands 变量中总是只写一个音符。

我的代码

<body>
<div ng-app="myApp" ng-controller="myCtrl">
    <ul>
        <li ng-repeat="band in bands">
            {{band.artist}}
        </li>
    </ul>
</div>
<script>
    let app = angular.module('myApp', []);
    app.controller('myCtrl', function($scope, $http) {
    $http.get(" https://itunes.apple.com/search?term=The+Beatles").then(function(response) {
  let jsonData = []; 
  for (let i = 0; i < response.data.resultCount; i++) {
    $scope.bands = [{
        artist:response.data.results[i].artistName,
        track:response.data.results[i].trackName,
        collection:response.data.results[i].collectionName,
        genre:response.data.results[i].primaryGenreName,
        image:response.data.results[i].artworkUrl100
    }];

  }
  }, function(response) {
  $scope.content = "ERROR:Something went wrong";});});

</script>

请解释一下,为什么它不能正常工作!

提前谢谢你

您尚未定义值 $scope.bands

有关详细信息,请查看范围文章:

https://docs.angularjs.org/guide/scope

您还需要推送到数组:

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/push

试试这个:

<body>
<div ng-app="myApp" ng-controller="myCtrl">
    <ul>
        <li ng-repeat="band in bands">
            {{band.artist}}
        </li>
    </ul>
</div>
<script>
    let app = angular.module('myApp', []);
    app.controller('myCtrl', function($scope, $http) {
    $http.get(" https://itunes.apple.com/search?term=The+Beatles").then(function(response) {
  let jsonData = []; 
  $scope.bands = [];
  for (let i = 0; i < response.data.resultCount; i++) {
    $scope.bands.push({
        artist:response.data.results[i].artistName,
        track:response.data.results[i].trackName,
        collection:response.data.results[i].collectionName,
        genre:response.data.results[i].primaryGenreName,
        image:response.data.results[i].artworkUrl100
    });

  }
  }, function(response) {
  $scope.content = "ERROR:Something went wrong";});});

</script>

您也可以稍微重构:

  for (let i = 0; i < response.data.resultCount; i++) {
    let currentData = response.data.results
    $scope.bands.push({
        artist:currentData[i].artistName,
        track:currentData[i].trackName,
        collection:currentData[i].collectionName,
        genre:currentData[i].primaryGenreName,
        image:currentData[i].artworkUrl100
    });

最新更新