Using AngularJS to validate the "input" element created dynamically

advertisements

I have a table that displays several entries, each has an <input>. The user can dynamically add additional inputs by clicking an "add entry" button. I need to iterate over them before saving and validate each one. I simplified my example to check that the value of each input is greater than 100 (ultimately I will use a pattern-match to validate MAC and IP addresses).

I can probably handle it if I could select all <input>s, but I would really like to select a specific <input> using an index I already have in my scope. I read that angular.element is a way, but I need to select something that was dynamically created, and thus not named something easy like id="myInput". Unless I use an id of "input" and append a unique number with Angular's $index in the id attribute?

Here is my Fiddle that shows what I'm doing. Line 44 is an if() that should check if any <input> is greater than 100. The "Save Row" button validates that the input is greater than 100, but if you edit a line, I need the "Save" button to validate any that the user has edited (by clicking Edit next to it).

tl;dr: How can I use Angular to select an <input> that has been created dynamically?


I have updated your fiddle in a clean way so that you can maintain the validation in a generic method for both add & edit.

function validateBinding(binding) {
     // Have your pattern-match validation here to validate MAC and IP addresses
     return binding.ip > 100;
}

Updated fiddle:

https://jsfiddle.net/balasuar/by0tg92m/27/

Also, I have fixed the current issue with editing you have to allow multiple editing without save the first row when clicking the next edit on next row.

The validation of 'save everything' is now cleaner in angular way as below.

$scope.changeEdit = function(binding) {
    binding.onEdit = true;
    //$scope.editNum = newNum;
    $scope.showSave = true;
  };

$scope.saveEverything = function() {
    var error = false;
    angular.forEach($scope.macbindings, function(binding) {
       if(binding.onEdit) {
          if (validateBinding(binding)) {
             binding.onEdit = false;
          } else {
             error = true;
          }
       }
    });

    if (error) {
      alert("One/some of the value you are editing need to be greater than 100");
    } else {
      $scope.showSave = false;
    }
  }

You can check the updated fiddle for the same,

https://jsfiddle.net/balasuar/by0tg92m/27/

Note: As you are using angular, you can validate the model as above and no need to retrieve and loop the input elements for the validation. Also for your case, validating the model is sufficient.

If you need some advanced validation, you should create a custom directive. Since, playing around with the elements inside the controller is not recommended in AngularJS.