我正在尝试在 Angular 中创建一个简单的电影应用程序。我可以向 tmdb(电影数据库)api 发出 JSON 请求,并在我的主页上显示原始结果。但我的问题是,我似乎无法仅显示 JSON 请求中的电影标题。
examplecontroller.js.coffee
angular.module('app.exampleApp').controller('exampleCtrl', [
'$scope', '$http', function($scope, $http) {
var base = 'http://api.themoviedb.org/3';
var service = '/movie/popular';
var apiKey = 'a8f703963***065942cd8a28d7cadad4';
var callback = 'JSON_CALLBACK'; // provided by angular.js
var url = base + service + '?api_key=' + apiKey + '&callback=' + callback;
$scope.movieList = 'requesting...';
$http.jsonp(url).then(function(data, status) {
$scope.movieList = JSON.stringify(data);
console.log($scope.movieList)
},function(data, status) {
$scope.movieList = JSON.stringify(data);
});
}
]);
show.html.haml
#search{"ng-app" => "app.exampleApp"}
%div{"ng-controller" => "exampleCtrl"}
%div{"ng-repeat" => "movie in movieList track by $index"}
{{movie.title}}
当我检查 Chrome 中的元素时,我发现大约有 25.000 个 ng-repeat div。但都没有内容。
我一直在关注this教程(以及一些其他来源)和我不明白的是电影列表中的电影
。我知道 movielist 是整个 json 请求,但什么是 movie?
已解决
Controller
angular.module('app.exampleApp').controller('exampleCtrl', [
'$scope', '$http', function($scope, $http) {
var base = 'http://api.themoviedb.org/3';
var service = '/movie/popular';
var apiKey = 'a8f7039633f2065942cd8a28d7cadad4';
var callback = 'JSON_CALLBACK'; // provided by angular.js
var url = base + service + '?api_key=' + apiKey + '&callback=' + callback;
$scope.movieList = [];
$http.jsonp(url).
success(function (data, status, headers, config) {
if (status == 200) {
$scope.movieList = data.results;
console.log($scope.movieList)
} else {
console.error('Error happened while getting the movie list.')
}
}).
error(function (data, status, headers, config) {
console.error('Error happened while getting the movie list.')
});
}
]);
显示
%h1
Logo
%li
= link_to('Logout', destroy_user_session_path, :method => :delete)
#search{"ng-app" => "app.exampleApp"}
%div{"ng-controller" => "exampleCtrl"}
%div{"ng-repeat" => "movie in movieList"}
{{ movie.original_title }}
最佳答案
你的问题是你将返回到请求回调的javascript数组作为data
并使用 JSON.stringify()
将其转换为字符串.
然后当你将此字符串传递给ng-repeat
时它循环遍历该字符串中的每个字符。因此你有大量重复的 <div>
但由于每个都是包含一个字符的字符串,因此没有 title
要打印的字符串的属性
将数组直接传递到请求回调中的作用域变量。
更改:
$scope.movieList = JSON.stringify(data);
致:
$scope.movieList = data;
JSON 是一种字符串数据格式。当$http
接收到该字符串响应后,它会在内部将其解析为 JavaScript 对象/数组。您不需要自己改造它
关于javascript - ng-repeat 不列出电影标题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31788382/