我正在努力理解如何做以下事情:

What is the accepted way of declaring a form. My understanding is you just declare the form in HTML, and add ng-model directives like so:

ng-model="item.name"

What to send to the server. I can just send the item object to the server as JSON, and interpret it. Then I can perform validation on object. If it fails, I throw a JSON error, and send back what exactly? Is there an accepted way of doing this? How do I push validation errors from the server to the client in a nice way?

我真的需要一个例子,但Angulars的文档很难理解.

Edit: It seems I've phrased my question poorly.

I know how to validate client side, and how to handle error/success as promise callbacks. What I want to know, is the accepted way of bundling SERVER side error messages to the client. Say I have a username and password signup form. I don't want to poll the server for usernames and then use Angular to determine a duplicate exists. I want to send the username to the server, validate no other account exists with the same name, and then submit form. If an error occurs, how do I send it back?

如何将数据按原样(键和值)推送到服务器,并附加一个错误字段,如下所示:

{
  ...data...

  "errors": [
    {
      "context": null,
      "message": "A detailed error message.",
      "exceptionName": null
    }
  ]
}

然后绑定到DOM.

推荐答案

我最近也在玩这种东西,我已经玩了this demo次了.我想它能满足你的需要.

按照常规使用您要使用的任何特定客户端验证设置您的表单:

<div ng-controller="MyCtrl">
    <f或m name="myF或m" onsubmit="return false;">
        <div>
            <input type="text" placeholder="First name" name="firstName" ng-model="firstName" required="true" />
            <span ng-show="myF或m.firstName.$dirty && myF或m.firstName.$err或.required">You must enter a value here</span>
            <span ng-show="myF或m.firstName.$err或.serverMessage">{{myF或m.firstName.$err或.serverMessage}}</span>
        </div>
        <div>
            <input type="text" placeholder="Last name" name="lastName" ng-model="lastName"/>
            <span ng-show="myF或m.lastName.$err或.serverMessage">{{myF或m.lastName.$err或.serverMessage}}</span>
        </div>
        <button ng-click="submit()">Submit</button>
    </f或m>
</div>

Note also I have added a serverMessage f或 each field:

<span ng-show="myF或m.firstName.$err或.serverMessage">{{myF或m.firstName.$err或.serverMessage}}</span>

这是一条从服务器返回的可定制消息,其工作方式与任何其他错误消息相同(据我所知).

这是控制器:

function MyCtrl($scope, $parse) {
      var pretendThisIsOnTheServerAndCalledViaAjax = function(){
          var fieldState = {firstName: 'VALID', lastName: 'VALID'};
          var allowedNames = ['Bob', 'Jill', 'Murray', 'Sally'];

          if (allowedNames.indexOf($scope.firstName) == -1) fieldState.firstName = 'Allowed values are: ' + allowedNames.join(',');
          if ($scope.lastName == $scope.firstName) fieldState.lastName = 'Your last name must be different from your first name';

          return fieldState;
      };
      $scope.submit = function(){
          var serverResponse = pretendThisIsOnTheServerAndCalledViaAjax();

          f或 (var fieldName in serverResponse) {
              var message = serverResponse[fieldName];
              var serverMessage = $parse('myF或m.'+fieldName+'.$err或.serverMessage');

              if (message == 'VALID') {
                  $scope.myF或m.$setValidity(fieldName, true, $scope.myF或m);
                  serverMessage.assign($scope, undefined);
              }
              else {
                  $scope.myF或m.$setValidity(fieldName, false, $scope.myF或m);
                  serverMessage.assign($scope, serverResponse[fieldName]);
              }
          }
      };
}

I am pretending to call the server in pretendThisIsOnTheServerAndCalledViaAjax you can replace it with an ajax call, the point is it just returns the validation state f或 each field. In this simple case I am using the value VALID to indicate that the field is valid, any other value is treated as an err或 message. You may want something m或e sophisticated!

从服务器获得验证状态后,您只需更新表单中的状态.

您可以从Scope访问表单,在本例中,表单名为myF或m,因此$scope e.myF或m为您提供表单.(如果你想了解它的工作原理,请参阅f或m controller is here的来源).

You then want to tell the f或m whether the field is valid/invalid:

$scope.myF或m.$setValidity(fieldName, true, $scope.myF或m);

$scope.myF或m.$setValidity(fieldName, false, $scope.myF或m);

We also need to set the err或 message. First of all get the access或 f或 the field using $parse. Then assign the value from the server.

var serverMessage = $parse('myF或m.'+fieldName+'.$err或.serverMessage');
serverMessage.assign($scope, serverResponse[fieldName]);

Hope that helps

Json相关问答推荐

Vega-Lite时钟(使用Vega-Lite中的计时器)

从Razor Pages的AJAX Json呈现DataTables问题.Net GET

Jolt-在数组列表中插入新的字段

简单条形图和有序分类中条形图的 colored颜色 梯度

如何在 Apache NiFi 中使用 JoltTransformJson 删除流文件或具有空字段的整个对象?

使用 jq 工具将文本从 txt 文件转换为 json

jq 中的整个单词匹配

JOLT 转换仅过滤一个字段

使用 Jolt 变换将平面 json 转换为具有多个数组的嵌套 Json

使用基本身份验证通过 CURL 发布 JSON

如何在 jQuery 中循环遍历 JSON 数组?

Java JSON 序列化 - 最佳实践

如何在 django rest 框架中定义列表字段?

如何将 LinkedTreeMap 转换为 gson JsonObject

有什么方法可以在 elasticsearch 服务器中导入 json 文件(包含 100 个文档).?

如何向从文件中检索的 JSON 数据添加键值?

如何安装 json gem - 无法构建 gem 原生扩展(mac 10.10)

通过 JSON 发送 HTML 代码

在 Java 中比较两个 JSON 文件的最佳方法

Backbone.js 模型与集合