ng-table
ng-table copied to clipboard
Change API to correct promises
Now, promises are used in incorrect way. They must be written smth like this:
this.getData = function (params) {
if (angular.isArray(this.data) && angular.isObject(params)) {
return this.data.slice((params.page() - 1) * params.count(), params.page() * params.count());
} else {
return [];
}
};
this.getGroups = function (column) {
return $q.when(this.getData(self))
.then(function (data) {
var groups = {};
angular.forEach(data, function (item) {
var groupName = angular.isFunction(column) ? column(item) : item[column];
groups[groupName] = groups[groupName] || {
data: []
};
groups[groupName]['value'] = groupName;
groups[groupName].data.push(item);
});
var result = [];
for (var i in groups) {
result.push(groups[i]);
}
log('ngTable: refresh groups', result);
return result;
});
};
this.reload = function () {
var self = this, dataPromise;
settings.$loading = true;
if (settings.groupBy) {
dataPromise = $q.when(settings.getGroups(settings.groupBy, this));
} else {
dataPromise = $q.when(settings.getData(this));
}
log('ngTable: reload data');
return dataPromise.then(function (data) {
settings.$loading = false;
log('ngTable: current scope', settings.$scope);
if (settings.groupBy) {
self.data = settings.$scope.$groups = data;
} else {
self.data = settings.$scope.$data = data;
}
settings.$scope.pages = self.generatePagesArray(self.page(), self.total(), self.count());
settings.$scope.$emit('ngTableAfterReloadData');
});
};
Ang then, getData mehtod will be much pretty. Instead of
getData: function ($defer, params) {
$http.get('/api/someResource', {params: params.filter})
.then(function (respones) {
$defer.resolve(respones.data);
});
}
will be
getData: function (params) {
return $http.get('/api/someResource', {params: params.filter})
.then(function (respones) {
return respones.data;
});
}
+1 this is more natural way to deal with promises.
+1