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

时间:2018-03-13 20:55:47

标签: javascript arrays angularjs angularjs-ng-repeat

我正在做一个从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>

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

提前谢谢

1 个答案:

答案 0 :(得分:0)

你还没有定义价值$ 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
    });