Search code examples
javascriptangularjsdynamicform

Angular Dynamic Field in form not showing in view


This is baffling. It is such a simple thing, but I'm not able to get it to work. I am adding an input field to the form on a button click (originally). At this point I'm just trying to see any value in the view (hence the simple p tag)

HTML VIEW

<span>Add secondary field</span>
<md-button class="md-fab md-mini" ng-click="vm.addVals()">
    <i class="material-icons">add</i>
</md-button>

<div ng-if="moreVal">
    <div data-ng-repeat="vl in valHolder.valArr track by $index">
    <p>My Value: {{vl.myVal}}</p>
</div>

Controller

 function EditFormController($scope, $sanitize, ngToast) {
  var vm = this;
  vm.addVals = addVals;
  $scope.valHolder= {valArr: []};
  function addVals(){
   var ln = $scope.valHolder.valArr.length;
   $scope.valHolder.valArr.push({myVal: 'Test'+ln});  
   $scope.moreVal = true;
  }
 }());

I have checked that valArr is being populated with new myVal values on button click. But I cannot see anything in the View. the ng-repeat div is empty. Why is this happening? I have been searching for a solution all day now, but this is so absurd no one seems to have this issue. Don't know what I'm doing wrong. I would really appreciate an answer.


Solution

  • Write below code in your controller:

    var self = this;
    self.valHolder= {valArr: []};
    function addVal(){
      var ln = self.valHolder.valArr.length;
      self.valHolder.valArr.push({myVal: 'Test'+ln});  
      self.moreVal = true;
    }
    

    Write in your HTML like below:

    <div ng-if="moreVal">
        <div data-ng-repeat="vl in vm.valHolder.valArr track by $index">
        <p>My Value: {{vl.myVal}}</p>
    </div>