[英]Angular ng-repeat doesn't work with data fetched from mongodb
我是Web開發的新手。 如果這是一個愚蠢的問題,我對此表示歉意。 我的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);
})
});
提前致謝!
$ http返回一個Promise,在“ then”部分中設置作用域變量。
例:
$http({url: 'db-comments'})
then(function(response) {
$scope.comment = response.data.
}, function(response) {
console.log('error: ' + response.error);
});
正如scottseeker所指出的那樣,您需要將http響應數據分配給變量,而不是promise。
但是,由於您使用控制器作為語法,因此不足以使示例正常工作。 您需要設置this.comment
而不是$scope.comment
。 首先,您可能需要編寫如下內容:
$http(...).success(function (comments) {
this.comment = comments; // don't write that
});
但要注意的是,關鍵字this
在回調中並未提及同一這是外面。 因此,如果您使用控制器作為語法,請養成寫var vm = this;
的習慣var vm = this;
在控制器的開頭,在vm
內設置要綁定到視圖的變量( vm
代表viewmodel )。 像那樣:
app.controller('CommentController', ['$http', function ($http) {
var vm = this;
$http({url: 'db-comments'}).success(function (comments) {
vm.comment = comments;
});
}]);
附帶說明一下,如果您沒有為$http
調用設置特定的標頭,建議您使用簡短方法$http.get
。 更具可讀性:
$http.get('db-comments').success(...)
我真的不知道$ http服務如何在AngularJS上工作,但是我猜想它會返回一個承諾嗎?
盡管我對諾言並不十分熟悉,但我建議您采用這種方式:
(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;
});
}]);
})();
我希望這對您有用,如果沒有,請告訴我。 祝好運!
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.