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

Angular JS: Write array of objects to $scope variable

我正在做一个应用程序,它从 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
    });