I have the following settings for my ng-grid in my code :
$scope.gridOptions = {
...
useExternalSorting : false,
}
$scope.watch('gridOptions.ngGrid.config.sortInfo', function (oldValue, newValue) {
console.log(newValue)
})
I also tried using sortInfo : undefined
and $watch(gridOptions.sortInfo)
. This seems to work only when the grid initially loads. After that, when I click on the header columns, it does not seems to go inside the callback function for the $watch
. I tried putting a debugger inside the callback function which triggers the sort, and I could see the the code updating the sortInfo array with the right information, however it does not seem to go inside the callback function for the watch statement. Is there anything incorrect with my setup? I have a Plunker here with something similar to what I'm trying to do.
I had the same problem. I wanted to do my own server-side sorting but still use the sortInfo
object that's updated when the column headers are clicked. After looking at some errors in the console, I found that I had to set a default sortInfo
like so:
$scope.gridOptions = {
...
sortInfo: { fields: [], columns: [], directions: [] },
useExternalSorting: true
}
I'm not sure why the columns
field is necessary and it doesn't match the documentation. I'm using AngularJS v1.2.19 and ng-grid v2.0.11. Not sure why you have useExternalSorting
set to false
but either way you should now be able to set a watch on that field like this:
$scope.$watch('gridOptions.sortInfo', function (newVal, oldVal) {
console.log(newVal);
}, true);
If you really need to watch the sorting changes you could use the following:
//default sorting
$scope.sortOptions = {
sortfield: "name",
sortdir: "DESC"
};
//on sorting event fill out sortOptions in scope
$scope.$on('ngGridEventSorted', function(event, data) {
$scope.sortOptions.sortfield = data.fields[0];
$scope.sortOptions.sortdir = data.directions[0];
});
//when sortOption changes do something
$scope.$watch('sortOptions', function(newVal, oldVal) {
if (newVal !== oldVal) {
console.log("ngGrid Field: " + $scope.sortOptions.sortfield + " - Direction: " + $scope.sortOptions.sortdir);
}
}, true);
Which uses the sort event to fill out the sortinfo in the scope which is watched and fires when it changes. Plunker here
Or, less complicated, fire directly on sort event and spare yourself the boring watching 8-\
//on sorting event do something
$scope.$on('ngGridEventSorted', function(event, data) {
console.log("ngGrid Field: " + data.fields[0] + " - Direction: " +data.directions[0]);
});
Another plunker
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With