[英]Is there a way to trigger callback function just once in $watchGroup | Angularjs?
我在我的角度項目中看到兩個值: $scope.$watchGroup( ['currentPage', 'newStatus'], $scope.setPage )
。
當兩個值都在改變時,$ scope.setPage會相應地執行兩次,但它應該一次。 怎么實現這個?
我的代碼:
JS
app.controller('CategoryListCtrl', ['$scope', '$http', '$location', '$route', function($scope, $http, $location, $route) {
$scope.numPerPage = 5;
$scope.currentPage = 1;
$scope.newStatus = -1;
var currentPageChanged = false;
var newStatusChanged = false;
function setPage() {
// function's code based on requests to db
};
setPage();
// pagination based on db requests
$scope.$watchGroup( ['currentPage', 'newStatus'], function(newValues, oldValues) {
if ((newValues[0] != oldValues[0]) && !newStatusChanged) {
console.log(1);
// currentPage has changed
setPage();
currentPageChanged = true;
} else if ((newValues[1] != oldValues[1]) && !currentPageChanged) {
console.log(2);
// newStatus has changed
newStatusChanged = true;
} else {
console.log(3);
newStatusChanged = false;
currentPageChanged = false;
}
});
...
HTML
...
<th>
<select class="form-control"
ng-model="isPublic"
ng-options="isPublic.name for isPublic in isPublicScope"
ng-change="newStatus = isPublic.status; currentPage = 1;">
<option value="">Show all</option>
</select>
</th>
<tr ng-repeat="category in categories | filter:search">
</tr>
...
這應該可以解決問題(未經測試):
var w = $scope.$watchGroup( ['currentPage', 'newStatus'],
function(newValues, oldValues) {
if ((newValues[0] != oldValues[0]) || (newValues[1] != oldValues[1])) {
$scope.setPage;
// clear $watchGroup
w();
}
}
)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.