5

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.)

4

2 に答える 2

0

promiseは将来の値 (通常は非同期操作の将来の結果)を表し、この値が利用可能になったとき、またはエラーが発生したときに何が起こるかを定義できます。

参照

var promise = asyncFunction(parameters); 

promise.then( 
 function (result) { 
 // Do Something with the result 
 }, 
 function (error) { 
 // Handle error (exception, etc). 
 }); 

ユーティリティ メソッドを使用して、任意の値をプロミスでラップできます$q.when()

  • $q.when(約束) → 約束
  • $q.when(nonPromise) → 新しい約束、それは
  • 指定された値 nonPromise に非同期的に解決されます。

==============================

あなたの例では:

HTML

<div ng-app ng-controller="testController">
    <p>Direct property: {{ property }}</p>
    <p>Function returning property: {{ getProperty() }}</p>
    <p>Direct promise: {{ promise }}</p>
    <p>Function returning promise: {{ out }}</p>
</div>

JS

function testController($scope, $q) {
    var deferred = $q.defer();
    deferred.resolve('some lazy text');
    $scope.promise = deferred.promise;

    $scope.out = $scope.promise.then(function (result) {
        console.log(result);
        return result;
    });


    $scope.property = 'some text';
    $scope.getProperty = function () {
        return $scope.property;
    };
}

デモフィドル

于 2013-10-23T22:31:15.387 に答える