Can I re-factor Angular JS validation conditionals to streamline code?

Issue

The below code is one row of my form.

I replicate “AddCarForm.uCarName.$dirty && AddCarForm.uCarName.$invalid” several times throughout the snippet. can i refactor this to a variable, that will be updated with the answer to the conditional as the user’s input changes/ better way of refactoring?

<div class="form-group required " ng-class="{'has-error': AddCarForm.uCarName.$dirty && AddCarForm.uCarName.$invalid}">
  <label class=" control-label col-lg-5 " for="uCarName">Name:</label>
  <div class="col-lg-7 ">
    <input type="text" ng-model="carDetails.carName" name="uCarName" class="form-control" required />
  </div>
  <div class="row">
    <div ng-show="AddCarForm.uCarName.$dirty && AddCarForm.uCarName.$invalid" class="error-msg col-lg-offset-5 col-lg-7">
      <span ng-show="AddCarForm.uCarName.$error.required"> Car Name required </span>	
    </div>
  </div>
</div>

Solution

On your controller, have that expression return from a function, i.e.:

$scope.shouldShow = function() {
      return $scope.AddCarForm.uCarName.$dirty && $scope.AddCarForm.uCarName.$invalid;
}

and then do:

ng-show="shouldShow();"

Just need to make sure the form is actually on the scope.

Answered By – PiniH

Answer Checked By – Dawn Plyler (AngularFixing Volunteer)

Leave a Reply

Your email address will not be published.