ng-model dla ` " (z dyrektywą DEMO)
Próbowałem użyć ng-model na znaczniku wejściowym z plikiem typu:
<input type="file" ng-model="vm.uploadme" />
Ale po wybraniu pliku, w kontrolerze, $scope.vm.uploadme jest nadal niezdefiniowany.
Jak uzyskać wybrany plik w kontrolerze?
11 answers
Stworzyłem obejście z dyrektywą:
.directive("fileread", [function () {
return {
scope: {
fileread: "="
},
link: function (scope, element, attributes) {
element.bind("change", function (changeEvent) {
var reader = new FileReader();
reader.onload = function (loadEvent) {
scope.$apply(function () {
scope.fileread = loadEvent.target.result;
});
}
reader.readAsDataURL(changeEvent.target.files[0]);
});
}
}
}]);
I znacznik wejściowy staje się:
<input type="file" fileread="vm.uploadme" />
Lub jeśli potrzebna jest tylko definicja pliku:
.directive("fileread", [function () {
return {
scope: {
fileread: "="
},
link: function (scope, element, attributes) {
element.bind("change", function (changeEvent) {
scope.$apply(function () {
scope.fileread = changeEvent.target.files[0];
// or all selected files:
// scope.fileread = changeEvent.target.files;
});
});
}
}
}]);
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2014-01-12 15:53:42
Używam tej dyrektywy:
angular.module('appFilereader', []).directive('appFilereader', function($q) {
var slice = Array.prototype.slice;
return {
restrict: 'A',
require: '?ngModel',
link: function(scope, element, attrs, ngModel) {
if (!ngModel) return;
ngModel.$render = function() {};
element.bind('change', function(e) {
var element = e.target;
$q.all(slice.call(element.files, 0).map(readFile))
.then(function(values) {
if (element.multiple) ngModel.$setViewValue(values);
else ngModel.$setViewValue(values.length ? values[0] : null);
});
function readFile(file) {
var deferred = $q.defer();
var reader = new FileReader();
reader.onload = function(e) {
deferred.resolve(e.target.result);
};
reader.onerror = function(e) {
deferred.reject(e);
};
reader.readAsDataURL(file);
return deferred.promise;
}
}); //change
} //link
}; //return
});
I wywołaj to tak:
<input type="file" ng-model="editItem._attachments_uri.image" accept="image/*" app-filereader />
The property (editItem.editItem._attachments_uri.obraz) zostanie wypełniona zawartością wybranego pliku jako data-uri (!).
Proszę pamiętać, że ten skrypt nie będzie niczego przesyłać. Będzie wypełniać twój model tylko zawartością zakodowanego pliku AD a data-uri (base64).
Sprawdź działające demo tutaj: http://plnkr.co/CMiHKv2BEidM9SShm9Vv
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2015-03-17 13:30:28
To jest dodatek do rozwiązania @endy-tjahjono.
Skończyło się na tym, że nie byłem w stanie uzyskać wartości uploadme z zakresu. Mimo że uploadme W HTML został wyraźnie zaktualizowany przez dyrektywę, nadal nie mogłem uzyskać dostępu do jego wartości przez $scope.uploadme. Udało mi się jednak ustalić jego wartość z lunety. Tajemnicze, prawda..?
Jak siÄ ™ okazaĹ 'o, zakres child zostaĹ' stworzony przez dyrektywÄ™, a zakres child miaĹ ' wĹ ' asny uploadme .
Rozwiązaniem było użycie obiektu zamiast prymitywnego do przechowywania wartości uploadme .
W kontrolerze mam:
$scope.uploadme = {};
$scope.uploadme.src = "";
Oraz w HTML:
<input type="file" fileread="uploadme.src"/>
<input type="text" ng-model="uploadme.src"/>
Nie ma żadnych zmian w dyrektywie.
Teraz wszystko działa zgodnie z oczekiwaniami. Mogę pobrać wartość uploadme.src {[6] } z mojego kontrolera używając $scope.uploadme.Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2013-09-21 08:33:54
Robocza wersja demonstracyjna dyrektywy, która działa z ng-model
Jak włączyć <input type="file">
do pracy z ng-model
Podstawowa dyrektywa ng-model
nie działa z <input type="file"
po wyjęciu z pudełka.
Ta niestandardowa dyrektywa umożliwia {[2] } i ma dodatkową zaletę w postaci włączenia ng-change
, ng-required
, i ng-form
dyrektywy do pracy z <input type="file">
.
angular.module("app",[]);
angular.module("app").directive("selectNgFiles", function() {
return {
require: "ngModel",
link: function postLink(scope,elem,attrs,ngModel) {
elem.on("change", function(e) {
var files = elem[0].files;
ngModel.$setViewValue(files);
})
}
}
});
<script src="//unpkg.com/angular/angular.js"></script>
<body ng-app="app">
<h1>AngularJS Input `type=file` Demo</h1>
<input type="file" select-ng-files ng-model="fileArray" multiple>
<code><table ng-show="fileArray.length">
<tr><td>Name</td><td>Date</td><td>Size</td><td>Type</td><tr>
<tr ng-repeat="file in fileArray">
<td>{{file.name}}</td>
<td>{{file.lastModified | date : 'MMMdd,yyyy'}}</td>
<td>{{file.size}}</td>
<td>{{file.type}}</td>
</tr>
</table></code>
</body>
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2018-06-27 18:06:16
Cześć chłopaki tworzę dyrektywę i zarejestrowałem się na bower.
Ta lib pomoże Ci modelować plik wejściowy, nie tylko zwracając dane Pliku, ale także dane pliku lub bazę 64.
{
"lastModified": 1438583972000,
"lastModifiedDate": "2015-08-03T06:39:32.000Z",
"name": "gitignore_global.txt",
"size": 236,
"type": "text/plain",
"data": "data:text/plain;base64,DQojaWdub3JlIHRodW1ibmFpbHMgY3JlYXRlZCBieSB3aW5kb3dz…xoDQoqLmJhaw0KKi5jYWNoZQ0KKi5pbGsNCioubG9nDQoqLmRsbA0KKi5saWINCiouc2JyDQo="
}
Https://github.com/mistralworks/ng-file-model/
Nadzieja ci pomoże
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2015-09-10 17:41:18
Jest to nieco zmodyfikowana wersja, która pozwala określić nazwę atrybutu w zakresie, tak jak w przypadku ng-model, usage:
<myUpload key="file"></myUpload>
Dyrektywa:
.directive('myUpload', function() {
return {
link: function postLink(scope, element, attrs) {
element.find("input").bind("change", function(changeEvent) {
var reader = new FileReader();
reader.onload = function(loadEvent) {
scope.$apply(function() {
scope[attrs.key] = loadEvent.target.result;
});
}
if (typeof(changeEvent.target.files[0]) === 'object') {
reader.readAsDataURL(changeEvent.target.files[0]);
};
});
},
controller: 'FileUploadCtrl',
template:
'<span class="btn btn-success fileinput-button">' +
'<i class="glyphicon glyphicon-plus"></i>' +
'<span>Replace Image</span>' +
'<input type="file" accept="image/*" name="files[]" multiple="">' +
'</span>',
restrict: 'E'
};
});
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2014-08-03 17:55:21
Dla wielu plików wprowadzanych za pomocą lodash lub underscore:
.directive("fileread", [function () {
return {
scope: {
fileread: "="
},
link: function (scope, element, attributes) {
element.bind("change", function (changeEvent) {
return _.map(changeEvent.target.files, function(file){
scope.fileread = [];
var reader = new FileReader();
reader.onload = function (loadEvent) {
scope.$apply(function () {
scope.fileread.push(loadEvent.target.result);
});
}
reader.readAsDataURL(file);
});
});
}
}
}]);
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2015-03-12 19:44:00
Musiałem zrobić to samo na wielu wejściach, więc zaktualizowałem metodę @ Endy Tjahjono. Zwraca tablicę zawierającą wszystkie odczytane pliki.
.directive("fileread", function () {
return {
scope: {
fileread: "="
},
link: function (scope, element, attributes) {
element.bind("change", function (changeEvent) {
var readers = [] ,
files = changeEvent.target.files ,
datas = [] ;
for ( var i = 0 ; i < files.length ; i++ ) {
readers[ i ] = new FileReader();
readers[ i ].onload = function (loadEvent) {
datas.push( loadEvent.target.result );
if ( datas.length === files.length ){
scope.$apply(function () {
scope.fileread = datas;
});
}
}
readers[ i ].readAsDataURL( files[i] );
}
});
}
}
});
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2014-03-08 22:06:05
function filesModelDirective(){
return {
controller: function($parse, $element, $attrs, $scope){
var exp = $parse($attrs.filesModel);
$element.on('change', function(){
exp.assign($scope, this.files[0]);
$scope.$apply();
});
}
};
}
app.directive('filesModel', filesModelDirective);
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2014-11-12 21:47:09
Musiałem zmodyfikować dyrektywę Endy ' ego, aby móc uzyskać Ostatnio zmodyfikowaną, lastModifiedDate, nazwę, Rozmiar, typ i dane, a także móc uzyskać tablicę plików. Dla tych z Was, którzy potrzebowali tych dodatkowych funkcji, proszę bardzo.
UPDATE: Znalazłem błąd, w którym jeśli wybierzesz plik(y), a następnie przejdź do wybierz ponownie, ale zamiast tego anuluj, pliki nigdy nie zostaną odznaczone, jak się wydaje. Więc zaktualizowałem mój kod, żeby to naprawić.
.directive("fileread", function () {
return {
scope: {
fileread: "="
},
link: function (scope, element, attributes) {
element.bind("change", function (changeEvent) {
var readers = [] ,
files = changeEvent.target.files ,
datas = [] ;
if(!files.length){
scope.$apply(function () {
scope.fileread = [];
});
return;
}
for ( var i = 0 ; i < files.length ; i++ ) {
readers[ i ] = new FileReader();
readers[ i ].index = i;
readers[ i ].onload = function (loadEvent) {
var index = loadEvent.target.index;
datas.push({
lastModified: files[index].lastModified,
lastModifiedDate: files[index].lastModifiedDate,
name: files[index].name,
size: files[index].size,
type: files[index].type,
data: loadEvent.target.result
});
if ( datas.length === files.length ){
scope.$apply(function () {
scope.fileread = datas;
});
}
};
readers[ i ].readAsDataURL( files[i] );
}
});
}
}
});
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2017-06-28 03:13:06
Spróbuj tego,to działa dla mnie w angular JS
let fileToUpload = `${documentLocation}/${documentType}.pdf`;
let absoluteFilePath = path.resolve(__dirname, fileToUpload);
console.log(`Uploading document ${absoluteFilePath}`);
element.all(by.css("input[type='file']")).sendKeys(absoluteFilePath);
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2017-12-15 12:50:41