【问题标题】:Unable to print the data fetched by the controller.js无法打印 controller.js 获取的数据
【发布时间】:2017-08-01 05:45:19
【问题描述】:

我是新手,我正在尝试制作一个虚拟联系人列表。 我已经打印了从 mongodb 获取数据的日志,我可以在浏览器控制台中看到正确的数据,但是当我尝试在 html 文件中打印它时它不显示。

这里是sn-ps:

controller.js

var myApp = angular.module('myApp', []);
myApp.controller('AppCtrl', ['$scope', '$http', function($scope, $http){
$http.get('/contactlist').then(function(response){
console.log("I got the response");
console.log(response); //able to see correct data is fetched in the browser console
$scope.contactlist=response;
});
}])

我尝试打印此数据的表格:

<tbody>
    <tr ng-repeat="Contact in contactlist">
        <td>{{Contact.name}}</td>
        <td>{{Contact.email}}</td>
        <td>{{Contact.number}}</td>
    </tr>
</tbody>

请解释发生了什么问题。

控制台中显示的响应:

【问题讨论】:

  • 控制台有错误吗?
  • 联系人列表是列表吗?你能粘贴你的回复吗?
  • 控制台中没有显示错误
  • 你需要使用回调函数来获取这些数据

标签: javascript mongodb mean-stack meanjs


【解决方案1】:

JavaScript 始终是同步的。所以这里发生了什么,$scope.contactlist=response;$http.get('/contactlist')... 完成之前执行。这意味着,$scope.contactlist 未定义。为了解决这个问题, 我建议使用Service

var myApp = angular.module('myApp', []);
myApp.controller('AppCtrl', ['$scope', 'dataService', function($scope, dataService){

  dataService.contactLists(function(response) {
    console.log(response.data);
    $scope.contactlist=response.data;
  });

});
}])

myApp.service('dataService', function($http) {
    this.contactLists = function(callback){
   $http.get('/contactlist').then(callback)
  }
});

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2016-05-20
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-08-22
    • 1970-01-01
    • 2012-07-15
    • 1970-01-01
    相关资源
    最近更新 更多