如何在格式

时间:2016-05-20 12:40:45

标签: javascript angularjs

我有要求,所有错误消息都必须显示在应用程序的标题中。我怎么能用角度呢?

如果我有这个申请(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>

我需要的是在header div中收到错误消息。我怎么能这样做?

2 个答案:

答案 0 :(得分:1)

此处已修复 demo

只需像一样形式访问错误,就像设置<form name="myForm" >一样,然后你会获得$ scope.myForm = [yourFormObject],然后在任何地方免费访问控制器。

Angular Form Document

  

标题为绑定到表单和控件状态

     

表单是FormController的一个实例。可以选择使用name属性将表单实例发布到作用域中。

并且甚至可以通过 $error访问控制器中的$scope.$watch('formName.fieldName.$error',function(nv,ov){});

&#13;
&#13;
// 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);
});
&#13;
/* Styles go here */

hr {
  margin: 20px 0;
}
&#13;
<!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>
&#13;
&#13;
&#13;

答案 1 :(得分:0)

您将拥有两个不同的控制器。在标头控制器中,您将显示错误消息。

然后您的控制器将通过$rootScope or service

进行通信