gpt4 book ai didi

javascript - 加载数据之前加载 Angular Controller

转载 作者:行者123 更新时间:2023-11-28 07:50:04 25 4
gpt4 key购买 nike

我正在编写一个简单的应用程序,可以从 API 加载电影信息。加载后,我尝试使用 Angular 在简单的 ListView 中显示电影。我正确加载了电影,但似乎在填充电影数组之前创建了 Angular Controller 并将电影数组发送到 View 。我不确定如何解决这个问题。

var movieList = [];
var app = angular.module('top250', []);

// immediately make a call to the server to get data (array of movies from text file)
$.post('/', {}, function(data) {
init(data);
});

app.controller('MovieController', function() {
// should be setting this.movies to an array of 250 movies
this.movies = movieList;
});

function init(data) {
// cycle through array, use title to retrieve movie object, add to array to be sent to view

$.each(data, function(index, value) {
var title = value.split(' (')[0];
title = title.split(' ').join('+');
var url = 'http://www.omdbapi.com/?t=' + title + '&y=&plot=short&r=json';

$.getJSON(url, function(data) {
console.log('in get json', data);
var movieObj = data;
storeMovie(movieObj);
});

});
}

function storeMovie(movieObj) {
movieList.push(movieObj);
}

还有我的 HTML(尽管我确信这不是问题:

<body ng-controller="MovieController as MovieDB">

<div class="row">
<div class="large-12 columns">
<h1>IMDB Top 250 List</h1>
</div>
</div>

<div class="row">
<div class="large-12 columns" id="movie-list">

<div class="list-group-item" ng-repeat="movie in MovieDB.movies">
<h3>{{movie.Title}} <em class="pull-right">{{movie.Plot}}</em></h3>


</div>
</div>

<script src="js/foundation.min.js"></script>
<script>
$(document).foundation();
</script>
</body>

最佳答案

首先,我将您的 ajax 调用转换为 Angular 工厂:

app.factory('MoviesService', function($http, $q) {

function getMovie(value) {
var title = value.split(' (')[0];
title = title.split(' ').join('+');
var url = 'http://www.omdbapi.com/?t=' + title + '&y=&plot=short&r=json';
return $http.get(url).then(function(res){ return res.data; });
}

return $http.post('/').then(function(res) {
return $q.all(res.data.map(getMovie));
});
});

然后我可以像这样使用它:

app.controller('MovieController', function(MoviesService) {

var self = this;

MoviesService.then(function(movies) {
self.movies = movies;
});
});

关于javascript - 加载数据之前加载 Angular Controller ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26951373/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com