我是 AngularJS 的新手,我一直在尝试制作一个简单的应用程序,从 API 获取数据,并且我需要在客户端浏览器上显示该数据。
我已经设法获取数据,并且可以使用 console.log
在 Controller 上访问它,但是当我尝试通过 Angular 表达式在 HTML 上显示该数据时,它什么也没有显示。数据写在控制台日志上,而不是写在 HTML 上,下面是我的 HTML 和 Controller 的代码:
HTML:
<body class="list-group" ng-controller="StoreController as store">
<header>
<h1 class="text-center">Learning Angular</h1>
<h2 class="text-center">– This is pretty fun –</h2>
</header>
<div class="sizeLimitter">
{{store.posts[0].title}}
</div>
</body>
Controller :
app.controller('StoreController', ['$sce', '$scope', '$http', function( $sce, $scope, $http ) {
this.products = gems; // Using on other parts and working as intended.
// urlPosts contains the original link, which i cannot share.
var trustedUrl = $sce.trustAsResourceUrl(urlPosts);
this.posts = $http.jsonp(trustedUrl, {jsonpCallbackParam: 'callback'})
.then(function(postsRecieved) {
this.posts = postsRecieved;
console.log(postsRecieved.data[0].title);
console.log(posts.data[0].title);
});
}]);
JSON 示例:
[
{
"userId": 1,
"id": 1,
"title": "sunt aut facere repellat provident occaecati excepturi optio reprehenderit",
"body": "quia et suscipit\nsuscipit recusandae consequuntur expedita et cum\nreprehenderit molestiae ut ut quas totam\nnostrum rerum est autem sunt rem eveniet architecto"
},
{
"userId": 1,
"id": 2,
"title": "qui est esse",
"body": "est rerum tempore vitae\nsequi sint nihil reprehenderit dolor beatae ea dolores neque\nfugiat blanditiis voluptate porro vel nihil molestiae ut reiciendis\nqui aperiam non debitis possimus qui neque nisi nulla"
}]
标题在控制台上打印两次,因此它适用于 postsRecieved.data[0].title
和 posts.data[0].title
。我在这里做错了什么以及如何修复它,以便数据可以显示在 html 上?
最佳答案
Controller 中很少有错误:
-
查询解析函数中的
this.posts
不是范围的posts
属性,因为this
在 Controller 中,this
在解析中 功能不同。因此,您应该使范围可用 通过在 Controller 中创建范围
变量来解析函数- 您的 View 需要
scope.posts
中的数据数组,而不是 http 结果对象。 因此,您应该将postsRecieved.data
放入posts
属性中。
这是完整的 Controller 代码:
app.controller('StoreController', ['$sce', '$scope', '$http', function( $sce, $scope, $http ) {
this.products = gems; // Using on other parts and working as intended.
//make scope available in .then(function)
var scope = this;
//initialize an empty array of posts. this is not nesessary, but good for code understanding
scope.posts = [];
// urlPosts contains the original link, which i cannot share.
var trustedUrl = $sce.trustAsResourceUrl(urlPosts);
this.posts = $http.jsonp(trustedUrl, {jsonpCallbackParam: 'callback'})
.then(function(postsRecieved) {
//put data into сorresponding scope's property
scope.posts = postsRecieved.data;
console.log(postsRecieved.data[0].title);
console.log(scope.posts.data[0].title);
});
}]);
关于javascript - 数据在 Controller 中可用,但在 html 中无法解析,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44336072/