我在我的主页中包含一个 html 文件,使用
<div ng-controller="detailViewCtrl" ng-include="'partials/template.html'"></div>
在这个脚本中有一个显示一些文档的列表。
<li ng-repeat="document in relatedDocuments" style="cursor: pointer;" class="box" ng-click="gotoDocument(document)">
<div><i class="fa fa-file-pdf-o"></i> <span>{{document.name | limitTo: 20 }}{{document.name.length > 20 ? '...' : ''}}</span></div>
<md-tooltip md-direction="top">
{{document.name}}
</md-tooltip>
<thumbnail file-type="{{document.filetype}}" source="document.fullpath" max-height="150" max-width="210"></thumbnail>
</li>
在某些时候使用另一个模板中的按钮,以几乎相同的方式包含在内,我可能会上传一个新的 pdf 文件。该文件已上传到我的服务器,并进行查询以请求文档列表(现在预计将包含此新文档)。此查询与最初调用以填充 relatedDocuments
的函数相同。这一次,无论我上传多少文件,列表都没有更新。只有当我刷新时,我才会看到新上传的文件。
我自己尝试强制执行 $digest
不会有任何效果,而且我的 View 将保持不变,即使在 promise 得到解决后我可以在我的控制台中看到打印的列表。
Controller 看起来像这样:
.controller('detailViewCtrl', function($scope, $i18next, $routeParams,...
$scope.relatedDocuments = [];
$scope.getRelatedDocuments = function(document) {
myAPI.getRelatedDocuments($scope.id).then(function(response) {
$scope.relatedDocuments = response.data.result;
console.log("getRelatedDocuments", $scope.relatedDocuments);
});
};
$scope.getRelatedDocuments();
此模块内还有一个 uploadDocument()
函数,在上传文档后调用 getRelatedDocuments()
。此函数使用 ng-file-upload处理到服务器的实际数据传输。
$scope.uploadFile = function(file) {
file.upload = Upload.upload({
url: tempPath,
method: 'POST',
file: file,
sendFieldsAs: 'form',
fields: {
docid: $scope.id
}
});
file.upload.then(function(response) {
$timeout(function() {
file.result = response.data;
});
}, function(response) {
$scope.getRelatedDocuments(); // Here I try to update the list
if (response.status > 0)
$scope.errorMsg = response.status + ': ' + response.data;
}, function(evt) {
file.progress = Math.min(100, parseInt(100.0 * evt.loaded / evt.total));
});
}
在主页面某处按下相应按钮后调用此上传函数。因为我可以看到日志消息和响应,所以我假设一切正常。
可以找到包含代码相关部分的 plunk here .它不起作用,因为它需要后端来保存和获取文档列表,但它仍然是一个很好的引用。
有人知道为什么会这样吗?
最佳答案
似乎我不应该在包含这两个模板时使用 ng-controller 指令,因为它们是从也使用相同 Controller 的页面调用的。如果您将相同的 Controller 嵌套在自身上,那么 Angular 可能会以意想不到的方式运行。
关于javascript - 即使在使用 $apply 之后 Angular 也不会更新 View ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33549691/