javascript - Controller 和 HTML 之间的 AngularJs ng-model 延迟

标签 javascript html angularjs

我对 AngularJs 和 ng-model 有疑问,从 Controller 到 UI 有很大的延迟。在 $scope.selectedRisk 中我遇到了这个问题,在模态显示之前变量是正确的但是当模态打开时显示旧值并且在几秒钟后(我认为是 $inteval 时间)我可以看到正确的值。
这是 angularjs 代码(我发布了所有代码,但问题在最后):

'use strict';

//$routeParams allows to retrieve the parameters passe by url
app.controller('asocAdminController', ['$scope','$http','$routeParams', '$filter', 'toastService', '$interval', 'riskService', function($scope, $http, $routeParams, $filter, toastService, $interval, riskService)  {

    const TIMING_SYNCHRONIZE = 5000;
    $scope.counterError = 0;
    $scope.selectedRisk={};
    $scope.likelihood = {};
    const MAX_ERROR = 3;
    $scope.mqtt = {status:true,message:"Service running"};
    /*
     * Retrieve the mqtt status
     */
    $scope.mqttStatusFunction = function(){
        $http({
            method: 'GET',
            url: '/mqtt/',
        }).then(function successCallback(response) {
            if (typeof response.data.success == 'undefined'){
                window.location.href = "/500";
            }else if (response.data.success==true){
                $scope.mqtt.status = response.data.result;
                if ($scope.mqtt.status===true)
                    $scope.mqtt.message = "Service running";
                else if ($scope.mqtt.status===false)
                    $scope.mqtt.message = "Service not running";
                else
                    $scope.mqtt.message = "Service unknow";                     
            }else if (response.data.success==false){
                notifyMessage(response.data.result, 'error');
            }
        }, function errorCallback(response) {
            $scope.counterError++;
            if (counterError === MAX_ERROR){
                $('#errorConnectionModal').modal('show');
            }else {
                $scope.mqttStatusFunction();
            }
        });
    }

    $scope.likelihoodFunction = function(){
        $http({
            method: 'GET',
            url: '/likelihood/',
        }).then(function successCallback(response) {
            if (typeof response.data.success == 'undefined'){
                window.location.href = "/500";
            }else if (response.data.success==true){
                $scope.likelihood = response.data.result;
            }else if (response.data.success==false){
                notifyMessage(response.data.result, 'error');
            }
        }, function errorCallback(response) {
            $scope.counterError++;
            if (counterError === MAX_ERROR){
                $('#errorConnectionModal').modal('show');
            }else {
                $scope.likelihoodFunction();
            }
        });
    }

    $scope.tableInitialize = function(){
        //initialize datatable
        $scope.riskTable = $('#riskTable').DataTable({
            responsive: true,
            paging : false,
            order: [[ 0, "desc" ]],
            info: false,
            searching: false,
            select: {
                style: 'os',
                items: 'cell'
            },
            "ajax":{ 
                "url": "/risk/",
                "dataSrc": function ( json ) {
                    if (typeof json.success == 'undefined')
                        location.reload();
                    else if (json.success){
                        return json.result;
                    }else{
                        notifyMessage(json.result, 'error');   
                        return "";
                    }                           
                },  
                "error": function (xhr, error, thrown) {
                    location.reload();
                }
            },
            "columns": [
                {data:null, 
                    render: function ( data, type, row ) {
                        return data[0].severity;
                    }
                },
                {data:null, 
                    render: function ( data, type, row ) {
                        return  riskService.riskIcon(data[0].value);
                    }
                },
                {data:null, 
                    render: function ( data, type, row ) {
                        return  riskService.riskIcon(data[1].value);
                    }
                },
                {data:null, 
                    render: function ( data, type, row ) {
                        return  riskService.riskIcon(data[2].value);
                    }
                },
//              { 
//                  data:null, render: function ( data, type, row ) {
//                      return '<span style="cursor:pointer"><i class="fa fa-pencil-square-o fa-2x" aria-hidden="true" style="color:green" name="modifyRisk"></i></span>';
//                  }
//
//              },
            ],
        });
    }

    $('#riskTable').on( 'click', 'td', function () {
        let cell =$scope.riskTable.cell( this );
        $scope.selectedRisk = cell.data()[cell.index().column] ;
        $('#editRiskModal').modal('show');
    } );



    //Main
    $scope.mqttStatusFunction();
    $interval($scope.mqttStatusFunction,TIMING_SYNCHRONIZE);
    $scope.likelihoodFunction();
    $scope.tableInitialize();
}]);

HTML(我正在使用 Angular 路由来制作单页应用程序):

<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml"
    xmlns:th="http://www.thymeleaf.org"
    xmlns:sec="http://www.thymeleaf.org/thymeleaf-extras-springsecurity4"
    xmlns:layout="http://www.ultraq.net.nz/thymeleaf/layout">
<head>
<style type="text/css">
.color-red {
    color: red
}

.color-green {
    color: green
}

.color-grey {
    color: grey
}
}
</style>
</head>
<body>
    <!-- Content Wrapper. Contains page content -->
    <!-- Content Header (Page header) -->
    <section class="content-header">
        <h1>SAP</h1>            
    </section>

    <!-- Main content -->
    <section class="content">
        <div class="row">
            <div class="col-xs-12">
                <div class="box">
                    <div class="box-body">
                        <div class="row">
                            <div class="col-md-3 col-xs-12">
                                <div
                                    data-ng-class="{'box box-success': mqtt.status == true, 'box box-danger': mqtt.status == false, 'box box-warning': mqtt.status == null}">
                                    <!-- form start -->
                                    <form class="form-horizontal">
                                        <div class="box-body">
                                            <span
                                                data-ng-class="{'info-box-icon bg-red': mqtt.status == false, 'info-box-icon bg-orange': mqtt.status == null, 'info-box-icon bg-green': mqtt.status == true}"><i
                                                data-ng-class="{'fa fa-check': mqtt.status == true, 'fa fa-times': mqtt.status == false, 'fa fa-question': mqtt.status == null}"
                                                aria-hidden="true"></i></span>
                                            <div class="info-box-content">
                                                <span class="info-box-text" style="font-size: 25px;">{{mqtt.message}}</span>
                                            </div>
                                        </div>
                                        <!-- /.box-body -->
                                    </form>
                                </div>
                            </div>
                        </div>
                        <div class="row">
                            <div class="col-md-3 col-xs-12">
                                <div class="box box-info">
                                    <div class="box-header with-border">
                                        <h3 class="box-title">Likelihood</h3>
                                    </div>
                                    <!-- /.box-header -->
                                    <!-- form start -->
                                    <form class="form-horizontal">
                                        <div class="box-body">
                                            <div class="form-group">
                                                <label for="likelihoodA" class="col-sm-2 control-label">A</label>

                                                <div class="col-sm-4">
                                                    <div class="input-group">
                                                        <input type="number" class="form-control" id="likelihoodA"
                                                            data-ng-model="likelihood.a" min="0" max="100"> <span
                                                            class="input-group-addon">%</span>
                                                    </div>
                                                </div>
                                            </div>
                                            <div class="form-group">
                                                <label for="likelihoodB" class="col-sm-2 control-label">B</label>

                                                <div class="col-sm-4">
                                                    <div class="input-group">
                                                        <input type="number" class="form-control" id="likelihoodB"
                                                            data-ng-model="likelihood.b" min="0" max="100"> <span
                                                            class="input-group-addon">%</span>
                                                    </div>
                                                </div>
                                            </div>
                                        </div>
                                        <!-- /.box-body -->
                                        <div class="box-footer">
                                            <button type="submit" class="btn btn-info pull-right">Save</button>
                                        </div>
                                        <!-- /.box-footer -->
                                    </form>
                                </div>
                            </div>
                            <div class="col-md-9 col-xs-12">
                                <div class="box box-info">
                                    <div class="box-header with-border">
                                        <h3 class="box-title">Risk table</h3>
                                    </div>
                                    <!-- /.box-header -->
                                    <!-- form start -->
                                    <form class="form-horizontal">
                                        <div class="box-body">
                                            <table id="riskTable"
                                                class="table table-bordered table-striped"
                                                style="width: 100%;">
                                                <thead>
                                                    <tr>
                                                        <th>Severity</th>
                                                        <th>&lt;A</th>
                                                        <th>A&lt;x&lt;B</th>
                                                        <th>&gt;B</th>
                                                    </tr>
                                                </thead>
                                            </table>
                                        </div>
                                        <!-- /.box-body -->
                                    </form>
                                </div>
                            </div>
                        </div>
                    </div>
                </div>
            </div>
        </div>
    </section>
    <div class="modal" id="editRiskModal" data-backdrop="static"
        data-keyboard="false">
        <div class="modal-dialog modal-sm">
            <div class="modal-content">
                <div class="modal-header">
                    <button type="button" class="close" data-dismiss="modal"
                        aria-label="Close">
                        <span aria-hidden="true">&times;</span>
                    </button>
                    <h4 class="modal-title">Risk editing</h4>
                </div>
                <div class="modal-body">
                    <div class="box-body">
                        <form>
                            <div class="form-group">
                                <label for="severityInput">Severity</label> <input
                                    class="form-control" id="severityInput" placeholder="severity" data-ng-model="selectedRisk.severity" disabled >
                            </div>
                            <div class="form-group">
                                <label for="exampleInputEmail1">Email address</label> <input
                                    type="email" class="form-control" id="exampleInputEmail1"
                                    aria-describedby="emailHelp" placeholder="Enter email" disabled>
                                <small id="emailHelp" class="form-text text-muted">We'll
                                    never share your email with anyone else.</small>
                            </div>
                            <div class="form-group">
                                <label for="exampleInputPassword1">Password</label> <input
                                    type="password" class="form-control" id="exampleInputPassword1"
                                    placeholder="Password">
                            </div>
                        </form>
                    </div>
                </div>
                <div class="modal-footer">
                    <button id="exit" type="button" class="btn btn-primary pull-left"
                        data-dismiss="modal">Cancel</button>
                    <button id="refresh" type="button" class="btn btn-primary"
                        onClick="window.location.href=window.location.href">Save</button>
                </div>
            </div>
            <!-- /.modal-content -->
        </div>
        <!-- /.modal-dialog -->
    </div>
</body>
</html>

问题出在模态中,但如果我放在外面,问题仍然相同。 这是我第一次遇到这个问题。你能帮帮我吗?谢谢

最佳答案

问题似乎是 $("#riskTable").on("click", "td", function() {}

这不是真正的问题,但 AngularJs 没有收到有关更改的通知。

为此,您必须在此函数末尾调用 $scope.$applyAsync() 以启动 digest-cycle

$('#riskTable').on( 'click', 'td', function () {
  let cell =$scope.riskTable.cell( this );
  $scope.selectedRisk = cell.data()[cell.index().column] ;
  $('#editRiskModal').modal('show');

  $scope.$applyAsync();
});

编辑 延迟是到下一个 digest-cycle 的时间。

关于javascript - Controller 和 HTML 之间的 AngularJs ng-model 延迟,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53296525/

相关文章:

javascript - html 中的一些 js 更改后,Javascript 中的按钮不起作用

无法存储 Javascript 日期

javascript - ng-repeat 元素删除属性

javascript - 获取另一个站点的本地存储数据

html - 如何按照我希望的方式将这 3 个元素与 Bootstrap 类对齐?

javascript - jquery for bootstrap 模式不起作用

javascript - Google map 信息窗口左箭头、右箭头传递 TypeError : Cannot read property '__e3_' of undefined?

javascript - 从 AngularJS 版本 1.0.8 转换到 1.4.2 时出现问题

javascript - 将 Google Analytics 脚本粘贴到我的网站(head.php、header.php 或 page-header.php)?

javascript - 仅允许数字输入而不通过 addEventListener 返回 false 的函数