简体   繁体   中英

Using Closure inside Angularjs $watch

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;
                }
            }
        })();
    });`

http://jsfiddle.net/svaos5d9/

Thank you!

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();
});

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