Reputation: 360
I'm trying to use a closure inside $watch(it is used to watch the changes that occur in a dropdown) . I'm trying to set a value for a variable for the first running and then to replace it for the changes that occurs in the dropdown. I feel that closures are not working properly in the $watch. Please have a look here:
$scope.$watch('myDropDown', function () { // it's watching the dropdown
$scope.monthsGroup = $scope.yearAndMonthsGroup.months; // months loaded in the dropdown
$scope.month = $scope.monthsGroup[0];// set the first month as default
var runOnlyOnce = (function () {
var called = false;
return function () {
if (!called) {
$scope.month = $scope.monthsGroup[$scope.monthsGroup.length -1]; // set the last month as default for first running
console.log("Run it!");//it is running it over again when changes occur in the dropdown
called = true;
}
}
})();
});`
Thank you!
Upvotes: 1
Views: 242
Reputation: 40298
runOnlyOnce
runs indeed only once... for each instance created. The problem is that you are creating many instances, one for each time the watch is triggered.
Just place the runOnlyOnce
creation code outside of the watch, and just call it inside:
var runOnlyOnce = (function(){
var called = false;
return function(){
if(!called){
$scope.month = $scope.monthsGroup[$scope.monthsGroup.length -1]; // set the last month as default for first running
console.log("Run it!");//it is running it over again when changes occur in the dropdown
called = true;
}
}
})();
$scope.$watch('myDropDown', function () {
$scope.monthsGroup = $scope.yearAndMonthsGroup.months; // months loaded in the dropdown
$scope.month = $scope.monthsGroup[0];// set the first month as default
runOnlyOnce();
});
Upvotes: 1