I am using AngularJS along with ng-grid and RestAngular for fetching data in pages. To handle the complexity of setting up the grid due to paginated data, I have opted to encapsulate it within a directive. However, upon resolving the promise returned by RestAngular, the data is not getting bound to $scope
.
$scope.gridService.get($scope.pagingOptions.currentPage,
$scope.pagingOptions.pageSize).then(function(result){
$scope.gridData = result;
});
Consequently, $scope.gridData
only contains an array within the promise resolution and nothing outside of it. Is there a way to bind the result to $scope
?
In a Controller
, I was able to achieve this binding successfully; however, the same approach is failing within this context. The full directive implementation is provided below.
angular.module('viz').directive('grid', function() {
return {
restrict: 'E',
replace: true,
scope: {
gridCols: '=',
gridService: '&'
},
template: '<div class="gridStyle" ng-grid="gridOptions"></div>',
controller: function ($scope, $element, $attrs, $injector) {
$scope.gridData = [];
$scope.gridService = $injector.get($attrs.gridservice);
$scope.pagingOptions = {
pageSizes: [5, 10, 20],
pageSize: 20,
currentPage: 1
};
$scope.gridService.get($scope.pagingOptions.currentPage,
$scope.pagingOptions.pageSize).then(function(result){
$scope.gridData = result;
});
$scope.totalServerItems = $scope.gridData.meta.results;
$scope.pagingOptions.currentPage = $scope.gridData.meta.page;
$scope.gridOptions = {
data: 'gridData',
selectedItems: $scope.mySelections,
multiSelect: false,
enableHighlighting: true,
enableRowSelection: true,
enablePaging: true,
showFooter: true,
pagingOptions: $scope.pagingOptions,
totalServerItems: 'totalServerItems',
columnDefs: $scope.gridCols
};
},
link: function(scope, element, attrs, fn) {
scope.$watch('pagingOptions', function (newVal, oldVal) {
if (newVal !== oldVal && newVal.currentPage !== oldVal.currentPage) {
scope.gridData = scope.gridService.get(
scope.pagingOptions.currentPage,
scope.pagingOptions.pageSize
);
}
}, true);
}
};
});