angular js: 无法验证文本区域

angular js: Unable to validate a textarea

伙计们!

我正在尝试通过单击 link 来验证文本区域。问题是,它没有进入表格。当用户单击 link 时,在文本区域中输入的内容应该被 posted(保存到数据库)。

我为此写了一个验证。不幸的是,它不起作用,我可以制作空白 posts。我试图防止空白 post posting。我在 fiddle 中重新创建了表单和控制器。 Link 我会提供下来。但在此之前,请看一下我的 html 和 js 代码。

HTML

<div ng-app="myApp" ng-controller="myMap">
  <div class="post-textarea" ng-class="{ 'has-error': vm.currentPost.content.$dirty && vm.currentPost.content.$error.required }">
    <textarea class="form-control" rows="3" ng-model="vm.currentPost.content" required></textarea>
    <a ng-click="vm.addPost(vm.currentPost.content,vm.currentPost.$valid)">Clik to Post and validate</a>
  </div>
</div>

JavaScript

angular.module('myApp', [])
  .factory('myService', function($http) {
    var baseUrl = 'api/';
    return {
      postCurrentPost: function(newPost) {
        var dataPost = {
          newPost: newPost
        };
        return $http({
          method: 'post',
          url: baseUrl + 'postCurrentPost',
          data: dataPost,
          headers: {
            'Content-Type': 'application/x-www-form-urlencoded'
          }
        });
      }
    };

  })
  .controller('myMap', function(myService, $http, $scope) {

    var vm = this;
    var userObject;

    // Add a post
    vm.addPost = function(newPost, isValid) {
      if (isValid) {
        var currentPost = vm.currentPost;
        currentPost.content = ""; //clear post textarea
        myService.postCurrentPost(newPost).success(function(data) {
          vm.posts = data;
        });
      } else {
        alert('Validation not working');
      }
    };
    //Check validation
    $scope.getError = function(error, name) {
      if (angular.isDefined(error)) {
        if (error.required && name == 'vm.currentPost.content') {
          return "This field is required";
        }
      }
    }
  });

这里是 FIDDLE

应使用表单输入元素的名称而不是模型值。

https://docs.angularjs.org/api/ng/directive/form

<div ng-app="myApp" ng-controller="myMap">
    <form name="formContent">
      <div class="post-textarea" ng-class="{ 'has-error': formContent.content.$dirty && formContent.content.$error.required }">
      <textarea name='content' class="form-control" rows="3" ng-model="vm.currentPost.content" required></textarea>
      <a ng-click="vm.addPost(vm.currentPost.content,vm.currentPost.$valid)">Clik to Post and validate</a>
      </div>
    </form>
    Content is dirty: {{formContent.content.$dirty}}
    <br>
    Content has required: {{formContent.content.$error.required}}
</div>