2015-10-08 40 views
0

我有以下代碼角JS:爲什麼在Angular JS中沒有更新範圍?

appService.get({id : id}).then(function (response) { 
    $scope.vm.events.push({title: 'New event', type: 'important', draggable: true, resizable: true}); 
}) 

此代碼返回response從AJAX服務並提出反對陣列$scope.vm.events

所以,在模板我沒有看到這個增加的元素:{{vm.events}}

也有在同一個控制器的一個功能:

$scope.add = function(){ 
    $scope.vm.events.push({title: 'New event', type: 'important', draggable: true, resizable: true}); 
} 

當我把它叫做我在模板中看到新的元素:{{vm.events}}

爲什麼在第一種情況下不工作代碼?

+0

您是否確定代碼執行過?承諾是否能解決? – ryanyuyu

+0

'appService.get'是'jquery' ajax? –

+0

是的,我得到了與數組 – Xakerok

回答

1

這是因爲您服務中的回調函數在angularjs摘要循環之外。

爲了解決這一點,有兩種方式:

方法1:

的第一種方式是使用$scope.$apply您在服務回調完成後立即如下:

appService.get({id : id}).then(function (response) { 
    $scope.vm.events.push({title: 'New event', type: 'important', draggable: true, resizable: true}); 
    $scope.$apply(); //this for updating your scope outside the digest cycle 
}) 

方法2:

包裝一下你的服務代碼函數內部控制器的範圍內,如下所示:

$scope.fn = function() { 
    appService.get({id : id}).then(function (response) { 
     $scope.vm.events.push({title: 'New event', type: 'important', draggable: true, resizable: true}); 
    }) 
} 

因此,在這種方法中,每當你要撥打的服務只是調用這個函數。這也是「添加」功能更新模板的原因,因爲它位於控制器的「範圍」和摘要循環中。

+0

我現在使用第二種方法,它不起作用,當我使用'$ scope。$ apply();'我得到:'錯誤:[$ rootScope:inprog] http://errors.angularjs.org/1.4 .7/$ rootScope/inprog?p0 =%24digest at Error(native)' – Xakerok

+0

我認爲這個答案是downvoted,upvoting – danday74

0

如果您沒有看到它,那是因爲承諾沒有得到解決。

會盡力把東西甩(以下簡稱「那麼()塊內的第二功能)處理的承諾的一部分:

appService.get({id : id}).then(function (response) { 
    $scope.vm.events.push({title: 'New event', type: 'important', draggable: true, resizable: true}); 
}, 
function(){ 
$scope.vm.events.push({title: 'ERROR_EVENT', type: 'ERROR_CALLBACK', draggable: true, resizable: true}); 
}); 

像其他人則建議,如果是這樣的角度之外,請調用$ scope。$ apply()或$ scope。$ digest()來觸發摘要循環,以便更新數據。

通過添加第二個函數,您應該能夠看到承諾是否得到解決,如果問題在別處。

相關問題