对于从MongoDB获取的数据,Ang-ng不起作用
我是网页开发新手。 如果这是一个愚蠢的问题,我为此道歉。 我的ng-repeat显示的不是从MongoDB中获取的JSON,但是当我传递一个本地的JSON的时候,它工作。 我一整天都在努力。 谁能告诉我哪里出了问题?
这里是我的Angular代码
(function(){ var app = angular.module('app', ['ngRoute']); app.controller('CommentController', ['$scope', '$http', function($scope, $http){ //I've tried 'this.comment', it still not work. //It works when I use a test local JSON'this.comment = [{Visitor: 123, Comment: 345, CreateDate: 879}, {Visitor: 123, Comment: 345, CreateDate: 879}] $scope.comment = $http({url: 'db-comments'}).success(function (comments) { //I've confirmed 'comments' is an array of the JSON objects which I want. return comments; }); }]); })();
这是我的HTML代码
<div id="home" class="container" ng-controller='CommentController as comments'> <div id="comment" ng-repeat="x in comments.comment"> <h2>{{x.Visitor}}</h2> <hr> <p>{{x.Comment}}<p> <span>{{x.CreateDate}}</span> <hr> </div> </div>
这里是我的node.js代码
router.get('/db-comments', function(req, res, next){ Comment.find(function(err, data){ if(err){ console.log('can not fetch the data') } res.send(data); }) });
提前致谢!
正如scottseeker指出的那样,您需要将http响应数据分配给您的variables,而不是承诺。
但是,因为您使用控制器作为语法,这不足以使您的示例工作。 您需要设置this.comment
而不是$scope.comment
。 起初,你可能想要写下如下的东西:
$http(...).success(function (comments) { this.comment = comments; // don't write that });
但请注意,callback中的关键字this与外部不一样。 所以,如果你使用控制器作为语法,习惯写var vm = this;
在你的控制器的开始,并在vm
设置你想绑定到视图的variables( vm
代表viewmodel )。 像那样:
app.controller('CommentController', ['$http', function ($http) { var vm = this; $http({url: 'db-comments'}).success(function (comments) { vm.comment = comments; }); }]);
作为一个方面说明,如果你没有给你的$http
调用设置特定的头文件,我会build议你使用简短的方法$http.get
。 这更可读:
$http.get('db-comments').success(...)
$ http返回一个promise,在'then'部分设置你的scopevariables。
例:
$http({url: 'db-comments'}) then(function(response) { $scope.comment = response.data. }, function(response) { console.log('error: ' + response.error); });
我真的不知道$ http服务如何在AngularJS上工作,但是我猜想它会返回一个promise吗?
虽然我不太熟悉承诺,但我build议你这样做:
(function() { var app = angular.module('app', ['ngRoute']); app.controller('CommentController', ['$scope', '$http', function($scope, $http) { $http({ url: 'db-comments' }).success(function(response) { // Bind the variable here $scope.comment = response.data; }); }]); })();
我希望这对你有用,如果没有,让我知道。 祝你好运!
- 如何使用Angular js&Node.js通过dynamic生成的字段将数据发布到mongodb
- 从angular度读取nodejs中的cookie
- 不知道如何使用meanjs限制路线
- 你如何截取一个angularjs应用程序的截图?
- 将使用loopback-component-passport的用户angular色设置为内置模型
- node.js和JS Frameworks可以使用ES6吗?
- Mean stack web应用程序的基于angular色的访问控制
- 试图链接到angularjs应用程序中的特定页面
- 使用Socket.io,Angular,JWTvalidation数据直到用户validation刷新后才可用