如何使用 Angular 更新 NG-Repeat 中的列表

how to update a list inside ng-repeat using angular?

本文关键字:列表 NG-Repeat 更新 何使用 Angular      更新时间:2023-09-26

>i lave an ionic list

<ion-list>
  <ion-item ng-repeat="item in items">
    Hello, {{item.name}}!
  </ion-item>
</ion-list>

然后,在控制器中我有一个事件:

$scope.items = someData();
itemsRef.on('event', function (response) {
    console.log(response); // this is an object containing he "name" property
});

我想将response追加为ion-item,而不插入 HTML,但以某种方式将响应添加到项目中

编辑:

我试过了:$scope.items.push(response);但奇怪的是我得到了Uncaught TypeError: undefined is not a function

编辑:看起来一个人不仅$scope.items.push(response);,而且$scope.items[next_key_here] = response;

见JSFIDDLE

如果 itemRef 是一个 Angular 服务,你只需要将对象添加到 items 数组中:

$scope.items.push( response );

如果itemRef使用一些非Angular异步服务来获取其响应,则需要告诉Angular事情已经更新:

$scope.$apply( function() {
    $scope.items.push( response );
});

如果您在使用$scope时遇到问题,最好使用带有点的 $scope 变量,例如使用 $scope.data.items 而不是 $scope.items。

有关原因的精彩讨论,请参阅 http://jimhoskins.com/2012/12/14/nested-scopes-in-angularjs.html。

我试过了:$scope.items.push(response);但奇怪的是,我得到了Uncaught TypeError: undefined is not a function

发生这种情况是因为 $scope.items 在尚未填充值之前访问它时不是Array对象。尝试做这样的事情,这应该有效:

if ($scope.items && $scope.items instanceof Array) {
  $scope.items.push(response);
}