2

In my ember application I've a file input DOM element. I bind the value attribute of the element to a controller property.

I do this to know when the file input's value changes. But I don't want to set the value from the controller. I mean one way binding. DOM element to controller and not controller to DOM element.

Handlebar code :

{{input type="file" name="pic" accept="image/*;capture=camera" id="newImage" value= imagePath}}

Controller :

App.ExampleController = Ember.ObjectController.extend({
    imagePath: null,
    imageChanged: function () {
        //Some Code
    }.observes('imagePath')
});

I need this because I get the following error

Uncaught InvalidStateError: Failed to set the 'value' property on 'HTMLInputElement': This input element accepts a filename, which may only be programmatically set to the empty string. thrown by jquery-1.11.1.min.js

Is there a way to fix this ?

Presse
  • 418
  • 1
  • 4
  • 23

2 Answers2

1

File inputs elements do not have a value attribute, you'll need to bind to the change event on the input and then access the files property.

see this answer for an implementation that might help you Ember.js: Upload file component

Community
  • 1
  • 1
Jakeii
  • 1,273
  • 9
  • 16
1

Using Controller

You can make one way binding using observer in which you are going to set the value manually.

App.ExampleController = Ember.ObjectController.extend({
    imagePath: null,
    imagePathValue: null,

    _imageChanged: function () {
        this.set('imagePath', this.get('imagePathValue'));
    }.observes('imagePathValue')
});

with

{{input type="file" name="pic" accept="image/*;capture=camera" id="newImage" value=imagePathValue}}

Using View

App.ExampleView = Ember.View.extend({
   _imageChanged: function () {
       this.$().find('#imageFile').on('keypress paste', function() {
           this.set('controller.imagePath', this.value);
       }.bind(this));
   }.on('didInsertElement')
});

with

{{input type="file" name="pic" accept="image/*;capture=camera" id="newImage" id="imageFile"}}

Using Ember.Binding.oneWay

One especially useful binding customization you can use is the oneWay() helper. This helper tells Ember that you are only interested in receiving changes on the object you are binding from.

App.ExampleController = Ember.ObjectController.extend({
    imagePath: Ember.Binding.oneWay("imagePathValue"),
    imagePathValue: null,
});

{{input type="file" name="pic" accept="image/*;capture=camera" id="newImage" value=imagePathValue}}
Mateusz Nowak
  • 4,021
  • 2
  • 25
  • 37
  • Thanks for the explanation. I can see this how one way binding is demonstrated in ember. But I meant to say a different thing. That is the changes in the DOM element should reflect in controller's property but the vice versa shouldn't happen. – Presse May 05 '15 at 09:46