Search code examples
javascriptangularjsng-init

Default value of a variable passed from controller with ng-init in angular text box not showing


I want to display default value of an input text box in edit form using ng-init but I cannot make it no matter what I did.

Here is what I wrote.

In controller:

.controller('ProfileCtrl', function ($scope, $http) {
   $http.get('users.php').then(function (result) {  
   $scope.data = result.data;

   $scope.username = $scope.data.username;
   $scope.email = $scope.data.email;
   $scope.phone = $scope.data.phone;
});

In view:

   <label class="item item-input item-stacked-label">
       <span class="input-label">Username</span>
       <input type="text" ng-model="formData.username" placeholder="Email" ng-init="formData.email={{username}}">
   </label>
   <label class="item item-input item-stacked-label">
          <span class="input-label">Phone</span>
             <input type="text" ng-model="formData.phone" placeholder="0815********" ng-init="formData.phone='{{phone}}'">
    </label>
    <label class="item item-input item-stacked-label">
          <span class="input-label">Email</span>
          <input type="text" ng-model="formData.email" placeholder="" ng-init="formData.email='{{email}}'">
    </label>

I also tried to write ng-init="formData.email={{email}}" and ng-init="formData.email=email" but still not working.


Solution

  • So your main problem is setting that ng-init, first if you want to set it like that you shouldn't use {{ scopevar }} when you are inside of ng-init, but just scopevar.

    But even then, there is no reason to do it like you're trying. Once you set up data model on field, it will update automatically when you get data - angular will do everything for you, just set it up like in example below:

    .controller('ProfileCtrl', function ($scope, $http) {
       $http.get('users.php').then(function (result) {  
       $scope.formData = result.data;
    });
    });
    

    And remove ng-inits from your code.

    <label class="item item-input item-stacked-label">
           <span class="input-label">Username</span>
           <input type="text" ng-model="formData.username" placeholder="Email" >
       </label>
       <label class="item item-input item-stacked-label">
              <span class="input-label">Phone</span>
                 <input type="text" ng-model="formData.phone" placeholder="0815********" >
        </label>
        <label class="item item-input item-stacked-label">
              <span class="input-label">Email</span>
              <input type="text" ng-model="formData.email" placeholder="">
        </label>
    

    Also, I made a fiddle with simplified example. https://jsfiddle.net/pegla/9mqz8drh/1/