0

I have the following, very simplified snippet:

c.then(function(data){
    vm.checkedOut = data;
});

It will either return a record, or it will not. Either way, the promise does return an object--it just might not have any record data attached.

So far, so good. Here's my question: how can I detect recordless responses in my views?

I was doing this:

<div ng-if="vm.checkedOut.loaneeName !== undefined">
    checked out!
</div>

loaneeName is a property of the record and it will be undefined if no record is returned. Kind of sloppy, but it works.

However this was how I displayed the opposite message:

<div ng-if="vm.checkedOut.loaneeName === undefined">
    not checked out!
</div>

Because vm.checkedOut.loaneeName will always be undefined when the page first loads (and waiting for responses from the API), the "not checked out!" message appears, at least for a while, which could be very bad if the connection speed is slow enough.

To fix this issue, I've done the following:

    c.then(function(data){
        vm.checkedOut = data;
        if(vm.checkedOut.loaneeName === undefined){
            vm.forRealsCheckedOut = true;
        }
        else {
            vm.forRealsCheckedOut = false;
        }
    });

And then:

<div ng-if="vm.forRealsCheckedOut === false">
    not checked out!
</div>
...

This works, but it also strikes me as a slightly gross workaround for what I assume should be a common problem.

I am not the first person to ask a question like this, but I don't have an array and other answers aren't much help.

Is there a better way?

Community
  • 1
  • 1
crowhill
  • 2,398
  • 3
  • 26
  • 55
  • You could at least simplify to `vm.forRealsCheckedOut = (vm.checkedOut.loaneeName === undefined);` and `ng-if="!vm.forRealsCheckedOut"`, but other than that it seems to be what you want. – Bergi Aug 17 '16 at 21:56
  • use **resolve** before loading the state (perform the api request and wait for it to return before rendering the view). – Muli Yulzary Aug 17 '16 at 23:53

1 Answers1

0

The basis of your problem is that if the connection is slow, then the "not checked out!" message will appear until the data is loaded. You need to detect when the data is actually loaded. You can do that by checking if vm.checkedOut is defined or not:

<div ng-if="vm.checkedOut !== undefined && vm.checkedOut.loaneeName === undefined">
    not checked out!
</div>

Only if vm.checkedOut is defined AND vm.checkedOut.loaneeName is defined will you see the "not checked out" message.

Or you could add a flag variable in your .then() function which will signal the ng-if statements that the data has been loaded and they can begin checking for the loaded values:

$scope.dataLoaded = false;

c.then(function(data){
    vm.checkedOut = data;
    $scope.dataLoaded = true;
});

<div ng-if="dataLoaded && vm.checkedOut.loaneeName === undefined">
    not checked out!
</div>
Dr. Cool
  • 3,713
  • 3
  • 22
  • 26