【发布时间】:2015-11-18 14:50:50
【问题描述】:
我有这个控制器。每当我尝试将我的 $scope.things 绑定到从服务器接收到的 JSON 时,我的视图都不会更新。事实上,如果我离开我的push(newThing) 并取消注释我对getAllThings() 的调用,我的视图将显示数据,并在不到一秒的时间内将其删除。
问题是:在服务器端(使用 Node 和 MongoDB 运行的摩根),我在将 json 对象传递给我的客户端之前打印出它,并且该对象是正确的,它确实具有最新创建的对象。
我愿意使用推送而不是向服务器发出另一个请求来获取数据,但我真的对这个话题感到不安。另一个有趣的事情是,我对insertThing() 的第二次、第三次和随后的调用将正确更新我的观点。让人感觉有点不知所措。如果需要,我可以提供更多代码。
控制器:
$scope.insertThing= function(newThing){
$scope.things.push(newThing);
$http.post('http://localhost:8080/things', newThing)
.then(function(res){
//$scope.getAllThings();
delete $scope.newThing;
}, function(res){
});
//$scope.getAllThings();
};
$scope.getAllThings = function(userDpt){
$http.post('http://localhost:1234/things/dpt/', {userDpt: userDpt})
.then(function(res){
$scope.things = res.data;
}, function(res){
});
};
带有 Mongoose 的节点服务器:
app.post('/things/dpt', function(req, res){
var department = req.body.dpt;
var things= {};
TicketModel.find({ fromDpt: department},
function(err,obj){
res.json(obj);
});
});
标记:
<tr ng-repeat="thing in things">
<td> {{ thing.toDpt}} </td>
<td> {{ thing.status }}</td>
<td> {{ thing.deadline }}</td>
<td><button class="btn close" data-ng-click="deleteThing(thing._id)">×</button></td>
</tr>
【问题讨论】:
-
在您的
getAllThings函数中,data.json来自哪里?我没有看到它在任何地方定义。 -
这听起来像是加载数据然后调用 insertThing 方法的顺序问题。很难用您提供的代码来判断。我们可以看到更多。
-
代码添加到问题中。
标签: javascript json angularjs node.js