【问题标题】:How to fill an AngularJS form loading data via XMLHttpRequest [duplicate]如何通过 XMLHttpRequest 填充加载数据的 AngularJS 表单 [重复]
【发布时间】:2019-01-16 15:26:23
【问题描述】:

我在 AngularJS 控制器中有一个表单,我想用 XHTMLRequest 收集的数据自动填充表单。

Form 只需使用 data-ng-model 进行输入

page.html

<div id="PersonalAppID" data-ng-controller="PersonalAppCtrl as ctrl">
<form action="/" method="post" novalidate> 
<div class="input-group">
<div class="form-group col-md-5">
<label>First name: </label>
<input name="fname" type="text" data-ng-model="ctrl.fname" placeholder="first name">
</div>
</div>

控制器初始化时,它会创建一个请求,下载数据并将其放入变量ctrl.variable

page.js

 angular.controller('PersonalAppCtrl',function() { var ctrl = this;

        ctrl.$onInit= function(){
            var req=XMLHttpRequest();

            req.onreadystatechange = function(){
                if (req.status == 200&req.readyState==4){
                    var ret = convertJSON(req.responseText);
                    ctrl.fname = ret.FirstName;
                    return (true);
                }
           }
           req.open();
           req.send();
        }

我的问题是只有当用户触摸输入然后触摸它外部时才会填充输入。 我希望在页面加载后立即填写表格

我也尝试过使用 ng-loadng-init 但在这种情况下行为几乎相同。

有什么想法吗?

【问题讨论】:

    标签: javascript html angularjs input xmlhttprequest


    【解决方案1】:

    如下更新您的代码:

    angular.controller('PersonalAppCtrl',function() { var ctrl = this;
    
            ctrl.$onInit= function(){
                var req=XMLHttpRequest();
    
                req.onreadystatechange = function(){
                    if (req.status == 200&req.readyState==4){
                        var ret = convertJSON(req.responseText);
                        $scope.$apply(function () {
                           ctrl.fname = ret.FirstName;
                        });
                        return (true);
                    }
               }
               req.open();
               req.send();
            }
    

    您正在制作一个非角度代码的 XMLHTTPRequest。 Angular 不知道何时收到响应,因此您需要通过调用 $scope.$apply()

    例子:

    function Ctrl($scope) {
      $scope.message = "Waiting 2000ms for update";
    
        setTimeout(function () {
            $scope.message = "Timeout called!";
            // AngularJS unaware of update to $scope
        }, 2000);
    }
    

    但是,如果我们将该回合的代码封装在 $scope.$apply() 中,则会注意到更改,并更新页面。

    function Ctrl($scope) {
      $scope.message = "Waiting 2000ms for update";
    
        setTimeout(function () {
            $scope.$apply(function () {
                $scope.message = "Timeout called!";
            });
        }, 2000);
    }
    

    这里给出了非常详细的解释 - http://jimhoskins.com/2012/12/17/angularjs-and-apply.html

    最好对所有 HTTP 请求使用 Angular $http。所以你不必费心使用$scope.$apply()

    【讨论】:

    • $scope.$apply 在我的情况下工作得很好,谢谢。
    • 太棒了!不客气!
    猜你喜欢
    • 2019-01-16
    • 1970-01-01
    • 2016-01-21
    • 2011-09-09
    • 1970-01-01
    • 1970-01-01
    • 2015-10-11
    • 1970-01-01
    • 2013-10-05
    相关资源
    最近更新 更多