有没有办法触发一次回调函数,仅在$ 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示例

也可以像这样写:编辑

在此示例中,仅给出了两个文本框,只有当两个文本框值首次更改时,手表将计数增加到1。之后,手表被禁用,因此即使在更改时,计数也不会增加发生在文本框中。

随着代码的略有更改,您可以从此示例中获得想要的东西。

这应该可以做到这一点(未测试):

var w = $scope.$watchGroup( ['currentPage', 'newStatus'],
    function(newValues, oldValues) {
        if ((newValues[0] != oldValues[0]) || (newValues[1] != oldValues[1])) {
          $scope.setPage;
          // clear $watchGroup
          w();
        }
    }
)

最新更新