[英]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-repeat列出它们,如下所示:
<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,而是“未来”对象。 实际上,这意味着取决于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'])
我不知道为什么您的代码无法正常工作,但以下内容应该可以正常工作。 $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); });
}
您应该从$ get http调用的成功函数中为$ scope.messages变量分配一个值。 这样的事情:(请参阅punker )
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.myRender = false;
然后拨打电话...成功之后:
$scope.myRender = true;
和html使用ng-if="myRender" ng-model="myModel"
祝好运!
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.