【问题标题】:AngularJS - ng-repeat is not updating when adding dataAngularJS - 添加数据时 ng-repeat 不更新
【发布时间】:2015-08-10 12:49:29
【问题描述】:

我正在尝试通过从数据库中获取数据来更新数据列表。每次我会添加一个数据,它不会更新视图,只有当我刷新页面时视图才会更新。我通过使用 $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>

注意:删除按钮在这里有效

【问题讨论】:

  • 你检查响应结构了吗?
  • @RIYAJKHAN,是的,我做到了。它确实返回了正确的结构。但仍然没有运气

标签: javascript angularjs angularjs-scope


【解决方案1】:

因为 ng-repeat 在 DashboardCtrl 范围之外。我猜你有一个 DashboardCtrl div 和 posts div 的父控制器,你在父控制器中启动 $scope.posts 。

当你有

$scope.renderPost = function(response){
    $scope.posts = response;
}

它更新子范围内的帖子。您可能需要执行以下操作:

$scope.$parent.posts = response;

或将 ng-repeat div 移到 &lt;div class="jumbotron text-center" ng-controller="DashboardCtrl"&gt;...&lt;/div&gt;

【讨论】:

  • 这成功了!谢谢@Shawn Song,我没想到会这样。
【解决方案2】:

因为您只更新数据库。 将新添加的 post_detail 推送到 post 对象中。

//posting post
$scope.post = function(){
    $http.post('/post',$scope.post_detail)
    .success(function(response){
        $scope.post.push($scope.post_detail);
        $scope.render();
    });
}

【讨论】:

  • @Dimitry Mikadze,我试过推,还是没有运气。
【解决方案3】:

我假设您的服务器对 $http.get('/post') 的响应是一个 json 对象数组

在这种情况下,数组可以嵌套在 data 属性中

$scope.renderPost = function(response){
    $scope.posts = response.data;
}

【讨论】:

  • 是的,它是一个 json 对象数组,但目前还不是嵌套的 json。通过console.log(response),数据正确返回为GET语句
  • 因此,如果您将响应记录到控制台,您会看到数组内容吗?你确定你没有看到一个物体
  • 页面加载时:[Object, Object, Object], 发布新数据后[Object, Object, Object, Object]。添加了一个新对象。刷新页面更新第四个对象
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2016-02-12
  • 2018-06-03
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多