com48
com48

Reputation: 73

angularjs ng-grid keep selection on update

I'm trying to use the ng-grid setup and I have the following problem.

The data I am displaying changes very frequently, every 5 seconds or so. But not a lot of new data gets added to the list.

When i set data to the ng-grid the user can start looking at the data. but when I update the data after about 5 seconds the selections the user has made and the grouping is lost.

http://plnkr.co/edit/eK1aeRI67qMROqDUtPnb

Is there anyway to keep the selection and/or the grouping?

Upvotes: 3

Views: 2392

Answers (2)

timothyswt
timothyswt

Reputation: 559

We are going to be adding a primaryKey option in the next version that will allow the grid to key off that instead of references.

Upvotes: 2

Ben Lesh
Ben Lesh

Reputation: 108471

You're going to have to go through and merge the data in a for loop. If you replace the entire array, you're replacing the object references, and therefor you will lose any changes you've made.

The other option would be to keep your selections in a different array or dictionary, then remap your properties after you replace your array. Notice here you're going to need to use a reference type so changes persist to your selections array.

So like [psuedo-code]:

// a dictionary of reference types (IMPORTANT that they are objects!)
// to hold selection data.
var selections = {
  'Name1' : { value: 'selection' },
  'Name2': { value: 'selection2' }
}

$scope.getMyData = function () {    
    // do whatever to get your data here.
    $scope.myData = [
       { name: 'Name1' },
       { name: 'Name2' }
    ];

    // update your objects in your array. 
    for(var i = 0; i < $scope.myData.length; i++) {
       var data = $scope.myData[i];
       var selection = selections[data.name];
       if(selection) {
           data.selection = selection;
       }
    }    
};

// initial load
$scope.getMyData();

// your test interval
setInterval(function () {
    $scope.$apply(function (){
       $scope.getMyData();
    });
}, 5000);

Upvotes: 3

Related Questions