带控制器的Angularjs指令

时间:2013-08-08 22:01:13

标签: angularjs

我试图用它自己的控制器编写一个指令。

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()
                {
                }
            });
        }
    };
});

使用模态调用此伪指令,//创建库为上传者js生成id。我不明白的是链接:函数正在运行并在控制器之前返回undefined。对此有任何指导意见。

谢谢

1 个答案:

答案 0 :(得分:6)

不是在控制器之前调用链接函数,这是因为$scope.created.then()是异步的,设置id的回调函数在链接函数之后被称为

要解决此问题,您需要在链接功能中调用$scope.created.then()

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()
            {
            }
        });
    });
}