SuperNinja
SuperNinja

Reputation: 1606

Angularjs Directive with Controller

I am attempting to write a directive with it's own controller.

myApp.directive('imageUploadifive', function (createGal)
{
    return {
        restrict: 'A',
        controller: function($scope)
        {
            //create gallery
            $scope.created = createGal.createGal();
            $scope.created.then(function(createGal){
                $scope.gallery.id = createGal.created_id;
                console.log($scope.gallery.id);//returning after the link function
            });

            $scope.gallery.galleryName = "New Image Gallery";
        },
        link: function($scope, element, attrs)
        {
        var id = $scope.gallery.id;
        console.log(id);
            $(element).uploadifive({
                'uploadScript'  : '/beta/images/upload',
                'buttonClass'   : 'uploadifive-button btn btn-primary',
                'queueID'       : 'imageGallery_queue',
                'buttonText'    : 'Select Files',
                'fileSizeLimit' : 500,
                'formData' : {
                    'galleryID' : id
                },
                'onError': function(errorType)
                {
                    alert('There was a problem');
                },
                'onUpload': function()
                {
                }
            });
        }
    };
});

This directive is called with a modal and the //create gallery is generating an id for the uploader js. What I don't understand is the link: function is running and returning undefined before the controller. Any guidance on this would be appreciated.

Thanks

Upvotes: 3

Views: 3323

Answers (1)

Ye Liu
Ye Liu

Reputation: 8986

It's not the linking function is called before the controller, it's because the $scope.created.then() is asynchronous, the callback function to set the id is called after the linking function.

To fix it, you need to call $scope.created.then() in the linking function instead:

link: function($scope, element, attrs) {
    $scope.created.then(function(createGal) {
        $scope.gallery.id = createGal.created_id;

        $(element).uploadifive({
            'uploadScript'  : '/beta/images/upload',
            'buttonClass'   : 'uploadifive-button btn btn-primary',
            'queueID'       : 'imageGallery_queue',
            'buttonText'    : 'Select Files',
            'fileSizeLimit' : 500,
            'formData' : {
                'galleryID' : $scope.gallery.id
            },
            'onError': function(errorType)
            {
                alert('There was a problem');
            },
            'onUpload': function()
            {
            }
        });
    });
}

Upvotes: 6

Related Questions