0

i'm using a AngularJS custom directive to implement html file input.I used an open source library which is on Github.But when i'm trying to access the scope value from the controller, it's showing as undefined variable.

Following is the directive code,

 angularApp.directive('file', function() {
return {
    restrict: 'AE',
    scope: {
        file: '@'
    },
    link: function(scope, el, attrs){
        el.bind('change', function(event){
            var files = event.target.files;
            var file = files[0];
            // scope.file = file;
            scope.file = file;
            scope.$parent.file = file;
            scope.$apply();
        });
    }
};
});

Following is the html code

<input type="file" class="form-control" name="file" required>

But here in the html code other html snippets have ng-models which is binding to a scope object.As an example,

And this uses a ng-submit attribute with addNewUser(resources.newUser)

Following is part of controller code

$scope.addNewUser = function(data) {
        console.log('FILE PATH IS :' + $scope.file);

}

1 Answer 1

1

use directive as attribute to the element as file="file".

<input type="file" class="form-control" name="file" required file="file" >

Check the demo

angular.module("app",[])
.controller("ctrl",function($scope){
$scope.file ;

$scope.addNewUser = function(data) {
   console.log( $scope.file);

}

}).directive('file', function() {
return {
    restrict: 'AE',
    scope: {
        file: '@'
    },
    link: function(scope, el, attrs){
    debugger
        el.bind('change', function(event){
            var files = event.target.files;
            var file = files[0];
            // scope.file = file;
            scope.file = file;
            scope.$parent.file = file;
            scope.$apply();
        });
    }
};
});
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<div ng-app="app" ng-controller="ctrl">
 <input type="file" class="form-control" file="file" name="file" required>
 <button ng-click="addNewUser()">aaa</button>
</div>

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

3 Comments

Thanks for this.Okay, if my directive name is "videofile", should i use file="videofile" as html directive or videofile="videofile"?
it should be videofile="flle" . note that file is the value
I added the html code like this, <input type="file" class="form-control" name="videofile" videofile="file">

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.