Angular.js不显示从$http.get检索到的对象数组
Angular.js not displaying array of objects retrieved from $http.get
我是angular.js的新手,我正在努力了解如何使用$http函数,如$http.get
和$http.post
。
我有一个非常简单的应用程序,通过Java rest服务从MySQL数据库检索消息。返回的数据看起来像:
[
{id:1, content:"Hello World!"},
{id:2, content:"Testing 1, 2, 3..."},
{id:3, content:"I am from the database"}
]
我正试图使用类似的ng重复来列出它们:
<div ng-controller="MessageController">
<ul>
<li ng-repeat="m in messages">{{m.content}}</li>
</ul>
</div>
然后我的控制器看起来是这样的:
function MessageController($scope, $http) {
$scope.getAll = function(callback) {
$http.get('/messages').success(function(response) { callback(response); });
}
$scope.messages = $scope.getAll(function(data) { return JSON.stringify(data); });
}
我看到调用正确地返回了一组消息对象,我可以从回调函数中将它们打印到控制台,但由于某种原因,它们没有显示在ng-repeat
中。当我手动创建消息列表时,我可以让它发挥作用,但当我介绍$http.get
时,它停止了工作。
我是不是错过了什么?
编辑:我使用的是angular.js版本1.2.19
根据AngularJS 1.2版本,数组不再从Promise中展开(默认情况下)(请参阅迁移说明)。我看到它仍然适用于Objects
,但根据文档,您也不应该依赖它。
相反,您应该为此使用$resource。资源不再返回Promises,而是返回"future"对象。在实践中,这意味着依赖于REST调用的空对象或数组,一旦REST调用解析,它就会填充自己(示例)。
在您的情况下,它将类似于以下(伪):
function MessageController($scope, $resource) {
var resource = $resource('/messages');
$scope.messages = resource.query(function (data) {
return JSON.stringify(data); // is this really necessary, though?
});
// $scope.messages = resource.query(); // should be enough
}
为此,您需要ngResource模块依赖项(别忘了在index.html中包含angular-resource.js):
var app = angular.module('myApp', ['ngResource'])
您应该在$get-http调用的success函数中为$scope.messages变量赋值。类似这样的东西:(见plunker)
var app = angular.module('plunker', []);
app.controller('MessageController', function($scope, $http) {
$scope.getAll = function() {
$http.get('data.json').success(function(response) {
$scope.messages = response;
});
}
$scope.getAll();
});
我不知道为什么你的代码不起作用,但以下应该起作用。$scope
在回调中被更新。
function MessageController($scope, $http) {
$scope.getAll = function(callback) {
$http.get('/messages').success(function(response) { callback(response); });
}
$scope.getAll(function(data) { $scope.messages = JSON.stringify(data); });
}
我用解决
-
调用后,初始化变量
$scope.myRender = false;
-
然后打电话。。。之后和成功:
$scope.myRender = true;
html使用ng-if="myRender" ng-model="myModel"
祝你好运!
- 如何从类关系中检索对象列表
- 检索对象项的路径
- 正在根据ID从数组中检索对象
- 以文本形式检索对象元素中的SVG Dom
- AJAX来检索对象并将其存储在变量中
- 如何在帮助程序或事件中检索对象的内部_id
- 如何在 ydn-db 中检索对象的排序列表
- Javascript - 检索对象属性路径
- 从具有特定参数的数组中检索对象
- 如何从jsonString中检索对象
- 检索对象自己的标记
- 从URL检索对象/资源
- 如何从Google Apps脚本项目属性中存储和检索对象
- 如何从GTM数据层中检索对象
- JQueryAJAX检索对象数组
- 正在检索对象中嵌套的值
- 使用PHP从JSON中检索对象
- 如何从具有给定(键、值)对的长列表中检索对象
- 使用承诺从 mongo db 检索对象时出错
- 在树状的angularjs模型中检索对象