Stack Overflow is a community of 4.7 million programmers, just like you, helping each other.

Join them; it only takes a minute:

Sign up
Join the Stack Overflow community to:
  1. Ask programming questions
  2. Answer and help your peers
  3. Get recognized for your expertise

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!!

share|improve this question
1  
Show source dynamicGrid.html. If you are using variables (data,headers) directly in the template dynamicGrid.html, you do not need to track changes in variables directly in the function link. – Stepan Kasyanenko yesterday

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: '='
}
share|improve this answer

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

share|improve this answer

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.