【问题标题】:AngularJS doesn't push new record into the arrayAngularJS 不会将新记录推送到数组中
【发布时间】:2015-10-26 16:39:09
【问题描述】:

我新建一条记录,这条记录已成功添加到数据库中。那挺好的。 但问题是它不会更新现有记录的列表——这意味着push 函数似乎不起作用。

这是在控制器内部:

$scope.posts = Posts.query();
...
$scope.saveForm = function(post) {
  var p = new Post(post);
  p.$save(function (response) {
  $scope.posts.push(angular.extend(p, response.id));
    console.log('saved');
    console.log(response.id);
  });
};

我尝试只使用push()而不使用angular.extend(),也尝试在控制器末尾添加$scope.posts = Posts.query();,但没有帮助 - 新记录仍未添加到当前列表帖子数。

什么可能导致这种情况?我在 SO 上找到了类似的主题,但它并没有帮助我解决这个问题。

谢谢。

编辑: 我在console.log($scope.posts); 看到了新帖子,它只是没有出现在帖子列表中。

EDIT2: 我在push 命令之后也尝试了$scope.$apply();,但它导致了这个错误消息:

Error: [$rootScope:inprog] $digest already in progress

EDIT3: 我发现当我尝试删除记录时,列表也没有更新(仅在刷新后)。

EDIT4: 当我添加一条新记录时,在 JS 中是这个输出(新记录,正确保存,只是没有在所有项目的列表中更新):

Resource {id: Object, title: "hohohohooho", body: null, starred: null, created_at: "2015-10-27T04:00:06.943Z"…}

ID 可作为response.id.$oid 访问。

【问题讨论】:

  • 扩展名不应该是angular.extend(p,{id: response.id}) 吗?
  • 您需要提供更多代码。 Angular 使用标准的 js 数组推送,效果很好。
  • 在将 p 的扩展推入帖子之前,登录以查看 p 打印的内容
  • @charlietfl - 谢谢,我试过这个选项,但很遗憾没有帮助。
  • @MohammadJavad Seyyedi - p 包含一个对象 - {id: Object, title: "asdgasdhc", body: "cc", starred: null, created_at: "2015-10-26T18:41:52.686Z"…} - 这应该没问题。

标签: javascript ruby-on-rails ruby angularjs push


【解决方案1】:

这对我有用...

p.$save().then(function(response){ 
     $scope.posts.push(response.id) 
});

【讨论】:

  • 该死,还是什么都没有。它仍然不会将新记录添加到现有记录列表中。
【解决方案2】:

Angular 扩展不保存列表/数组。 它用新项目扩展旧列表/数组。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2017-09-01
    • 2016-11-18
    • 1970-01-01
    • 1970-01-01
    • 2016-12-23
    • 2016-08-09
    • 2022-12-06
    相关资源
    最近更新 更多