如何在AngularJS中使用该函数之外的变量?

时间:2016-04-19 11:53:28

标签: javascript angularjs

我在控制器中使用此范围:

$scope.uploadPic = function (file) {
            file.upload = Upload.upload({
                url: 'http://sites.net/upload',
                data: {file: file, blobType: 'apps'},
            });

            file.upload.then(function (response) {
                $timeout(function () {
                    file.result = response.data;
                    var downloadLink = response.data.data.uploadInfo.publicDownloadUrl;
                    console.log(downloadLink);
                });
            }, function (response) {
                if (response.status > 0)
                    $scope.errorMsg = response.status + ': ' + response.data;
            }, function (evt, response) {
                // Math.min is to fix IE which reports 200% sometimes
                file.progress = Math.min(100, parseInt(100.0 * evt.loaded / evt.total));
            });
        }

是的,它有效,我需要这个:

var downloadLink = response.data.data.uploadInfo.publicDownloadUrl;
console.log(downloadLink);

好的,但现在,我必须在另一个函数中使用此var。我该怎么做?感谢。

3 个答案:

答案 0 :(得分:2)

您可以在函数外声明变量:

var downloadLink;

$scope.uploadPic = function (file) {
    // ..
    file.upload.then(function (response) {
        $timeout(function () {
            file.result = response.data;
            downloadLink = response.data.data.uploadInfo.publicDownloadUrl;
            // or, if you want to use it in your view:
            // $scope.downloadLink = downloadLink;
            console.log(downloadLink);
        });
    }, function (response) {
    // ..
}

function doSomethingWithLink() {
    var link = downloadLink;
    // do something with link
}

答案 1 :(得分:0)

一种解决方案是document.variable

示例内部函数:

 document.downloadLink = response.data.data.uploadInfo.publicDownloadUrl;

外部函数示例:

document.downloadLink=  response.data.data.uploadInfo.publicDownloadUrl;

答案 2 :(得分:0)

您可以将其绑定在$scope

$scope.downloadLink = response.data.data.uploadInfo.publicDownloadUrl;

所以它可以在文件中全局使用,也可以在模板上使用。

您可以在函数外部声明它以全局使用它