在$ promise解决后,视图中的值不会更新

时间:2016-02-17 00:41:33

标签: angularjs data-binding ionic-framework angularjs-scope

我的视图中有一个值,在调用服务方法后没有更新。

以下是控制器中的相关代码:

$scope.remaining = 20;

AcctService.getCurrentCount.get(calculateRemaining); //This is a $resource method

function calculateRemaining(result) {
    $scope.remaining -= result;
    alert($scope.remaining);
}

以下是.getCurrentCount的代码:

service.getCurrentCount = $resource('/api/getCount', {}, {
        'get': { method: 'GET', isArray: true }
    });

使用上面的代码,例如,返回的result为5.“15”将被警告。但是,在视图中,{{remaining}}仍为20.没有错误,视图不会更新。

我尝试了以下内容:

  • $ timeout - 没有什么不同发生
  • 使$scope.remaining具有属性“value”的对象。 (我在另一篇文章中读到了关于原语与引用的数据绑定问题)。没有区别。
  • $ promise和.then() - 没有区别
  • $ apply会导致摘要错误

注意,我也在使用Ionic编码,不确定它是否有所作为。我在Ionic配置中禁用了缓存,另一个返回数组的服务方法按预期传播了ng-repeat。

谢谢!

2 个答案:

答案 0 :(得分:0)

我不确定get()函数内部的内容是什么,但看起来不对。 假设get()返回一个promise,你应该这样写:

AcctService.getCurrentCount.get().then(calculateRemaining); //This is a $resource method

答案 1 :(得分:0)

首先,您不需要创建get方法来返回数组。使用默认'查询' $ resource的方法。并且该方法的第一个参数是参数对象。第二个是成功功能。所以改变你对此的服务

service.getCurrentCount = $resource('/api/getCount');

后来用它作为

AcctService.getCurrentCount.query({},calculateRemaining); 

同时检查您是否使用单向数据绑定{{:: remaining}}

而且你还必须确保使用正确的$ scope,以检查make"剩余的"一个物体的一个领域。你可以这样做:

$scope.myData = {};
$scope.myData.remaining = 20;

稍后在控制器上初始化它并在html

{{myData.remaining}}

你也可以使用$ scope.apply();但实际上是在不同情况下使用