Đây là một trọng lượng nhẹ chỉ thị tôi đã viết để giải quyết vấn đề này, phản ánh cách thức gắn kết các sự kiện góc cạnh.
Bạn có thể sử dụng các chỉ thị như thế này:
HTML
<input type="file" file-change="yourHandler($event, files)" />
Như bạn thấy, bạn có thể tiêm các file được chọn vào xử lý sự kiện của bạn, như bạn sẽ bơm một $ sự kiện đối tượng vào bất kỳ trình xử lý sự kiện nào.
Javascript
angular
.module('yourModule')
.directive('fileChange', ['$parse', function($parse) {
return {
require: 'ngModel',
restrict: 'A',
link: function ($scope, element, attrs, ngModel) {
// Get the function provided in the file-change attribute.
// Note the attribute has become an angular expression,
// which is what we are parsing. The provided handler is
// wrapped up in an outer function (attrHandler) - we'll
// call the provided event handler inside the handler()
// function below.
var attrHandler = $parse(attrs['fileChange']);
// This is a wrapper handler which will be attached to the
// HTML change event.
var handler = function (e) {
$scope.$apply(function() {
// Execute the provided handler in the directive's scope.
// The files variable will be available for consumption
// by the event handler.
attrHandler($scope, { $event: e, files: e.target.files });
});
};
// Attach the handler to the HTML change event
element[0].addEventListener('change', handler, false);
}
};
}]);
Nguồn
2014-10-27 15:34:31
Tôi đã sử dụng kỹ thuật tương tự này thành công. Thật xấu xí ... nhưng đó là điều tốt nhất chúng tôi có bây giờ. – Espilon
Điều gì xảy ra với ...? – user1876508
@ user1876508 "Sau khi bạn đã nhận được tham chiếu tệp, hãy khởi tạo đối tượng FileReader để đọc nội dung của nó trong bộ nhớ. Khi tải xong, sự kiện tải của người đọc được kích hoạt và thuộc tính kết quả của nó có thể được sử dụng để truy cập dữ liệu tệp." Từ http://www.html5rocks.com/en/tutorials/file/dndfiles/ –