我正在尝试通过从数据库中获取数据来更新数据列表。每次我添加一个数据,它不会更新 View , View 只会在我刷新页面时更新。我通过使用 $scope.apply 并重新排列我的代码的位置尝试了一些解决方案,这些没有什么区别。我在这里错过了什么?以下是我的代码:
JS
//posting post
$scope.post = function(){
$http.post('/post',$scope.post_detail)
.success(function(response){
$scope.render();
});
}
//getting post
$scope.render = function(){
$http.get('/post')
.success(function(response){
$scope.renderPost(response);
});
}
//view post
$scope.renderPost = function(response){
$scope.posts = response;
}
$scope.remove_post = function(id){
$http.delete('/post/'+id).success(function(response){
$scope.render();
});
}
$scope.render();
HTML
<div class="jumbotron text-center" ng-controller="DashboardCtrl">
<h1>{{title}}</h1>
<input type="text" ng-model="post_detail.title" />
<input type="text" ng-model="post_detail.border_color" />
<button ng-click="post(post_detail)">Post</button>
</div>
<div ng-repeat="post in posts">
<p>{{post.title}}</p>
<button ng-click="remove_post(post._id)">Remove</button>
</div>
注意:删除按钮在这里有效
最佳答案
因为 ng-repeat 在 DashboardCtrl 范围之外。我猜你有 DashboardCtrl div 和 posts div 的父 Controller ,你在父 Controller 中启动 $scope.posts。
当你有
$scope.renderPost = function(response){
$scope.posts = response;
}
它更新子范围内的帖子。您可能需要执行以下操作:
$scope.$parent.posts = response;
或者将 ng-repeat div 移动到 <div class="jumbotron text-center" ng-controller="DashboardCtrl">...</div>
中
关于javascript - AngularJS - 添加数据时 ng-repeat 不更新,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31911588/