在我的项目中,我尝试上传图像,将其读取为 dataURL 并将其存储到我的数据库中。
我的 HTML ng-click 使用 true 或 false 作为参数调用这些方法(一个执行 body 图像,另一个执行个人资料图像)
根据调用的是 true 还是 false,它会更改事件的 ID。
出于某种原因,当它“真实”时,一切都工作得很好。用户可以选择图像,它会被正确发送到数据库,并且图像会被正确加载。
但是,当调用“false”时,我收到错误:
[$rootScope:inprog] $apply already in progress
然后 console.log() 测试“2222”不会被调用。
HTML
<img src="{{controller.myCause.causeImage}}" ng-click="controller.uploadImage('true')" alt="Your Image Here" class="cause-img" id="profileImage" style="width: 80%; height: 35%;" height="300" />
<input id="imageUpload" type='file'>
<img src="{{controller.myCause.causeThumbnailImage}}" ng-click="controller.uploadImage('false')" alt="Your Thumbnail Here" id="profileImageThumb" class="cause-img" style="width: 80%; height: 20%;" height="200" />
<input id="profileImageUpload" type='file'>
客户端
/////////////////////////////////////
//Begin Uploading Cause Profile Image
public uploadImage(bool) {
if (bool === "true") {
$("#imageUpload").click();
this.imgUpload(bool);
} else {
$("#profileImageThumb").click();
this.imgUpload(bool);
}
}
public imgUpload(bool) {
console.log(bool);
var _this = this;
var id = "";
var imgId = "";
if (bool === "true") {
id = "#imageUpload";
imgId = "#profileImage";
} else {
id = "#profileImageUpload";
imgId = "#profileImageThumb";
}
console.log("111");
$(id).change(function () {
console.log("2222");
if (this.files && this.files[0]) {
var reader = new FileReader();
reader.readAsDataURL(this.files[0]);
$(imgId).attr('src', this.files[0]);
_this.convertFileToBase64AndSet(this.files, bool);
}
});
};
convertFileToBase64AndSet(fileList: FileList, bool) {
var self = this;
if (fileList.length > 0) {
var reader = new FileReader();
reader.onloadend = (e: Event) => {
self.postProfileImage(reader.result, bool);
}
reader.readAsDataURL(fileList[0]);
}
}
public postProfileImage(file, bool) {
if (bool === "true") {
this.$http.put(`api/causes/profpic`, JSON.stringify(file)).then((res) => {
this.$state.reload();
});
} else {
this.$http.put(`api/causes/thumbpic`, JSON.stringify(file)).then((res) => {
this.$state.reload();
});
}
}
//End Cause Profile Image Upload
////////////////////////////////
最佳答案
您的点击事件正在运行摘要周期,该周期与当前摘要周期冲突。
您可以使用setTimeout()
你能试试这个吗
public uploadImage(bool) {
if (bool === "true") {
setTimeout(function({$("#imageUpload").click();})
this.imgUpload(bool);
} else {
setTimeout(function({$("#profileImageThumb").click();})
this.imgUpload(bool);
}
}
关于javascript - $rootScope :inprog $apply already in progress . 更改事件错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44422653/