James
James

Reputation: 2860

Angular directive being called before AJAX call populates data

I have an issue at the moment with a directive whereas some scope values that are set in the parent controller are not set when the directive tried to access them. This is because the directive is called before the AJAX call has returned any data. Is there any to make my directive wait for this data to be set before continuing?

Here is my directive:

return {
                restrict: 'E',
                //scope: {},
                templateUrl: window.baseUrl + '/template-common/directives/blurGallery',
                // -------------------------------------------------------------
                link: function(scope, element, attrs) {

                    var $gallery = $('body').find('.the-gallery'),
                        $item = $gallery.find('.preview-content');

                    console.log($scope.tasks);

                    scope.gallery = {

The view (jade) code:

blur-gallery(gallery-items)

And the controller code:

//Get task details
                PPTaskService.loadTaskDetails($scope.theTaskId)
                    .then(function(response) {
                        $scope.task = new TaskWrapper(response);

                        $scope.isDataLoaded = true;
                    });

As you can see, the controller asks a service to retrieve data and set the $scope.task variable but the directive is trying to access this before this has returned (as you can see with console.log).

Thanks

Upvotes: 2

Views: 204

Answers (1)

Agop
Agop

Reputation: 1917

In the directive, use scope.$watch() on either scope.task or scope.isDataLoaded to be notified when the data is available. From there, continue to perform your directive logic.

For example:

scope.$watch('isDataLoaded', function(newValue, oldValue) {
    if (newValue === true)
    {
        /* do stuff with data */
    }
});

Upvotes: 2

Related Questions