如何在回调函数中获取 AngularJS 中 $scope 变量的当前状态



>我在将服务/工厂用于 REST 接口并在 create 方法的回调函数中访问$scope变量的当前数据时遇到问题:

controllers.controller('ResourceAddCtrl', ['$scope', ... 'Resource','ResourceComb',
        function($scope, ...) {
            ...
            $scope.selectedEntryId = {};
            $scope.resource = new Resource();
            $scope.addResource = function(){
                $scope.resource.$create(function(response){
                    var id = response.id;
                    console.log($scope.selectedEntryId);
                    //ResourceComb.$create({res_id : id, rescomb_id : $scope.selectedEntryId},function(){});
                }); 
            };
        }]);

问题是$scope.selectedEntryId在回调方法中始终是它的初始值,尽管它在 html 代码中使用了 ng-model 并且值得到了完美的更新,因为 {{selectedEntryId}} 在 bindet 输入字段中键入数字时会产生预期的输出。有人知道我的错误在哪里或我如何解决问题吗?

这可能太明显了,无法解决您的问题,但在我看来,您需要在返回范围后设置值。

// fwiw I'd prob. make the default a string
$scope.selectedEntryId = '';
$scope.resource = new Resource();
$scope.addResource = function(){
  $scope.resource.$create(function(response){
    // Set the ID on the scope
    $scope.selectedEntryId = response.id;
    // This is trivial now, but it will be the correct value
    console.log($scope.selectedEntryId);
    // ...and the HTML should automatically update itself, as well.
  }); 
};

我假设Resource是一个ngResource,在这种情况下,你传递给$create的函数不是回调。

从文档中:

  • HTTP GET "class" actions: Resource.action([parameters], [success], [error])
  • 非 GET "类"操作:Resource.action([parameters], postData, [success], [error])
  • 非 GET 实例操作:instance.$action([parameters], [success], [error])

AngularJS $resource Docs

所以在你的代码中,你实际上是在传递[parameters],而不是[success] - 因此当函数运行时尚未进行调用,因此selectedEntryId是它的初始值。

鉴于此,请尝试以下方法:

$scope.addResource = function(){
     $scope.resource.$create(null, function(response){
        var id = response.id;
        console.log($scope.selectedEntryId);
        //ResourceComb.$create({res_id : id, rescomb_id : $scope.selectedEntryId},function(){});
     }); 
};

好吧,真正的问题是不同的。我尝试了一个新的简单示例(Plunker)并发现原因一定是ngInclude的问题。我没想到这会产生效果:看这个例子:在主控制器中更改模型始终沿一个方向更新,但相反,在包含的页面中更改控制器变量 X 不会更新。

最新更新