I am displaying the properties of a room as part of a room management application I am working on, this is the output:
As you can see, the value of Beamer (Projector in english) is "Sony (lamp 01/12/2013)". This output is correct but when I open my console I see some errors concerning interpolation:
Larger resolution:
"Can't interpolate: {{getBeamerString()}} TypeError: Cannot read property 'aanwezig' of undefined"
This is my html partial:
<section class="eigenschappen">
<table class="table table-striped table-hover table-bordered">
<thead>
<tr>
<th>Eigenschap</th>
<th>Waarde</th>
<th>Bewerk</th>
</tr>
</thead>
<tbody>
...
<tr>
<td><img class="ruimteNaam" src="../Images/Beamer.png" alt=""/>Beamer</td>
<td>{{getBeamerString()}}</td>
<td><img class="edit" src="../Images/Edit.png" alt=""/></td>
</tr>
...
</tbody>
</table>
</section>
currentRuimte (CurrentRoom in English) is a scope defined variable that gets its value using a resource service that gets that data from my mongoDB:
function RuimteController($scope, $routeParams, Ruimte) {
$scope.currentRuimte = Ruimte.get({
ruimteNaam: $routeParams.ruimteNaam
});
$scope.getBeamerString = function () {
var beamer = $scope.currentRuimte.beamer;
if(beamer.aanwezig == 'Ja'){
return beamer.typeBeamer + ' (lamp: ' + beamer.datumLamp + ')';
}else{
return '-';
}
}
}
When I inspect the scope using batarang I get this:
Why do I get the error and why do I still get the correct output? Is there a way to prevent the error from happening? Please correct me as much as you can, I am fairly new to AngularJS and Javascript in general and trying to expand my skillset.
String Interpolation in Angular 8 is a one-way data-binding technique that is used to transfer the data from a TypeScript code to an HTML template (view). It uses the template expression in double curly braces to display the data from the component to the view.
The problem is that
$scope.currentRuimte = Ruimte.get({ ruimteNaam: $routeParams.ruimteNaam });
Is an asynchronous operation. $scope.currentRuimte
is going to be a blank object when this call returns, and some time later, when the data is available, it will be filled in with the HTTP response.
This means that the first time your view is rendered, $scope.currentRuimte
is going to be {}
, and therefore $scope.currentRuimte.beamer
is going to be undefined
, so this line:
var beamer = $scope.currentRuimte.beamer; if(beamer.aanwezig == 'Ja'){ /* <-- undefined.aanwezig ! */ }
is going to raise an exception. You can solve this by making sure that beamer
is truthy first:
$scope.getBeamerString = function () { var beamer = $scope.currentRuimte.beamer; if(beamer && beamer.aanwezig == 'Ja'){ return beamer.typeBeamer + ' (lamp: ' + beamer.datumLamp + ')'; }else{ return '-'; } }
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With