2014-10-02 63 views
0

我使用承諾。但是,當我的諾言解決了綁定到視圖不綁定到新的價值。Angularjs:承諾不會更新綁定

我做了一個小的jsfiddle:http://jsfiddle.net/58q8khap/8/

這裏的觀點:

<div ng-controller="MyCtrl"> 
    Hello, {{name}}! 
</div> 

,代碼:

var myApp = angular.module('myApp',[]); 

function MyCtrl($scope,ownservice) { 
    $scope.name = "Noname"; 
    ownservice.getname().then(function(result){ 
     $scope.name = 'Superhero'; 
    }); 
} 

myApp.service('ownservice', function ($q) { 
    this.getname = function() { 
     var deferred = $q.defer(); 
     setTimeout(function() { 
       deferred.resolve('Superhero'); 
     } , 1000); 
     return deferred.promise; 
     } 
}); 

回答

2

由角版本$timeout只需更換使用setTimeout。這樣的角度將迫使消化週期,並刷新你的範圍

工作小提琴:http://jsfiddle.net/cunuj46w/

請注意,你應該使用像$超時或$窗口也可用於測試全局的角度動力版本/嘲諷目的

+0

我的問題是另一個。這是一個簡單的例子。但由於你的回答,我發現了這一點。謝謝 – 2014-10-02 08:35:08

+0

更新您的問題/小提琴,如果需要;) – 2014-10-02 08:40:20

+0

沒關係。我認爲這是一個錯字或類似的東西 – 2014-10-02 08:41:04

1

此行之後

$scope.name = 'Superhero'; 

增加

$scope.$apply();