javascript - 使用$watch,表div消失

标签 javascript jquery html angularjs angular-datatables

我正在使用isteven-multi-select多选下拉指令。我给它thingsList它创建了checkedList当我选择事物时。

所以一开始我使用按钮确认选择和 ng-click触发postFunctioncheckedList 。而且效果很好。

但后来我决定添加一个观察者,这样我就不需要按下按钮了。正如我在 Debug模式下看到的,它正在工作(列表更新正确),但存在问题。我在页面上显示更新后的列表 datatables 。但不知何故,在下拉菜单中选择任何内容后($watch event)<div> with table正在消失。它不是 ng-show 或从 DOM 本身消失的东西。

我不知道为什么。

this.postThings = function (checkedList) {
        $http.post("/list/" JSON.stringify(checkedList)).then(
            function success(response) {
                $scope.thingsList.splice(0);   
                Array.prototype.push.apply($scope.thingsList, response.data);
            },
            function error(data) {
                console.log(data);
                $.notify({message: data.data.message}, {type: 'danger'});
            }
        );
    };


$scope.$watch(function (scope) {
            return scope.checkedList
        },
        function (newValue, oldValue) {
            if ($scope.checkedList.length == 0) {
                vm.bindBack();
            } else {
                vm.bindNew($scope.checkedList);
            }
        });

指令:

<isteven-multi-select input-model="thingsList"
                          output-model="checkedList"
                          button button-label="icon name"
                          item-label="icon name maker"
                          tick-property="check">
</isteven-multi-select>

消失的 HTML:

        ...
        <div class="table-responsive">
            <h3>Things:/h3>
            <table datatable="ng" class="display">
                <thead>
                <tr>
                    <th>ID</th>
                    <th>Name</th>
                </tr>
                </thead>
                <tbody>
                <tr ng-repeat="thing in thingsList">
                    <td>{{thing .id}}</td>
                    <td><a ui-sref="thing Info({thing Id: thing .id})">{{thing .name}}</a></td>
                </tr>
                </tbody>
            </table>
        </div>
        ...

最佳答案

发现问题了。 Angular-datatables 中存在已知错误,多次重新渲染会以某种方式从 DOM 中删除

https://github.com/l-lin/angular-datatables/issues/729

So the idea is to stop constant rerendering, not trigger the bug.

对我来说,解决方案是添加检查 newValue 的长度是否与 oldValue 不同。现在没有持续的重新渲染并且工作正常。

$scope.$watch(function (scope) {
        return scope.checkedList
    },
    function (newValue, oldValue) {
     if(newValue.length != oldValue.length) {
        if ($scope.checkedList.length == 0) {
            vm.bindBack();
        } else {
            vm.bindNew($scope.checkedList);
        }
     }
    });

关于javascript - 使用$watch,表div消失,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38304725/