AngularDart: file input model directive

Issue

I’m trying to make a directive similar to ng-model to work with file inputs. I am new to AngularDart so don’t really know how to go about doing this.

Here is some code I managed to write by looking at the ng-model source files but it (obviously) doesn’t work.

  @Decorator(
      selector: 'input[type=file][file-model]',
      map: const {'file-model': '&filesSelected'})
  class FileModel {
    final InputElement inputElement;
    String expression;
    final Scope scope;
    String _inputType;
    List<File> files;
    var filesSelected;

    FileModel(this.inputElement, this.scope, NodeAttrs attrs) {

      expression = attrs["file-model"];

      inputElement.onChange.listen((event) {
        files = inputElement.files;
        filesSelected(files);
      });
    }
  }

Any suggestions?

Solution

I’ve got it working.

@Decorator(
    selector: 'input[type=file][file-model]',
    map: const {'file-model': '&filesSelected'})
class FileModel {
  Element inputElement;
  String expression;
  final Scope scope;
  String _inputType;
  List<File> files;
  var listeners = {};

  FileModel(this.inputElement, this.scope) {
  }

  initListener(var stream, var handler) {
    int key = stream.hashCode;
    if (!listeners.containsKey(key)) {
      listeners[key] = handler;
      stream.listen((event) => handler({r"files": (inputElement as InputElement).files}));
    }
  }

  set filesSelected(value)  =>  initListener(inputElement.onChange, value);
}

Usage: <input type="file" multiple file-model="cmp.filesSelected(files)">

Answered By – andrei

Answer Checked By – Clifford M. (FlutterFixes Volunteer)

Leave a Reply

Your email address will not be published.