Issue
Angular JS - 1.6.9
Have been working on this for hours, confessedly, I am very not practised in Angular JS and would appreciate some guidance.
I have an element that every time information is updated in fields across a form, it will update a "preview pane" using the information from those fields, reading a template file, and substituting the values, printing that information to said preview pane. (Note: right now I'm reading every time every field is updated in any way, and I know this is bad, and later after I get THIS working, I will work on caching. So, I am not asking for help on this part, cos I know I have to address it and will later.)
I've tried this in so many ways and this is most recent attempt, after hours of fiddling and I just keep getting undefined
as a result to my console.
I am pretty confident this really just has to do with my absolute misunderstanding of asynchronous things.
I have had debugging info in fillTemplate() and it does successfully read the file, just, it is not getting to the browser.
HTML:
<div class="col text-monospace small shadow p-2 mb-2 pre-scrollable">
{{updateItemInformation()}}
</div>
var app = angular.module('app', ['ngSanitize']);
app.controller('c', ($scope, $sce) => {
$scope.updateItemInformation = async () => {
let result ;
const maxLineLength = 80;
result = await fillTemplate($scope.item) ;
console.log(result) ;
return result ;
};
async function fillTemplate(item) {
let result = "";
const response = await fetch(`./templates/${item.category}.template`)
const template = await response.text()
if(!template) return "";
return template ;
}
Solution
The issue seems to be with AngularJS not recognizing updates made by your async function. You'll need to trigger Angular's digest cycle
manually using $scope.$apply()
after your async operation.
Here's a more streamlined version of your code:
var app = angular.module('app', ['ngSanitize']);
app.controller('c', ($scope) => {
$scope.updateItemInformation = async () => {
const result = await fillTemplate($scope.item);
console.log(result);
$scope.$apply(() => {
$scope.template = result;
});
};
async function fillTemplate(item) {
const response = await fetch(`./templates/${item.category}.template`);
return response.text();
}
});
In your HTML:
<div class="col text-monospace small shadow p-2 mb-2 pre-scrollable">
{{template}}
<button ng-click="updateItemInformation()">Refresh Preview</button>
</div>
Added a button to trigger the update and display the result in {{template}}
. Hope this helps! Keep going; you're on the right track! 👍
Answered By - Krishan Saini
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.