As you may already be aware I'm using UI-Router with my AngularJS app. I have a page which accepts user input, lets call it a profile page for this matter. Within this page I have a save button where the user can save the information they inputted. That part works great there are no issues.
What I want to do is save the page/ information on state change. What I was thinking of doing is, within my controller is something like this:
$rootScope.$on('$stateChangeStart', function (event, toState, toParams, fromState, fromParams) {
saveFile();
});
// Save Document
function saveFile() {
$(".page-loading").removeClass("hidden");
html2canvas($('#main_page'), {
// When image is rendered proceed with saving the file
onrendered: function (canvas) {
//$rootScope.contentJson.image = canvas.toDataURL();
var html = $('#main_page')[0].innerHTML;
for (var x in tmpList) {
if (tmpList[x].saveText === 'true') {
tmpList[x].element = tmpList[x].savedElement;
}
if (tmpList[x].saveText === 'tabs') {
for (var y in tmpList[x].tabType) {
tmpList[x].tabType[y].tabText = tmpList[x].tabType[y].savedElement;
tmpList[x].tabType[y].header = tmpList[x].tabType[y].savedHeader;
}
}
if (tmpList[x].saveText === 'table') {
for (var y in tmpList[x].layout) {
for (var z in tmpList[x].layout[y].row) {
tmpList[x].layout[y].row[z].text = tmpList[x].layout[y].row[z].savedText;
}
}
}
if (tmpList[x].saveText === 'accordion') {
for (var y in tmpList[x].accordion) {
tmpList[x].accordion[y].title = tmpList[x].accordion[y].savedTitle;
tmpList[x].accordion[y].content = tmpList[x].accordion[y].savedContent;
}
}
}
var data = {
'html': html,
'image': canvas.toDataURL(),
'json': JSON.stringify({"content": tmpList, "gallery": $scope.img, "audio": $scope.audio})
};
editorData.saveContent(data).then(function (response) {
$scope.pushAlerts('Saved');
$rootScope.lastSegment = '';
$(".page-loading").addClass("hidden");
// If its a new content
if ($rootScope.newElement == 'new-content') {
// Set Content ID
$rootScope.contentID = response.data.id;
// Set cookie for contentID
$cookies.put('contentID', $rootScope.contentID);
// Set new element to empty
$rootScope.newElement = '';
$cookies.remove('newElement');
// Redirect and populate contentID
$state.go('editor', {
topicID: $stateParams.topicID,
contentID: response.data.id
});
$state.reload();
}
var currentTime = new Date();
$scope.timeSaved = currentTime.getMinutes();
});
}
});
}
Which in my mind makes sense (maybe it doesn't in yours :) ). But the problem is the saveFile() function doesnt finish and state changes. Has anyone come accross a way for example to wait until this function finishes and only then continue with state change? Maybe create a promise?
Thanks