0

I have a directive which I can use like this:

<input type="file" ng-file-select="onFileSelect($files)" multiple>

This works just fine in the main scope, but when I try to use it within a repeater and then inside include:

<div ng-repeat="tab in tabs">
    <div ng-include="tab.url"></div>
</div>

tab.url:

<input type="file" ng-file-select="onFileSelect($files)" multiple>

It stops working, no data is sent to the scope.

ngFileSelect directive:

app.directive("ngFileSelect", function () {
    return {
        link: function ($scope, el) {
            el.bind("change", function (e) {
                for (var i = 0; i < e.target.files.length; i++) {
                    $scope.file = (e.srcElement || e.target).files[i];
                     $scope.getFile();
                }
            });
        }
    };
});

In my controller i have:

$scope.getFile = function() {
    fileReader.readAsDataUrl($scope.file, $scope)
        .then(function(result) {
            $scope.images.push(result);
        });
};

How can I access the files selected inside the included file in a tab?

0

1 Answer 1

2

Try:

$scope.getFile = function() {
    var currentScope = this; //access the file from current scope instead of from $scope which is always your controller's scope

    fileReader.readAsDataUrl(currentScope.file, currentScope)
        .then(function(result) {
            currentScope.images.push(result);
        });
};

The reason is scope inheritance, ng-repeat and ng-include create child scopes. The selected file is assigned to a child scope:

$scope.file = (e.srcElement || e.target).files[i];

And then call:

$scope.getFile(); //this is inherited from parent scope (controller)

In the getFile function, you're accessing $scope.file (your controller's scope) that does not have the file assigned.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.