javascript - AngularJS - 添加数据时 ng-repeat 不更新

标签 javascript angularjs angularjs-scope

我正在尝试通过从数据库中获取数据来更新数据列表。每次我添加一个数据,它不会更新 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/

相关文章:

javascript - AngularJS 复选框和 ng-change 的工作方式非常奇怪

javascript - 观察 ngmodel 中的任何变化

angularjs - Angular.js 如何从指令更新范围?

javascript - 一页中可以有多个谷歌图表吗?

javascript - onchange 函数到输入文本 JQuery 数组

javascript - 选择任何其他选项 bootstrap 时取消选择默认选择

javascript - 如何使用 "controller as"语法从基本 Controller 继承?

javascript - 防止 Bootstrap Accordion 扩展到父 div 之外

javascript - 如何发送十进制数 "545.20"并删除双引号并发送 545.20

javascript - 变量在 $scope 中可见,但在 Angular 中实际访问时未定义