Miguel Moura
Miguel Moura

Reputation: 39364

Push server side errors into Angular

I have the following Angular / HTML code:

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>

When I sign up the user the api returns the following object:

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

How can I push these errors into angular to display them on the form?

Upvotes: 1

Views: 128

Answers (1)

azium
azium

Reputation: 20614

Depends on how you want to display them, but this would work:

<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>

Upvotes: 3

Related Questions