如何将文件上传到ng重复模型?

时间:2017-09-12 21:37:41

标签: angularjs file

我有一个角度控制器,可以更新人员数据。使用文本和日期字段,这很好,我有

if let json = try JSONSerialization.jsonObject(with: jsonData) as? [String: Any],
    let siteStandardProfileRequest = json["siteStandardProfileRequest"] as? [String: Any],
    let urlString = siteStandardProfileRequest["url"] as? String,
    let url = URL(string: urlString) {
    let profileUrl = url
}

和组件代码:

<ul>
    <li ng-repeat="person in $ctrl.persons | filter:$ctrl.query">
      ...
      <div ng-show="person.edit">
        <label>Full Name*:</label><input class="edit-person" ng-model="person.fullname" /><br />
        <label>Birthdate:</label><input class="edit-person" type="date" ng-model="person.birthdate" /><br />
        <label>Deathdate:</label><input class="edit-person" type="date" ng-model="person.deathdate" /><br />
        <label>Description: </label><input class="edit-person" type="text" ng-model="person.description" /><br />
        <img ng-src="{{person.picture}}" width="100px" height="100px" /><br />
        <label>Picture: </label>
        <input class="edit-person" type="file" accept="image/*" 
               ng-file-select="handleEditPersonFiles(this.files);" /><br />
        <button ng-click="$ctrl.submitEdit(person); person.edit = false;">submit</button>
        <button ng-click="$ctrl.cancelEdit(); person.edit = false;">cancel</button>
     </div>
   </li>
</ul>

var self = this;

this.submitEdit = function(person){
  $http.post('/edit_person', {
    id: person.id,
    fullname: person.fullname,
    birthdate: person.birthdate,
    deathdate: person.deathdate,
    description: person.description,
    picture: person.picture
  }).then(loadPersons);
};

我在新人函数中阅读和上传图片没有问题,因为我有一个变量,只能handleEditPersonFiles = function(files){ var reader = new FileReader(); var that = this; reader.onload = function(){ ? = reader.result; }; reader.readAsDataURL(files[0]); }; ,但是使用编辑功能,我不知道在哪里分配读者结果,因为我无法通过角度访问person.picture变量。 onchange事件正确提交文件列表。但self.new_person_picture = reader.result似乎需要一个模型,并且在选择文件时不会触发。我也尝试了ng-change,但是当我选择要上传的文件时,似乎没有事件被触发。任何帮助将不胜感激。

1 个答案:

答案 0 :(得分:1)

这比您想象的要容易,您只需将person模型传递给handleEditPersonFiles模型。

HTML:

<li ng-repeat="person in $ctrl.persons ...
  ...
  <label>Picture: </label><input class="edit-person" type="file" accept="image/*" ng-file-select="handleEditPersonFiles(person, this.files);" />

JS:

handleEditPersonFiles = function(person, files){
  var reader = new FileReader();
  reader.onload = function(){
    person.picture = reader.result;
  };
  reader.readAsDataURL(files[0]);
};