0

In my HTML template I have the following:

<a ng-href="{{ person | personLink }}">

person is set in the controller as:

$scope.person = Person.get({examId: $routeParams.personId});

and Person is a resource:

  app.factory('Person', [
    '$resource', function($resource) {
      return $resource('/api/people/:personId/', {
        personId: '@personId'});
    }
  ]);

The problem is the filter gets called before the promise is ready and results in reading undefined values. What is the correct way to deal with this?

Right now I use an if check on the attribute, but this does not seem ideal:

renderFilters.filter('personLink', function() {
  return function(person) {
    if(person.ages) {
        return '#/ages/' + person.ages;
    }else{
        return '#';
    }
  };
});
1
  • is it because promises are not unwrapped anymore in templates? docs.angularjs.org/guide/… And as far as I know you cannot re-enable this either in the latest release as you used to be able to do before. Commented Jul 15, 2014 at 2:12

2 Answers 2

1

A promise can be accessed like:

    Person.get({examId: $routeParams.personId}).$promise.then(function(p) {
                   $scope.person = p; 
      });

But your issue seem to be a problem with the filter than the promise. Since its part of the data binding expression it will be called with a null value during initialization.

Consider the test case where the Person.get is passed a personid that's not in your database. You will get a undefined error still. I am not sure whether this could be be solved with accessing the promise. You might still have to handle it in the filter. I would change the if condition in the filter to:

    if(person)
       return '#/ages/' + person.ages;
    else
       return "#";

Another option is to initialize the person object with some dummy data in the controller init. Like:

     $scope.person={"ages":"#"};

I don't think that's a clean solution any way.

Sign up to request clarification or add additional context in comments.

Comments

0

The "correct" way is to use ng-if to keep the elements from showing before your data is ready. Not in your JS, but in your HTML. That's basically it. This can be fine tuned depending on what your desired implementation is, so if you want something special let us know exactly what your aim is.

3 Comments

How do I know when the data is "ready"? As in, given the promise object, how do I query it for readiness?
have the promise populate a variable. when that variable is no longer undefined, the data is ready.
There is no way to directly query the promise to get that information? What is the best way to have the promise from a resource populate an additional variable?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.