I have this html
<input type="file" file-input="files" multiple />
<button ng-click="upload()" type="button">Upload</button>
<li ng-repeat="file in files">{{file.name}}</li>
This directive:
.directive('fileInput', ['$parse', function($parse){
return {
restrict: 'A',
link: function(scope, elm, attrs){
//console.log("directives scope: ")
elm.bind('change', function(){
$parse(attrs.fileInput)
.assign(scope,elm[0].files)
scope.$apply()
//console.log(scope);
})
}
}
}]);
and in my controller I have this function:
$scope.upload=function(){
console.log($scope.files)
var fd = new FormData() // put these 3 lines in a service
angular.forEach($scope.files, function(file){
fd.append('file', file)
})
$http.post('/api/directory/upload-file-test', fd,
{
transformRequest: angular.identity, // returns first argument it is passed
headers:{'Content-Type': undefined} //multipart/form-data
})
.success(function(d){
console.log(d)
console.log("works?")
})
}
It works fine if I just put the HTML directly in the html file as you'd normally do, however...
I need to inject it, and when I do that, the directive scope and controller scope is not the same.. so files which I've added to scope.files in the directive is just "undefined" inside the controller function, so my file upload breaks...
More exactly...
If I do this:
<tr ng-repeat="prop in tab.properties">
<td>{{prop.name}}</td>
<td compile ng-bind-html="prop.data_type.html | unsafe"></td>
<td>{{prop.description}}</td>
</tr>
Where the content inside the ng-bind-html quotes (prop.data_type.html) simply just equals to this:
<input type="file" file-input="files" multiple />
<button ng-click="upload()" type="button">Upload</button>
<li ng-repeat="file in files">{{file.name}}</li>
It doesn't work. The scopes are different.
My compile-directive looks like this:
.directive('compile',function($compile, $timeout){
return{
restrict:'A',
link: function(scope,elem,attrs){
$timeout(function(){
$compile(elem.contents())(scope);
});
}
};
})
and the last relevant bit of code would be the unsafe-filter which is this:
.filter('unsafe', function($sce) {
return function(val) {
return $sce.trustAsHtml(val);
};
})
Does anyone have an idea why my "upload" function inside my controller and my directive scope cannot stay synced and reference the same scope IF and only IF I inject my html with my compile-directive and unsafe-filter via ng-bind-html? Is there anyway around this or must I refrain from using directives to make this work?
I've tried first Angular 1.3.0 rc4 and now after I upgraded to latest version v. 1.3.5 it's still the same.