简体   繁体   English

$ scope。$ watch在AngularJS 1.6中不收听

[英]$scope.$watch does not listen in AngularJS 1.6

I have a problem with my script which collects data from database in parts. 我的脚本有问题,该脚本从部分数据库中收集数据。 I would like to inform Angular when downloading data is finished so I used $watch. 我想在下载数据完成后通知Angular,所以我使用了$ watch。 Unfortunatelly, it does not work. 不幸的是,它不起作用。 Angular calls function at the beginning instead of after change loadingComplete value. 角调用在开始时起作用,而不是在更改loadingComplete值之后起作用。

angular
.module('app')
.controller('tlmController', function($scope, $http) {
    var vm              = this;
    var data            = [];
    vm.countTestLines   = 0;
    vm.loadingComplete  = false;

    $scope.$watch('vm.loadingComplete', function() {
        console.log(data);
    });     

    $http({
        method: 'GET',
        url: 'app/server/tt/count_testlines.php'
    }).then(function successCallback(response) {
        vm.countTestLines = parseInt(response.data.count);

        downloadInParts(data, 0, vm.countTestLines);

    }, function errorCallback(response) {
        console.log('error');
    });

    var downloadInParts = function(data, offset, max) {         
        if(max < offset) { 
            vm.loadingComplete = true;
            return;
        }

        $http({
            method: 'GET',
            url: 'app/server/tt/get_testlines.php',
            params: { offset: offset }
        }).then(function successCallback(response) {
            data = data.concat(response.data);          
            downloadInParts(data, offset + 5, max);
        }, function errorCallback(response) {
            console.log('error');
        });


    }

});

The problem is that the loadingComplete is not a part of the scope. 问题是loadingComplete不属于范围。 you should declare it as $scope.loadingComplete; 您应该将其声明为$scope.loadingComplete; .

If you are using var vm = this , which is the proper way according to JohnPapa's styleguide for AngularJS, you should rewrite your $watch to: 如果您使用的是var vm = this ,这是根据JohnPapa的 AngularJS 样式指南的正确方法,则应将$ watch重写为:

$scope.$watch(function(){ return vm.loadingComplete }, function() {
    console.log(data);
});

Update from comments: Your function parameter data hides your data variable from your controller. 注释更新:函数参数data对控制器隐藏data变量。

Since you are using 'vm' instead of '$scope', it is a necessary that you need to insert $scope.$apply in your function. 由于您使用的是'vm'而不是'$ scope',因此有必要在函数中插入$ scope。$ apply。

if(max < offset) { 
     vm.loadingComplete = true;
     $scope.$apply();
     return;
  }

$scope always watches for change in value and if there is any, Angular will call the $digest() function internally and the changed value will be updated. $ scope总是监视值的变化,如果有变化,Angular会在内部调用$ digest()函数,并且更改后的值将被更新。 Using 'vm' wont update the value which results in your problem. 使用'vm'不会更新导致您出现问题的值。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM