我正在 MEAN 堆栈中创建一个基本网站,但我遇到了一些 ng-repeat 问题,它不会显示任何内容。奇怪的是,当我在另一个项目中执行类似的操作时,它显示没有任何问题。
这是该页面的 HTML :
<!-- POST.HTML -->
<div class="row" ng-app ="myapp">
<div class = "col-xs-6 col-xs-offset-6 col-sm-6 col-sm-offset-6 col-md-6 col-md-offset-6" ng-controller="postController as post">
<div class = "row">
<strong> Username: </strong>
<input type = "text" ng-model ="post.newPost.Author" class = "form-control" placeholder="Enter your username">
</div>
<div class = "row">
<strong> Content </strong>
<input type = "text" ng-model = "post.newPost.Content" class= "form-control" placeholder="Write a short text about your humor !">
</div>
<button ng-click = "post.Post()" > Post your message ! </button>
<div>
<h4> Posts </h4>
<li ng-repeat = "message in post.messages">
<blockquote>
<strong> Title : {{message._id}} </strong>
<!-- {{message.content}} -->
<!-- <cite class="clearfix">—{{message.author}}</cite> -->
</blockquote>
</li>
</div>
</div>
以及相关的脚本:
(function(){
angular.module("myapp")
.controller("postController", ["$http", function($http){
$http.get("/api/message/getAll/").then(function(response){
this.messages = response.data;
console.log(this.messages);
});
this.Post = function(){
console.log("Post() function called");
var newPost = this.newPost;
console.log(newPost);
$http.post("/api/message/post/", newPost)
.success(function(response){
this.messages.push(newPost);
})
}
}])
})();
我确信 Controller 在这个 html 页面中处于事件状态,因为我可以毫无问题地提交内容,并且我的后端没有任何问题(我可以使用 HTTP REST 客户端进行请求)。 此外,当我登录控制台 this.messages 时,我可以看到有正确的数据:
数据被记录了 3 次,因为我刷新页面的时间太多了。我确保数据选项卡的每个对象都有一个 _id 属性。 我真的没有看到这个问题,因为每个tuto似乎都做同样的事情。看起来 this.messages 在填充请求后立即丢失了数据。
有人知道发生了什么吗?
最佳答案
所以看起来您在路由中将post引用为controllerAs。 您将值插入错误的范围变量中。您应该使用专用的 $scope,以便可以更好地跟踪您的分配。以下应该有效。
(function(){
angular.module("myapp").controller("postController", ["$scope","$http", function($scope, $http){
$http.get("/api/message/getAll/").then(function(response){
$scope.messages = response.data;
console.log(this.messages);
});
this.Post = function(){
console.log("Post() function called");
var newPost = this.newPost;
console.log(newPost);
$http.post("/api/message/post/", newPost)
.success(function(response){
$scope.messages.push(newPost);
})
}
}])})();
关于javascript - 即使数据存在,ng-repeat 也不显示,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38203746/