I've structured my code into separate layers: 1. A factory that handles all of my $http requests and returns a promise. 2. A controller that manages the promise using a then function to assign it to a $scope variable for display on a gridview.
Now, I'm attempting to develop a directive to streamline the Gridview functionality by passing the data as an attribute to be managed in the link function and displayed. This approach aims to promote code reusability. However, I'm encountering an issue where the data variable in the scope is empty due to the asynchronous nature of the API call. How can I adopt a better strategy to resolve this issue?
angular.module('parametrosModule').factory('apiMethods', ['$http', 'apiUrl', function ($http, apiUrl) {
return {
getBleh: function () {
return $http.get(apiUrl.urlBase + '/getBleh');
},
}
}])
.controller('transactionController', ['apiMethods', function (apiMethods) {
var vm = this;
function getData() {
apiMethods.getBleh()
.then(function (response) {
vm.data = response.data;
});
};
}])
.directive('dynamicGrid', [function () {
return {
restrict: 'E',
templateUrl: 'app/directives/dynamicGrid.html',
scope: {
data: '=',
headers: '='
},
link: function (scope, elem, attrs) {
var vm = this;
vm.values = scope.data;
vm.headers = scope.headers;
}
}
}]);
This represents my current code structure after formatting. The challenge lies in the fact that the data attribute remains empty due to the delay in the API call. The ultimate goal is to create a feature that dynamically populates itself upon receiving relevant data from any part of the application. Any suggestions would be greatly appreciated!