伙计:在角度和节点webkit中创建应用程序 - 用户将文件排队等待下载,导航到其仪表板视图,这将启动下载。
我创建了一个包含文件数据对象的服务:
..
var downloadObj = {};
// fileObj = {'name':'The file name'; 'download_progress' : dlProgress}
showcaseFactory.myDownloads = function(eventId, fileObj) {
if(eventId){
console.log('update the object');
downloadObj['event_'+eventId] = fileObj;
}
console.log(downloadObj);
};
showcaseFactory.getDownloads = function() {
return downloadObj;
};
..
当仪表板视图加载时,ng-repeat
遍历$scope.downloadFiles
,引用此对象返回数据。
<div ng-repeat="file in downloadFiles">
<div><span>{{file.name}}</span> [{{file.download_progress}}%]</div>
</div>
我创建了一个自定义模块,利用node_modules
执行文件下载:
nwjsDownloadFactory.commenceDownload = function(event_id, url, dest, cb) {
var http = require('http');
var fs = require('fs');
var statusBar = require('status-bar');
var path = require('path');
// THIS UPDATES THE OBJECT AND DISPLAYS FINE --------- >>
var id = 7;
var testFileObj = {
'name' : 'This is the file name prior to the download...',
'download_progress' : 10
};
ShowCase.myDownloads(id, testFileObj);
// <<< THIS UPDATES THE OBJECT AND DISPLAYS FINE ---------
var file = fs.createWriteStream(dest);
var request = http.get(url, function(response) {
response.pipe(file);
file.on('finish', function() {
file.close(cb); // close() is async, call cb after close completes.
});
bar = statusBar.create({ total: response.headers['content-length'] })
.on('render', function (stats) {
// var percentage = this.format.percentage(stats.percentage);
// console.log(event_id + '....' + percentage);
var id = 7;
var testFileObj = {
'name' : 'This is the new file name during the download...',
'download_progress' : 35 // this will be replaced with percentage
};
ShowCase.myDownloads(id, testFileObj);
});
response.pipe(bar);
}).on('error', function(err) { // Handle errors
fs.unlink(dest); // Delete the file async. (But we don't check the result)
if (cb) cb(err.message);
});
}
问题:在行var request = http.get(url, function(response)
之前,对象会更新,并且更改会反映在UI中。但是,我需要不断更新对象,下载完成%,这样我就可以创建一个进度条。但是,当这个异步函数执行时,该对象
显示进行更新 - 请参阅随附的屏幕截图 - 但用户界面并未反映此内容。
有人可以引导我朝正确的方向发展 - 我需要在函数bar = statusBar.create({
期间更新对象,并在UI中反映更改。
答案 0 :(得分:1)
在对模型进行更改后调用$scope.$apply()
以通知Angular它必须更新UI。
showcaseFactory.myDownloads = function(eventId, fileObj) {
if(eventId){
console.log('update the object');
downloadObj['event_'+eventId] = fileObj;
$scope.$apply();
}
console.log(downloadObj);
};
如果您使用Angular的$http
对象,则会自动为您处理,但如果您从其他异步回调更新模型,则必须自行处理。
请参阅this blog post和this documentation page,了解有关正在进行的更深入的解释。