0

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

1
  • 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. Commented Mar 10, 2016 at 4:48

2 Answers 2

1

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: '='
}
Sign up to request clarification or add additional context in comments.

Comments

0

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.