繁体   English   中英

如何在输入angularjs中放置响应

[英]How to place response in inputs angularjs

我想将收到的数据放入3个输入中。 我从节点服务器收到json响应,控制器应接收到响应并将其放入3个输入中。 我收到响应,但无法将其放入输入中

控制器:

$scope.edit = function(id, contact) {
console.log(id);
$http.get('/contactlist/' + id).then(function(response) {
  console.log(response);
  $scope.contact = response;
});
};  

服务器:

app.get('/contactlist/:id', function (req, res) {
 var id = req.params.id;
console.log(id);
   connection.query('SELECT * FROM contactlist WHERE id = ' + id, function (error, results, fields) {
   console.log(results);
   res.json(results);
   });
});

index.html:

<div class="input-field col s4">
    <input id="name" type="text" class="form" ng-model="contact.name">
    <label for="name">Nom</label>
    {{contact.name}}
</div>
<div class="input-field col s4">
    <input id="email" type="text" class="form" ng-model="contact.email">
    <label for="email">Email</label>
</div>
<div class="input-field col s4">
    <input id="number" type="text" class="form" ng-model="contact.number">
    <label for="number">Numéro</label>
</div>

在chrome上收到的响应: 来自chrome对象的响应

您的响应包含带有对象的数据数组。 data [0]具有联系对象。

$http.get('/contactlist/' + id).then(function(response) {  
  $scope.contact = response.data[0];
});

使用$ http服务时, then函数中的已解决对象包含完整响应。 响应对象不仅包含您的数据,还包含诸如statusCode和发送请求时使用的配置之类的属性。 因此,您要做的是:

$http.get('/contactlist/' + id).then(function(response) {
  console.log(response);
  $scope.contact = response.data;
});

请注意,使用response.data评分器不只是response 另外,请注意,在服务器端,您可能只想返回第一个结果-而不是结果数组:

app.get('/contactlist/:id', function (req, res) {
    var id = req.params.id;
    console.log(id);
    connection.query('SELECT * FROM contactlist WHERE id = ' + id, function (error, results, fields) {
        console.log(results);
        res.json(results[0]);
    });
});

由于您会收到联系人列表,因此建议您这样做:

$http.get('/contactlist/' + id).then(function(response) {
  console.log(response);
  $scope.contacts = response.data; //note the 's'
});

和在HTML

<div ng-repeat="contact in contacts">
    <div class="input-field col s4">
      <input id="name" type="text" class="form" ng-model="contact.name">
      <label for="name">Nom</label>
      {{contact.name}}
    </div>
    <div class="input-field col s4">
      <input id="email" type="text" class="form" ng-model="contact.email">
      <label for="email">Email</label>
    </div>
    <div class="input-field col s4">
      <input id="number" type="text" class="form" ng-model="contact.number">
      <label for="number">Numéro</label>
    </div>
</div>

暂无
暂无

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

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