Angular ng-显示如何使可见

Angular ng-show how to make visible

正在处理一个简单的联系表单,如果 $scope 未定义,我需要在其中显示一条错误消息。

验证部分有效,但我不记得如何在 html 端的 ng-show 下启用消息视图。

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);
  }

}
}])

只需在您的控制器内为 true 创建一个 error 标志 或者 您可以像 @ryanyuyu 在评论中建议的那样拥有 ng-show="errorMessage"

代码

$scope.submitForm = function () {
  console.log($scope.formData);
  if($scope.formData == null) {
    $scope.error = true; //or //$scope.errorMessage = $emptyContent;
  }
};

您不想创建自定义错误范围您使用预定义的对象来解决这个问题

<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