简体   繁体   中英

How can I use variable outside that function in AngularJS?

I'm using this scope in controller:

$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));
            });
        }

Yes, it works and I need this:

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

Ok but now, I have to use this var in another function. How can I do it? Thanks.

You can declare the variable outside your function:

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
}

One solution is document.variable

example inside function:

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

example outside function:

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

You can bind it in $scope like

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

so it can be used globally in the file as well as on the template too.

OR

You can declare it in outside the function to use it globally

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM