0

I have the requirement, that all error messages have to be shown in the header of the application. How can I do that with angular?

If I have this application (see on plunker):

 <body>
    <div id="header">
      <!-- I want error messages to show up here -->
    </div>
    <form name="myForm">
      <label>Email</label>
      <input name="myEmail" type="email" ng-model="user.email" required="" />
      <div ng-messages="myForm.myEmail.$error">
        <div ng-message="required">required</div>
        <div ng-message="email">invalid email</div>
      </div>
    </form>
    <p>Your email address is: {{user.email}}</p>
  </body>

What I need is to have the error messages in the header div. How can I do that?

BetaRide
  • 16,207
  • 29
  • 99
  • 177

2 Answers2

1

Fixed demo here.

Just access the error the way same as in form, as when you set <form name="myForm" >, then you will get $scope.myForm = [yourFormObject], then access free anywhere in same controller.

Angular Form Document

Under the title Binding to form and control state

A form is an instance of FormController. The form instance can optionally be published into the scope using the name attribute.

And, even access the $error in controller by $scope.$watch('formName.fieldName.$error',function(nv,ov){});

// Code goes here

var app = angular.module('plunker', ['ngMessages']);
app.controller('appCtrl', function($scope) {
  $scope.$watch('myForm.myEmail.$error', function(nv, ov) {
    console.info(nv);
  }, true);
});
/* Styles go here */

hr {
  margin: 20px 0;
}
<!DOCTYPE html>
<html ng-app="plunker">

<head>
  <meta charset="utf-8" />
  <title>AngularJS Plunker</title>
  <script>
  </script>
  <link rel="stylesheet" href="style.css" />
  <script src="https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.5.5/angular.js"></script>
  <script src="https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.5.5/angular-messages.js"></script>
  <script src="script.js"></script>
</head>

<body ng-controller="appCtrl">
  <div id="header">
    <div ng-show="myForm.myEmail.$error.required">required</div>
    <div ng-show="myForm.myEmail.$error.email">invalid email</div>
  </div>
  <hr />
  <form name="myForm">
    <label>Email</label>
    <input name="myEmail" type="email" ng-model="user.email" required="" />
    <div ng-messages="myForm.myEmail.$error">
      <div ng-message="required">required</div>
      <div ng-message="email">invalid email</div>
    </div>
  </form>
  <p>Your email address is: {{user.email}}</p>
</body>

</html>
Yin Gang
  • 1,443
  • 1
  • 10
  • 15
0

You'll have two distinct controller.In header controller, you'll be displaying your error messages.

Then your controller will be communicating over either $rootScope or service

Community
  • 1
  • 1
asdf_enel_hak
  • 7,474
  • 5
  • 42
  • 84