rxdazn
rxdazn

Reputation: 1390

variable change not notified to `$scope.$watch`

I am handling a JQRangeSlider through an angular directive + controller.

Within my controller, I am assigning new values to scope variables but there change is not notified to the controller scope (I am using isolated scope '=' in my directive) even though it is correctly updated.

// JQRangeSlider event handler
var valuesChanged = function(e, data) {
    if (data.values.min && data.values.max) {

        console.log('values changed', data.values); // this is always printed
        $scope.minselectedtime = data.values.min; // not triggering $scope.$watch
        $scope.maxselectedtime = data.values.max; 
        $scope.$broadcast('minchanged', $scope.minselectedtime); // instantly triggering $scope.$on('minchanged',...)
        console.log('scope', $scope);
    }
};


$scope.$watch('minselectedtime', function(newValue, oldValue) {
    if (newValue === oldValue) {
        return;
    }
    console.log('minselectedtime -->', newValue);
}, true);

$scope.$on('minchanged', function(event, min) {
    console.log('minchanged ==>', min);
});

$scope.$watch('minselectedtime', ...) is only triggered on the next $scope modification (where $scope.minselectedtime is not even modified):

$scope.toggleTimeScale = function(refinementString) {
    console.log('scale set to', refinementString);
    $scope.timescale = refinementString; // year, month, day...
} 

Why isn't $scope.$watch immediatly notified of the variable change?
The isolated code has its $scope.minselectedtime value changed but the parent scope doesn't see its value changed until $scope.toggleTimeScale is triggered.

Upvotes: 0

Views: 1289

Answers (1)

Mathew Berg
Mathew Berg

Reputation: 28750

Your method of using $scope.$apply() is correct. The reason being that the update from JQRangeSlider happened 'outside' of angularjs knowledge. If you read the documentation on the $apply method (http://docs.angularjs.org/api/ng.$rootScope.Scope#$apply) you'll see that it's used in the case you need.

Upvotes: 1

Related Questions