Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is it possible to set a value on a $watched scope property that doesn't trigger the $watch callback?

Tags:

angularjs

Is it possible to set count and not trigger the $watch callback?

$scope.count=1;
$scope.$watch('count',function(){...});

Thanks.

like image 983
Francisc Avatar asked Dec 08 '13 00:12

Francisc


3 Answers

You could use setTimeout to wait for Angular's digest cycle to complete and then run your code:

setTimeout(function(){
    $scope.count = 1;
},0)

This way the angular code finishes running, checks for changes and then the property is set without getting Angular involved.

like image 68
Matt Zeunert Avatar answered Nov 08 '22 21:11

Matt Zeunert


No, but you can add control variable logic within your callback

$scope.$watch('count',function(){
 if ($scope.bypass) return;
 //else ....
});
like image 22
oori Avatar answered Nov 08 '22 19:11

oori


Kind of. You can use a $watch listener function. So instead of using:

$scope.$watch('count',function(){...});

You'd use:

scope.$watch(
  function() {
    // return the condition you do want evaluated.  Whenever this return value changes
    // from the previous $digest cycle the change handler function below will be called. 
    // The return value will be passed in as `newValue` (and the previous as `oldValue`)
    // in the change handler.
 },
function(newValue,oldValue){...});

Edit: Since it looks like you're trying to watch 2 different variables, another option may be to use watchCollection which will trigger if either changes (so you could have one consolidated handler for both):

$scope.$watchCollection(['count','otherCount'], function(newValues, oldValues) { ...});
like image 27
KayakDave Avatar answered Nov 08 '22 21:11

KayakDave