首页 > 解决方案 > How to fill an AngularJS form loading data via XMLHttpRequest

问题描述

I have a form in an AngularJS controller, I would like to automatically fill the form with data collected with a XHTMLRequest.

Form has simply inputs with 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>

When controller init itself, it creates a request, downloads the data and put it into variables 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();
        }

My problem is that input are filled only if user touch an input and then touch outside it. I'd like to have form filled as soon as the page is loaded.

I also tried to use ng-load and ng-init but the behaviour is pretty the same in this case.

Any ideas?

标签: javascripthtmlangularjsinputxmlhttprequest

解决方案


更新您的代码,如下所示:

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

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


推荐阅读