繁体   English   中英

如何在不使用Angular和Node JS重新加载页面的情况下更改数据

[英]How to change data without reloading page with Angular and Node JS

客户资料:

accounts = [
    Account1 = {
        name: 'Dan', phone: 1775123, role: 'Client', email: 'none'
    },
    Account2 = {
        name: 'Messy', phone: 3564576, role: 'Client', email: 'none'
    },
    Account3 = {
        name: 'Sasha', phone: 34231234, role: 'Client', email: 'Sania@mail.ta'
    }
];

DOM:

<div  ng-repeat="account in accounts" >
    <table>
        <tr>
            <td><input type="checkbox" ng-change="Toggle(account.name)"/>{{ account.name }}</td>
        </tr>
    </table>
</div>

我只想弄清楚在不重新加载页面的情况下更改DOM中的数组数据的最佳方法是什么。 例如,我使用ng-repeat指令查看了一些数据。 我选择了所需的选项,并将其发送到NodeJS-> MongoDB。 现在,我想在同一位置获取此数据,而无需重新加载页面。

听起来这是一个非常典型的问题,但我一直在努力寻找解决方案。

只需更新控制器中的数据,Angular就会更新dom。 这是2方式数据绑定的一个小示例,我想这就是您想要的:

柱塞示例

在Toggle方法中,您将放入命中数据库并更改数据的服务:

 $scope.Toggle = function(idx, account){
      $scope.accounts[idx].name = account.name + " Edited";
      //replace above with whatever updates the account, ie, businessService.updateAccount(account);
 }

我假设您使用发布请求(即$ http.post(url,data))将数据发布到服务器和数据库。

在Angular中,所有Ajax调用都对成功方法做出承诺,因此,在成功方法中,向服务器发出get请求以检索您的数据,即:

$http.post(url, data)
.success(function(){
 $http.get(url)
 .success(function(data){
  updateAccounts(data) // a function to update your accounts array
 } 
})

在服务器端,您的节点服务器应侦听对上述get url的get请求,然后应使用回调在数据库中查询帐户:

app.get(url, function(req, res){
  // Query the database for accounts and send back result of query
  res.send(200, accounts);
})

希望有帮助!

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM