我在尝试在 AngularJS 中显示对象集合时遇到问题。
ng-repeat 仅显示项目,但控制台中数据为空。我正确获取了 JSON 数据,并成功捕获了 api 的范围项。 在我看来,它只是在底部显示一个灰色条,数据打印在底部而不是 ng-repeat 上。
<div ng-controller="userController">
<div class="container">
<div class="row">
<div class="col-md-12">
<div class="panel panel-default">
<div class="panel-heading">
<h2>Users</h2>
</div>
<div class="panel-body">
<div class="user">
<div class="form-group">
<input ng-model="user.name" type="text" placeholder="User Name" class="form-control">
</div>
<div class="form-group">
<input ng-model="user.email" type="email" placeholder="User Email " class="form-control">
</div>
<div class="form-group">
<input ng-model="user.password" type="password" placeholder="Set Your Password" class="form-control" >
</div>
<div class="form-group">
<select ng-model="user.admin" name="" id="" class="form-control">
<option value="">Admin</option>
</select>
</div>
<div class="form-group">
<button ng-click="createUser(user)" class="btn btn-success">Create User</button>
</div>
</div>
</div>
</div>
</div>
</div>
</div>
<div class="container">
<div class="row">
<div class="col-md-12">
<div class="panel panel-default">
<div class="panel-heading">
<h3>All Users</h3>
</div>
<div class="panel-body">
<table class="table">
<thead>
<tr>
<th>id</th>
<th>Name</th>
<th>Email</th>
<th>Options</th>
</tr>
</thead>
<tbody>
<tr ng-repeat="user in users">
<td>{{ user.id }}</td>
<td>{{ user.name }}</td>
</tr>
</tbody>
</table>
</div>
</div>
</div>
</div>
</div>
{{users}}
请参阅 this image和 this one .
(function() {
'use strict';
angular
.module('anicasioApp')
.controller('userController', userController);
function userController($scope, $http){
$scope.createUser = createUser;
$scope.users = [];
function init(){
getAllUsers();
}
init();
function getAllUsers() {
$http.get('/api/userpost/')
.then(function(users) {
$scope.users = users;
console.log($scope.users);
})
.catch(function(err) {
err.sendStatus(400);
})
}
function createUser(users) {
console.log(users);
$http.post('/api/userpost/', users)
.then(getAllUsers);
console.log(users);
}
}
})();
// Users Model
function getAllUsers(req, res) {
UserModel
.find()
.then(function(users) {
res.json(users);
}),
function(err){
res.sendStatus(400);
}
}
最佳答案
@Andriy 是对的...
在你的函数中
function getAllUsers() {
$http.get('/api/userpost/')
.then(function(users) { // var 'users' is actually your server 'response'
$scope.users = users;
console.log($scope.users);
})
.catch(function(err) {
err.sendStatus(400);
})
}
你不应该这样做$scope.users = users;
,而是这样做:$scope.users = users.data;
因为两者之间的区别不同我们处理 promise 的方式:
当您使用时
$http.get('/myserviceurl').
success(data){//mycode}
您正在获取服务器返回的标准参数response.data
...
但如果你这样做了(这就是你正在做的事情!)
$http.get('/myserviceurl').
then(response){//mycode}
...您得到的是来自服务器的响应
,其中包含带有您想要的数据的data
变量。
关于javascript - AngularJS 不显示 ng-repeat,只显示一个空列表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40954275/