在 Angularjs $watch 中使用闭包

Using Closure inside Angularjs $watch

我正在尝试在 $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;
                }
            }
        })();
    });`

http://jsfiddle.net/svaos5d9/

谢谢!

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

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

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