将服务器端错误推送到Angular

时间:2015-05-06 20:18:46

标签: angularjs

我有以下Angular / HTML代码:

function SignUpController($scope, UserService) {    
  $scope.model = {
    user: {  
      password: '',     
      email: ''
    },
  }
}

$scope.send = function (user) {
  UserService.SignUp(user)
    .success(function (data, status, headers, config) { })
    .error(function (data, status, headers, config) {
      $scope.errors = data.errors;
    });
};

<form name="form" class="form" data-ng-controller="SignUpController">
  <input id="email" data-ng-model="model.user.email" type="text" />
  <input id="password" data-ng-model="model.user.password" type="password" />
  <button class="button" data-ng-click="send(model.user)">
</form>

当我注册用户时,api会返回以下对象:

"errors": {
  "user.Email": [
      "The email is taken"
  ],
  "user.Password": [
      "The password is not secure"
  ]
}

如何将这些错误推送到角度以在表单上显示?

1 个答案:

答案 0 :(得分:3)

取决于您希望如何显示它们,但这可行:

<form name="form" class="form" data-ng-controller="SignUpController">
  <input id="email" data-ng-model="model.user.email" type="text" />
  <span ng-if="errors">{{errors["user.Email"][0]}}</span>

  <input id="password" data-ng-model="model.user.password" type="password" />
  <span ng-if="errors">{{errors["user.Password"][0]}}</span>

  <button class="button" data-ng-click="send(model.user)">
</form>