【发布时间】: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;
}
}
})();
});`
谢谢!
【问题讨论】:
标签: javascript angularjs closures