控制器和HTML之间的AngularJs ng-model延迟

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了控制器和HTML之间的AngularJs ng-model延迟相关的知识,希望对你有一定的参考价值。

我对AngularJs和ng-model有一个问题,从控制器到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(我使用角度路由来制作单页应用程序):

<!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的时间。

以上是关于控制器和HTML之间的AngularJs ng-model延迟的主要内容,如果未能解决你的问题,请参考以下文章

angularjs控制器之间通信,事件通知服务

AngularJS下拉需要验证

在 AngularJS 控制器之间共享数据

[angularjs] angularjs系列笔记控制器

angularJS

angularjs1.3验证