[英]Javascript variable scope in a JS URI, or how to write page-scope objects?
[英]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/zh-CN/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
});
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.