0

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?

Phil
  • 115
  • 1
  • 11

1 Answers1

1

Update your code like below:

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();
        }

You are making an XMLHTTPRequest which is a non angular code. Angular is not aware when the response is received so you need to make that angular aware by calling $scope.$apply()

Example:

function Ctrl($scope) {
  $scope.message = "Waiting 2000ms for update";

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

But, if we wrap the code for that turn in $scope.$apply(), the change will be noticed, and the page is updated.

function Ctrl($scope) {
  $scope.message = "Waiting 2000ms for update";

    setTimeout(function () {
        $scope.$apply(function () {
            $scope.message = "Timeout called!";
        });
    }, 2000);
}

A very detailed explaination on this is given here - http://jimhoskins.com/2012/12/17/angularjs-and-apply.html

Its better to use Angular $http for all HTTP requests. So you dont have to bother about using $scope.$apply()

Kishan
  • 231
  • 1
  • 11