简体   繁体   中英

How to keep calling a function when scope variable changes?

I have a controller that looks like

.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');
    }
})

and the value is retrieved from Server every 10 seconds

.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
    }
})

I want the $scope.graph to be called everytime the $scope.temperature changes

I see on browser console.log , that it is called just once

Value Changed: [object Object] monitoring.js:19 values changes, refreshing graph

How can I force it to be called every 10 seconds since I know the data from API is changing?

Since the data you're watching is an object, set the objectEquality flag on the $watch function to true . This is given as a third parameter.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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