簡體   English   中英

范圍變量更改時如何繼續調用函數?

[英]How to keep calling a function when scope variable changes?

我有一個看起來像的控制器

.controller('GraphsController', function($scope, TemperaturePoller, SoundPoller){
    $scope.temperatures = {readings: [], dateTimes: []}
    $scope.temperatures = TemperaturePoller.data;

    $scope.$watch(function(scope) {return scope.temperatures},
                  function(newValue, oldValue) {
                    console.log("Value Changed: " + newValue);
                    $scope.graph(newValue);
                  })

    $scope.graph = function(data) {
        console.log('values changes, refreshing graph');
    }
})

並且每10秒從Server檢索一次該值

.factory('TemperaturePoller', function($http, $timeout){
    var data = {};
    var poller = function() {
        $http.get('http://localhost:8080/monitoring/rest/graph/temperature').then(function(r){
            data = extractTemperatureReadings(r.data)
            data.calls++;
            $timeout(poller, 10000)
        });
    }
    poller();

    return {
        data: data
    }
})

我想$scope.graph要每次調用$scope.temperature變化

我在瀏覽器console.log看到它只被調用了一次

值更改:[對象對象] monitoring.js:19個值更改,刷新了圖形

自從我知道API中的數據正在更改后,如何強制每10 seconds調用一次?

由於您正在查看的數據是一個對象,因此請將$watch函數上的objectEquality標志設置為true 這是第三個參數。

$scope.$watch('temperatures', function(newValue, oldValue) {
     console.log("Value Changed: " + newValue);
     $scope.graph(newValue);
}, true);

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM