在Angularjs $ watch中使用Closure

时间:2015-03-23 08:04:51

标签: javascript angularjs closures

我正在尝试在$ 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/

谢谢!

1 个答案:

答案 0 :(得分:1)

对于每个创建的实例,

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