Reputation: 929
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);
}
Upvotes: 0
Views: 50
Reputation: 41387
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>
Upvotes: 1