更改范围时无法获取范围变量

时间:2016-10-23 03:00:10

标签: javascript angularjs angularjs-scope

在我的HTML中,我有ng-init="find()"来调用此函数:

$scope.find = function()
{
    $scope.vehicles = Vehicles.query();
    $scope.vehiclesQtd = $scope.vehicles.length;
};

我的车辆显示在视图中,但$scope.vehiclesQtd始终为0

当我添加或删除车辆时,我添加了一个观察者来更改$scope.vehiclesQtd

$scope.$watch('vehicles', function()
{
    $scope.vehiclesQtd = $scope.vehicles.length;
    console.log(JSON.stringify($scope.vehiclesQtd, null, 4));
});

控制台始终返回0(当我控制$scope.vehicles时,返回始终为[]),但我的车辆正在显示。 我需要知道车辆长度,以限制车辆的创造。

1 个答案:

答案 0 :(得分:0)

假设$scope.vehicles = Vehicles.query();是一个获取结果的http调用,因为它是异步调用,即使在您的http调用完成之前,您的$scope.vehiclesQtd = $scope.vehicles.length;也会被执行。

为了获得确切的长度,请在观察者中添加if(newVal !== oldVal){,一旦您的http呼叫完成并且您的服务将数据返回$scope.vehicles,观察者将会触发,如果条件得到满足,现在您可以获取长度。

$scope.find = function(){
    $scope.vehicles = Vehicles.query();// this is a http call which is async..
    $scope.vehiclesQtd = $scope.vehicles.length;// this line is executed even before your above line i.e http call is completed ..
};

您可以在观察者中执行以下操作

$scope.$watch('vehicles', function(newVal,oldVal){
     if(newVal !== oldVal){
         $scope.vehiclesQtd = $scope.vehicles.length;
         console.log(JSON.stringify($scope.vehiclesQtd, null, 4));
     }
});