1

Working on a simple contact form where I need to show an error message if the $scope is undefined.

The validation part works however I can't remember how to enable the view of the message under ng-show in the html side.

HTML:

<p class="response error" ng-show="error">{{errorMessage}}</p>

JS:

var $emptyContent = 'Please enter your prices.';
app.controller('priceForm', ['$scope', '$http', function($scope, $http){
$scope.formData;
// Process the form data
$scope.submitForm = function () {
  console.log($scope.formData);
  if($scope.formData == null) {
    // Show empty content message

    console.log($emptyContent);
  }

}
}])
Pankaj Parkar
  • 134,766
  • 23
  • 234
  • 299
Warve
  • 481
  • 1
  • 8
  • 22

2 Answers2

1

Just make an error flag to true inside your controller OR you could just have ng-show="errorMessage" as @ryanyuyu suggested in comment.

Code

$scope.submitForm = function () {
  console.log($scope.formData);
  if($scope.formData == null) {
    $scope.error = true; //or //$scope.errorMessage = $emptyContent;
  }
};
Pankaj Parkar
  • 134,766
  • 23
  • 234
  • 299
0

You dont want to create custom error scope you use predefined object to solve this problem

<form name="myForm">
  <label>
    Enter your name:
    <input type="text"
           name="myName"
           ng-model="name"
           ng-minlength="5"
           ng-maxlength="20"
           required />
  </label>
  <pre>myForm.myName.$error = {{ myForm.myName.$error | json }}</pre>

  <div ng-messages="myForm.myName.$error" style="color:maroon" role="alert">
    <div ng-message="required">You did not enter a field</div>
    <div ng-message="minlength">Your field is too short</div>
    <div ng-message="maxlength">Your field is too long</div>
  </div>
</form>

https://docs.angularjs.org/api/ngMessages/directive/ngMessages

Vipin Jain
  • 3,686
  • 16
  • 35