无法打印由controller.js获取的数据 [英] Unable to print the data fetched by the controller.js

查看:121
本文介绍了无法打印由controller.js获取的数据的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I am new to this and i am trying to make a dummy contact list. I have printed the log which fetches the data from mongodb and i can see the correct data in browser console,but when i try to print it in html file it doesn't display.

以下是摘要:

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;
});
}])

我尝试在其中打印此数据的表:

Table where i try to print this data:

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

请解释出了什么问题.

控制台中显示的响应:

Response shown in console:

推荐答案

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

JavaScript is always synchronous. So what is happening here, $scope.contactlist=response; is executing before $http.get('/contactlist')... completed. It means, $scope.contactlist undefined. To Solve this problem, I recommend to use 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)
  }
});

这篇关于无法打印由controller.js获取的数据的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆