AngularJS Interpolation Error

angularjs

Solution

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 '-';
    }
}

Problem

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.

Original source