[英]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;
}
}
})();
});`
谢谢!
对于创建的每个实例, 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();
});
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.