[英]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.