BD's
BD's

Reputation: 33

dynamically added elements are not removing from the form in angular JS

I am trying to remove an input element which was added dynamically into a form.

I am using the below code for this.

 var MyEle =  angular.element(document.getElementById('testID'));
  MyEle.remove();

and the input element is added dynamically as below

<ng-form name="TestForm" novalidate">
 <div class="testData">
    <input type="text" name="FirstName1" ng-model="FirstName1" ng-required="true"/>
    <input type="text" id="testID" name="FirstName2" ng-model="FirstName2" ng-required="true"/>
  </div>
</ng-form>                                                                           

The above code is removing the element but still the form is showing invalid even after entering the data into First Input(FirstName1) element.

It seems the removal process is not yet completed. It is not removing from the form. but I am not able to see it on the page.

Upvotes: 1

Views: 290

Answers (3)

Vanojx1
Vanojx1

Reputation: 5574

I can suggest you a more Angular approach to make a dynamic form, check the snippet

// the main (app) module
var myApp = angular.module("myApp", []);

// add a controller
myApp.controller("myCtrl", function($scope) {
  $scope.form = [{
    name: "FirstName1",
    required: true,
    type: "text",
    value: "billy"
  }, {
    name: "FirstName2",
    required: true,
    type: "text",
    value: "bolly"
  }];

  $scope.remove = function() {
    $scope.form.pop();
  };

  $scope.add = function() {
    $scope.form.push({
      name: "new_input_"+$scope.form.length,
      required: true,
      type: "text",
      value: "bolly_"+$scope.form.length
    });
  }
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>

<body ng-app="myApp" ng-controller="myCtrl">
  <input type="{{input.type}}" ng-repeat="input in form" name="{{input.name}}" ng-model="input.value" ng-required="input.required" />
  <button ng-click="add()">add</button>
  <button ng-click="remove()">remove</button>
</body>

Upvotes: 0

ssilas777
ssilas777

Reputation: 9764

In order to remove validation errors you should remove the element and compile again the form, your code should bes some thing like this, you should also inject $compile to your controller

 var MyEle =  angular.element(document.getElementById('testID'));
 MyEle.remove();
 var parentElement = document.getElementsByClassName("testData");
 $compile($(parentElement)($scope);

Upvotes: 0

zamarrowski
zamarrowski

Reputation: 483

Use ng-if, avoid manipulate the DOM in Controller.

Upvotes: 1

Related Questions