Javascript 在Angularjs$watch中使用闭包

Javascript 在Angularjs$watch中使用闭包,javascript,angularjs,closures,Javascript,Angularjs,Closures,我试图在$watch中使用闭包(它用于观察下拉列表中发生的更改)。我试图在第一次运行时为变量设置一个值,然后在下拉列表中为发生的更改替换该值。我觉得$watch中的闭包不能正常工作。请看这里: $scope.$watch('myDropDown', function () { // it's watching the dropdown $scope.monthsGroup = $scope.yearAndMonthsGroup.months; // months load

我试图在$watch中使用闭包(它用于观察下拉列表中发生的更改)。我试图在第一次运行时为变量设置一个值,然后在下拉列表中为发生的更改替换该值。我觉得$watch中的闭包不能正常工作。请看这里:

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


谢谢大家!

runOnlyOnce
确实只运行一次。。。对于创建的每个实例。问题是您正在创建多个实例,每次触发手表都会创建一个实例

只需将
runonlynce
创建代码放在手表外面,然后在手表里面调用即可:

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