AngularJS promise

前端 未结 3 1544
别那么骄傲
别那么骄傲 2020-12-10 04:47

AngularJS docs say:

$q promises are recognized by the templating engine in angular, which means that in templates you can treat promises attached to a

相关标签:
3条回答
  • 2020-12-10 05:23

    You need to use the then() function on the promise object:

    this.getItem().then(function(result) {
       $scope.item = result;
    });
    

    In your case I don't think you need a promise. Angular's $watch system will take care of things. Just return an object in your function, not a primitive type:

    this.getItem = function () {
        var item = {};
    
        // do some async stuff
        $http.get(...).success(function(result) {
           item.title = result;
        });
        return item;
    };
    
    $scope.item = this.getItem();
    
    0 讨论(0)
  • 2020-12-10 05:48

    I believe the reason your first fiddle does not work is because you are essentially binding scope property item to a promise. When you attempt to alter the value by typing into the text field, angular notices the activity, and then reassigns/resets the value of item to the result of the promise (which hasn't changed).

    The solution provided by @asgoth sets/assigns the value of item once, when the promise is resolved. There is no binding going on here (i.e, item is not bound to the promise), so altering the value via the textbox does alter the value.

    0 讨论(0)
  • 2020-12-10 05:48

    Its like @Mark said, here you can find a Working Example of your snippet.

    Basically you were returning an object and not binding the model itself.

    $timeout(function(){
       $scope.item = {
          title: 'Some title'
       }; // Apply the binding
       deferred.resolve(); // Resolve promise
    },2000); // wait 2 secs           
    
    0 讨论(0)
提交回复
热议问题