简体   繁体   中英

$watch only triggering once

I'm using the smart table ( http://lorenzofox3.github.io/smart-table-website/ ) for AngularJS, and I've created a flag called isReset that will trigger a table reload. This happens because I have a directive watching the flag and will run refresh when isReset is set, and after it's done refreshing, it will set the flag off again.

My problem is, when I set the flag, it runs the first time, but after monitoring the behavior of the flag, it seems like it is never set back to false. I tried manually setting the flag to false, but next time around the $watch did not even trigger. My code is as follows, it would be great if you can help me shed some light on the issue. The weirdest thing is, I have another place where I am using it the exact same way, and it works as intended.

JS

        $scope.resetFilter = function() {
        $scope.timestampFilter = "";
        $scope.levelFilter = "";
    };

    $scope.getAPIServerLogs = function (tableState) {
        $scope.isLoading = true;
        ServerLog.get({
            "serverType": "API",
            "timestampFilter": $scope.timestampFilter,
            "levelFilter": $scope.levelFilter,
            "offset": tableState.pagination.start,
            "limit": tableState.pagination.number,
            "sortField": tableState.sort.predicate,
            "order": tableState.sort.reverse ? "desc" : "asc"
        }, function (response) {
            $scope.isLoading = false;
            $scope.serverlogs = response.data;
            $scope.displayedserverlog = [].concat($scope.serverlogs);
            tableState.pagination.numberOfPages = response.pages;
        });
    };

Directive

directives.directive('stReset', function () {
return {
    require: '^stTable',
    replace: false,
    scope: {stReset: "=stReset"},
    link: function (scope, element, attr, ctrl) {
        scope.$watch("stReset", function () {
            if (scope.stReset) {
                // reset scope value
                var tableState = ctrl.tableState();
                tableState.pagination.start = 0;
                tableState.sort.prediate = {};
                tableState.search = {};
                ctrl.pipe();
                scope.stReset = false;
            }
        }, true);
    }
};

HTML

<table st-table="displayedserverlog" st-safe-src="serverlogs" st-pipe="getAPIServerLogs"
   class="table table-striped table-hover logtable">
<thead st-reset="isReset">
<tr>
    <th st-sort-default="reverse" st-sort="timestamp" width="11%">Timestamp</th>
    <th st-sort="logger" width="30%">logger</th>
    <th st-sort="level" width="3%">Level</th>
    <th st-sort="thread" width="11%">Thread</th>
    <th st-sort="message" width="45%">Message</th>
</tr>
</thead>
<tbody ng-repeat="serverlog in serverlogs">
<tr ng-click="click(serverlog)" ng-class="{'tr-active':serverlog.isClicked, 'pointer danger':serverlog.exception}">
    <td>{{serverlog.timestamp | date: 'yyyy-MMM-dd hh:mm:ss'}}</td>
    <td>{{serverlog.logger}}</td>
    <td>{{serverlog.level}}</td>
    <td>{{serverlog.thread}}</td>
    <td>{{serverlog.message}}</td>
</tr>
<tr ng-show="serverlog.isClicked">
    <td colspan="6">
        <div class="row">
            <div class="col-md-12">
                <div>{{serverlog.exception}}</div>
                <pre><div ng-repeat="trace in serverlog.stacktrace track by $index" class="stacktrace">{{trace}}
                </div></pre>
            </div>
        </div>
    </td>
</tr>
</tbody>
<tfoot ng-hide="isLoading">
<tr>
    <td colspan="10" class="text-center">
        <div st-pagination="" st-items-by-page="50"></div>
    </td>
</tr>
</tfoot>

This plunker simulates your problem: http://plnkr.co/edit/c8crhe9ZR44GQBJ2sqm6?p=preview (have a look at the console)

    scope.$watch("flag", function(neww, old){
            count ++;
            console.log("inWatch " + count + ": " + neww + ', ' + old);
            if (scope.flag === true) {
                scope.flag = false;
            }
    });

Setting the flag to false in $watch basically means it will always be false (because: you modify the value --> $watch runs --> at the end of the function it sets the value to false --> value is false)

I have discovered a solution. Still not sure why it works, but I added

scope.$parent.$parent.isReset = false;

to the end of the directive, it works the way it is intended. However, replacing the existing

scope.stReset = false;

broke the other place I am using the directive. For now, I will do both. In the future when I'm smarter at AngularJS, I will revisit this issue. I hope this helps someone in the future so they don't waste 3 days trying to figure it out like I did.

try this.

var watcher = $scope.$watch('someScope', function(newValue, oldValue){
    if(newValue === 'yourValue') {
      watcher(); // stop this watch
    }
  });

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM