簡體   English   中英

有沒有辦法在$ watchGroup中觸發一次回調函數 Angularjs?

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

您可以添加一個標志,當兩個值第一次更改時(僅一次),該標志會更改。 之后您可以禁用手表。

這是一個例子: jsbin示例

也可以這樣寫: editted

在此示例中,只有當兩個文本框值第一次更改時,才會給出兩個文本框,然后手表將計數增加到1.之后,手表被禁用,因此即使發生更改,計數也不會增加文本框。

只需稍微更改代碼,您就可以從此示例中獲得所需內容。

這應該可以解決問題(未經測試):

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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM