javascript – Retrieve Error messages via json in Angular

Question:

I'm trying to register using Angularjs, but I want to get the validations that are in my model in rails. But I'm having trouble:

Covenat(model) Rails

validates :name, presence: true 

controller Covenat Action Create

def create
  @covenat = Covenat.new(covenat_params)
  if @covenat.save
    render json: @covenat, status: 200
  else
    render json: { errors: @covenat.errors }, status: 422
  end
end

view /assets/templates/covenats/new.html

<form name="form" ng-submit="submit()" novalidate>
   <div class="form-group" ng-class="errorClass('name')">
     <label class="control-label" for="covenat_name">Nome</label>
     <input class='form-control' type='text' ng-model='covenat.name'     name='covenat_name' id="covenat_name" required/>
     <p class="help-block" ng-show="form.name.$invalid && form.name.$dirty">
        {{ errorMessage('name')}}
     </p>
   </div>          
</form>

covenats_new_controller.js

angular.module('clinica')
  .controller('CovenatsNewCtrl', ['$scope', 'Covenat', '$location', 
function($scope, Covenat, $location){

$scope.submit = function() {
  console.log("submit")

  function success(response) {
    console.log("success", response)
    $location.path("/covenats");
  }

  function failure(response) {
    console.log("failure", response)

    _.each(response.data, function(errors, key) {
    _.each(errors, function(e) {
      $scope.form[key].$dirty = true;
      $scope.form[key].$setValidity(e, false);
    });
   });
 }

  Covenat.save($scope.covenat, success, failure);

};

$scope.errorClass = function(name) {
 var s = $scope.form[name];
 return s.$invalid && s.$dirty ? "error" : "";
};

$scope.errorMessage = function(name) {
 var s = $scope.form[name].$error;
 result = [];
 _.each(s, function(key, value) {
   result.push(value);
 });
 return result.join(", ");
};

}]);

I have the following error in the failure function:

TypeError: Cannot read property '$invalid' of undefined

on the line return s.$invalid && s.$dirty ? "error" : "";

Answer:

When you call functions

errorClass('name') , errorMessage('name')

you are passing the string "name" as a parameter, that is, when it arrives in the function.

var s = $scope.form[name]; this is actually becoming $scope.form.name and the name property doesn't exist inside your form, so the variable s is undefined, when you try to access the variable $invalid it shows the error.

Scroll to Top