为什么Angular JS没有更新范围?

时间:2015-10-08 14:08:28

标签: angularjs

我有以下代码Angular JS:

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

此代码从AJAX服务返回response并将对象放入数组$scope.vm.events

因此,在模板中我不会将此添加的元素视为:{{vm.events}}

同一控制器中还有一个功能:

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

当我调用它时,我在模板中看到了新元素:{{vm.events}}

为什么第一种情况下代码不起作用?

2 个答案:

答案 0 :(得分: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});
    })
}

所以,在这种方法中,每当你想调用该服务时,只需调用此函数即可。这也是您的“添加”功能更新模板的原因,因为它位于控制器的“范围”和摘要周期中。

答案 1 :(得分:0)

如果你没有看到它,那是因为承诺没有得到解决。

请尝试在承诺的拒绝处理部分放置一些内容(在' then()'块中的第二个函数):

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()来触发摘要周期,以便更新数据。

通过添加第二个功能,您应该能够看到承诺是否得到解决,以及问题是否在其他地方。

相关问题