【问题标题】:Angular JS: Write array of objects to $scope variableAngular JS:将对象数组写入 $scope 变量
【发布时间】:2018-03-14 05:07:32
【问题描述】:

我正在做一个应用程序,它从 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 = 每次循环迭代都会覆盖数组。在循环外声明$scope.bands = [],然后使用$scope.bands.push({});添加。

标签: javascript arrays angularjs angularjs-ng-repeat


【解决方案1】:

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

【讨论】:

  • @Vadim - 很高兴为您提供帮助 :-) 不要忘记接受答案
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2017-05-25
  • 2019-05-11
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2016-06-04
  • 1970-01-01
相关资源
最近更新 更多