Reputation: 392
I have my code in different layers: 1. A factory that contains all of my $http request, and return the promise. 2. A controller that handles that promise with a then, to a assign it to a $scope variable to then display it on a gridview.
And now I'm trying to create a directive to handle the Gridview and just pass the data as an attr to be handled in the link function and display it. With this, I'm trying to achieve code re-usability. The problem is that the data variable on the scope is coming empty due to the async call of course, what would be a much better approach to this?
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 is somewhat my code after formatting, the thing is that the data attr is coming empty due to the lateness in the api call. The whole idea is to create something that build itself after receiving x data from anyone in the app. Thanks!!
Upvotes: 0
Views: 238
Reputation: 366
You do not need the link function
for this. here is a working example. You just need to actually bind the model to the $scope
of the directive by telling it what to bind to:
scope: {
data: '=data',
headers: '='
}
Upvotes: 1
Reputation: 637
you can resolve your api call so it is in fact loaded before your view renders, or you can wrap you directive in an ng-if="isDataLoaded" and in your then set it to true
Upvotes: 0