简体   繁体   中英

One-time binding with ng-repeat trackBy isn't updating

I'm trying to minimize the number of watchers in my AngularJS application by using both "track by" in my ngRepeat, as well as using one-time bindings.

eg

My View:

<div ng-repeat="item in items track by trackingId(item)">
  {{ ::item.updated_at }}  {{ ::item.id }}
</div>

My trackingId and scope look something like this:

$scope.items = [
  { id: 1, updated_at: 'January 1, 2015' },
  { id: 2, updated_at: 'January 1, 2016' },
  ...
]

$scope.trackingId = function(item) {
  return item.id + '_' + item.updated_at;
}

Now, somewhere in my app, an items updated_at value gets changed. For example,

$scope.updateItem = function(item) {
  item.updated_at = Date.now();
}

I would then expect that the view to reflect this item as a "new" item in the DOM due to the trackingId value for that item being changed, thereby updating the one-time bound value, however this is not happening.

Is my understanding of one-time binding + trackBy incorrect? How can I achieve the above such that if my trackingId changed, the item will be re-drawn on the view?

Thanks,

When you update an item attached to scope, you have to let angular know that the binding has changed and to do that you use $scope.$apply().

 $scope.updateItem = function(item) {
  item.updated_at = Date.now();
  $scope.$apply();
}

maybe this is not good idea

return item.id + '_' + item.updated_at;

try without this.for example only with id

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM