我正在尝试构建一个单页应用程序,其中列出了我的本地数据库(MongoDB)中的一些文件,但 AngularJS 没有向我显示数据。当我通过 Postman 从 Express-API 获取它们时,一切正常。我通过一个控制器获取它们,该控制器调用一个工厂,这是获取数据。但是当我从数据库中删除一个文件时,AngularJS 并没有更新表。当我重新加载页面时,它显示的是没有删除项目的正确数据,但为什么 2-way-databinding 不起作用?
这是我的 index.html 中的表格内容:
<div ng-controller="FileCtrl">
<div ng-hide="files.length" class="alert alert-warning">Noch keine Files vorhanden!</div>
<table ng-show="files.length" class="table">
<tr>
<th>ID</th>
<th>Name</th>
<th>Path</th>
<th></th>
<th></th>
</tr>
<tr ng-repeat="file in filtered = (files | filter:searchtext | orderBy: 'name')" class="files-item">
<td>{{file._id}}</td>
<td>{{file.name}}</td>
<td>{{file.path}}</td>
<td><a href class="btn btn-default btn-sm" ng-click="fileFactory.playFile(file);">Play</a></td>
<td><a href class="btn btn-default btn-sm" ng-click="fileFactory.removeFile(file._id);">Delete</a> </td>
</tr>
</table>
</div>
这是我的 app.js:
angular.module('picube', [])
.factory('fileFactory', function($http) {
var files = [];
return {
getFiles: function(callback) {
$http.get('http://localhost:8080/api/files/').then(function (Response) { //takes all files from the api, tested with postman
files = Response.data; //Update Data
callback(files);
});
},
postFile: function(filepath){
$http.post("http://localhost:8080/api/files/", filepath).then(function (Response) { //adds a new file to the server-api, tested with postman
files = Response.data; //Update Data
});
},
playFile: function(filepath){ //this is not important at the moment
console.log("Play called");
console.log(filepath);
},
removeFile: function(_id){ //deletes a file from server, tested with postman
$http.delete("http://localhost:8080/api/files/" + _id).then(function(callback){
files = callback.data; //Update Data
});
}
};
})
.controller('FileCtrl', function($scope, fileFactory) {
$scope.fileFactory = fileFactory;
init();
function init() {
fileFactory.getFiles(function(files){
$scope.files = fileFactory.files;
});
}
});