【发布时间】:2016-05-03 03:21:11
【问题描述】:
我可以添加和删除照片,但是当我这样做时,我必须刷新。我希望更新范围并自动完成,但是在添加文件后 get 永远不会运行。我必须使用 .apply 吗?
app.js
$scope.submit = function() {
if ($scope.file) {
$scope.upload($scope.file);
}
if($scope.files){
$scope.uploadFiles($scope.files);
console.log('this happens after upload files');
}
};
$scope.uploadFiles = function (files) {
if (files && files.length) {
for (var i = 0; i < files.length; i++) {
Upload.upload({
url: 'api/admin/photos',
data: {files: files[i]}
}).then(function(resp){
$scope.photos.push(resp.data);
$log.info(resp.data);
$log.info($scope.photos);
getPhotos();
},
function(resp){
console.log('Error status: ' + resp.status);
},
function(evt){
//var progressPercentage = parseInt(100.0 * evt.loaded / evt.total);
//console.log('progress: ' + progressPercentage + '% ' + evt.config.data.files.name);
});
}
}
};
//get all photographs
$scope.photos = [];
var getPhotos = function(){
$http.get('api/admin/photos/get')
.then(function successCallback(response){
$scope.photos.length = 0;
for (var i=0; i < response.data.length; ++i){
$scope.photos.push(response.data[i]);
}
$log.warn($scope.photos);
console.log('this happened automatically');
},
function errorCallback(error){
$log.warn(error);
});
};
getPhotos();
$scope.deletePics = function(id){
$http.delete('/api/admin/photos/' + id, {params : {id: id}})
.then(function successCallback(response){
//console.log(response);
$scope.photos = $scope.photos.filter(function(photo){
return photo.id !== id;
});
},
function errorcallback(error){
console.log(error);
});
};
当我提交上传时,在我的 console.log 中,这是我得到的:
[Object, Object]0: Object1: Objectlength: 2__proto__: Array[0]
app.js:375 这是自动发生的
但是,当我刷新代码时,图像会显示出来。
HTML
<form ng-controller="adminController" name="form" enctype="multipart/form-data">
Single Image with validations
选择 提交
<span class="progress" ng-show="progress >= 0">
<div style="width:{{progress}}%" ng-bind="progress + '%'"></div>
</span>
</form>
<ul >
<li ng-repeat="photo in photos"><img ng-src="img/{{ photo.url}}" />
{{ photo }}
{{photo.name}}
{{photos}}
<button class="button btn btn-warning" ng- click="deletePics(photo._id)">Delete</button>
</li>
</ul>
【问题讨论】:
-
如果
Upload不使用$http服务,那么是的。 -
所以把它放在一个方法中,在Ajax调用完成后调用该方法。
-
@epascarello 这将添加额外的请求以重新获取客户端上已经存在的所有数据。
-
好的,我做到了,现在在我的 console.log 中我看到了这个对象。现在我有一个很好的对象数组,但是我在视图中看不到它。它是未定义的。也许这是一个不同的范围?
-
我在下面发布了一个答案,但我只想添加这个,让您在 api/admin/photos 的帖子返回插入的照片(它的元数据),然后将其推送到 $ .then() 中的范围,保存到数据库的行程,仅在上传成功时更新(200 OK,201 OK)
标签: javascript angularjs multer ng-file-upload