【问题标题】:how to update a list inside ng-repeat using angular?如何使用角度更新 ng-repeat 中的列表?
【发布时间】:2014-11-29 02:31:50
【问题描述】:

我有一个离子列表

<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

【问题讨论】:

  • 你能给这个加个小提琴吗

标签: javascript angularjs angularjs-ng-repeat ionic-framework


【解决方案1】:

如果 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,详细讨论原因。

【讨论】:

  • 如果您遇到范围继承问题,我已经用可能的解决方案编辑了我的答案。
  • 谢谢,一直在找这个。
【解决方案2】:

我试过了:$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);
}

【讨论】:

  • 是的,我想通了,看看我最后的编辑.. 谢谢
猜你喜欢
  • 2015-06-13
  • 1970-01-01
  • 1970-01-01
  • 2015-11-04
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2014-12-23
相关资源
最近更新 更多