【问题标题】:Using Closure inside Angularjs $watch在 Angularjs $watch 中使用闭包
【发布时间】:2015-03-23 08:04:51
【问题描述】:

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

谢谢!

【问题讨论】:

    标签: javascript angularjs closures


    【解决方案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();
    });
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2015-04-03
      • 2016-12-12
      • 2013-10-24
      • 2013-02-13
      • 1970-01-01
      • 1970-01-01
      • 2016-04-09
      • 1970-01-01
      相关资源
      最近更新 更多