【问题标题】:Why doesn't this two way data binding work?为什么这两种方式的数据绑定不起作用?
【发布时间】: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)">&times;</button></td>
</tr> 

【问题讨论】:

  • 在您的getAllThings 函数中,data.json 来自哪里?我没有看到它在任何地方定义。
  • 这听起来像是加载数据然后调用 insertThing 方法的顺序问题。很难用您提供的代码来判断。我们可以看到更多。
  • 代码添加到问题中。

标签: javascript json angularjs node.js


【解决方案1】:

嗯,这是很久以前的事了。

所有这些代码都已完全重构。问题在于 JavaScript 的异步行为。有时,getAllThings() 函数会在删除行之前完成,而新获取的数据会在收到后消失。

解决这个问题的方法是在http请求之后再添加一个回调。

【讨论】:

    猜你喜欢
    • 2017-04-06
    • 2021-02-06
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-10-03
    • 1970-01-01
    • 2013-08-15
    相关资源
    最近更新 更多