我是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"
祝你好运!