Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can Angular template call function returning promise

Angular's $q documentation says "$q promises are recognized by the templating engine in angular, which means that in templates you can treat promises attached to a scope as if they were the resulting values."

Angular's view templates also let you evaluate expressions, which means you can call functions exposed from the scope.

I've found that a view template is able to refer to real values, promises (which eventually resolve to real values), or functions returning real values, but not functions returning promises, which always render {} into the view template.

I created a fiddle with an example of this.

Can anyone do better or steer me in the right direction?

(Perhaps using a function in the view template is a bad idea; there are other problems with this technique, because Angular watching a function can't tell whether it's changed without calling the function, so the watched function gets evaluated on every digest cycle. I've seen these two questions and in both of them, the recommended answer was to use promise.then to change a normal property on the scope, and have the view template watch the normal property instead of the promise. I get that, but for my use I want to supply some parameters to calculate a value, and it's convenient to supply those parameters directly in the view template. Basically I'm trying to write something like url_for in Flask or Rails.)

like image 590
metamatt Avatar asked Nov 01 '22 12:11

metamatt


1 Answers

I'm not exactly sure, but if you return an object with the promise as a property, it works. (fiddle)

var deferred2 = $q.defer();
$scope.po = { promise: deferred2.promise };
$scope.getPo = function() {
    return $scope.po;
};

$timeout(function() {
    deferred2.resolve('some lazy text');
}, 2000);

HTML:

<p>Function returning promise (object): {{ getPo().promise }}</p>
like image 112
Jason Goemaat Avatar answered Nov 09 '22 04:11

Jason Goemaat