Reputation: 443
i have a problem using directive inside ngRepeat. i cant get value of $scope.files. its undefined when using inside ngrepeat but works properly if ngrepeat not used. cant figure it out. help much appreciated.
$scope.files is undefined while used inside ng-repeat. if not used inside works perfectly
<button class="btn btn-success login-button" ng-click="addassignment()">+</button>
<table>
<tr ng-repeat = "assignment in assignments">
<td><input class = "filegap" type = "file" file-model="form.cv" ng-model="form.cv" ng-file-select="fileselected(newemp.email)" file-input="files" multiple/></td>
</tr>
</table>
javascript:
app.directive('fileInput', ['$parse', function($parse, $compile){
return {
restrict:'A',
link:function(scope,elm,attrs){
elm.bind('change', function(){
$parse(attrs.fileInput)
.assign(scope,elm[0].files)
scope.$apply()
})
}
}
}]);
controller:
$scope.addassignment = function(){
if(typeof $scope.assignments == 'undefined'){
$scope.assignments = [];
}
$scope.assignments.push({});
}
console.log($scope.files);
Upvotes: 0
Views: 452
Reputation: 1941
You don't create a files variable on the main scope, and when you use the assign it will assign to a newly created files (not on the controller), I have modified your code a bit,
angular.module('myApp',[]).controller('Main', ['$scope', function($scope) {
$scope.files = [];
$scope.addAssignment = function(){
if(typeof $scope.assignments == 'undefined'){
$scope.assignments = [];
}
console.log('add');
$scope.assignments.push({});
}
console.log($scope.files);
$scope.$watch('files.length', function() {
console.log($scope.files);
});
}]).directive('fileInput', [function() {
return {
restrict:'A',
link:function(scope,elm,attrs){
var files = scope[attrs['fileInput']];
elm.bind('change', function(){
files.push(this.files);
scope.$apply()
});
}
}
}]);
you can take a look here: http://plnkr.co/edit/mhXKdlDG5lg8Xnw50lua?p=preview
p.s. You can also use scope binding in the directive instead of that $parse.
Also, when you assign directly like that, it will always override the files because of how prototype inheritance work in JS, use objects / arrays instead for assigning values in a deeper scopes (like ng-model / ng-repeat etc)
Upvotes: 1