目录搜索
AngularJS API Referenceautoauto/serviceauto/service/$injectorauto/service/$providengng/directiveng/directive/ang/directive/formng/directive/inputng/directive/input[checkbox]ng/directive/input[date]ng/directive/input[dateTimeLocal]ng/directive/input[email]ng/directive/input[month]ng/directive/input[number]ng/directive/input[radio]ng/directive/input[text]ng/directive/input[time]ng/directive/input[url]ng/directive/input[week]ng/directive/ngAppng/directive/ngBindng/directive/ngBindHtmlng/directive/ngBindTemplateng/directive/ngBlurng/directive/ngChangeng/directive/ngCheckedng/directive/ngClassng/directive/ngClassEvenng/directive/ngClassOddng/directive/ngClickng/directive/ngCloakng/directive/ngControllerng/directive/ngCopyng/directive/ngCspng/directive/ngCutng/directive/ngDblclickng/directive/ngDisabledng/directive/ngFocusng/directive/ngFormng/directive/ngHideng/directive/ngHrefng/directive/ngIfng/directive/ngIncludeng/directive/ngInitng/directive/ngKeydownng/directive/ngKeypressng/directive/ngKeyupng/directive/ngListng/directive/ngModelng/directive/ngModelOptionsng/directive/ngMousedownng/directive/ngMouseenterng/directive/ngMouseleaveng/directive/ngMousemoveng/directive/ngMouseoverng/directive/ngMouseupng/directive/ngNonBindableng/directive/ngOpenng/directive/ngPasteng/directive/ngPluralizeng/directive/ngReadonlyng/directive/ngRepeatng/directive/ngSelectedng/directive/ngShowng/directive/ngSrcng/directive/ngSrcsetng/directive/ngStyleng/directive/ngSubmitng/directive/ngSwitchng/directive/ngTranscludeng/directive/ngValueng/directive/scriptng/directive/selectng/directive/textareang/filterng/filter/currencyng/filter/dateng/filter/filterng/filter/jsonng/filter/limitTong/filter/lowercaseng/filter/numberng/filter/orderByng/filter/uppercaseng/functionng/function/angular.bindng/function/angular.bootstrapng/function/angular.copyng/function/angular.elementng/function/angular.equalsng/function/angular.extendng/function/angular.forEachng/function/angular.fromJsonng/function/angular.identityng/function/angular.injectorng/function/angular.isArrayng/function/angular.isDateng/function/angular.isDefinedng/function/angular.isElementng/function/angular.isFunctionng/function/angular.isNumberng/function/angular.isObjectng/function/angular.isStringng/function/angular.isUndefinedng/function/angular.lowercaseng/function/angular.moduleng/function/angular.noopng/function/angular.toJsonng/function/angular.uppercaseng/objectng/object/angular.versionng/providerng/provider/$animateProviderng/provider/$compileProviderng/provider/$controllerProviderng/provider/$filterProviderng/provider/$httpProviderng/provider/$interpolateProviderng/provider/$locationProviderng/provider/$logProviderng/provider/$parseProviderng/provider/$rootScopeProviderng/provider/$sceDelegateProviderng/provider/$sceProviderng/serviceng/service/$anchorScrollng/service/$animateng/service/$cacheFactoryng/service/$compileng/service/$controllerng/service/$documentng/service/$exceptionHandlerng/service/$filterng/service/$httpng/service/$httpBackendng/service/$interpolateng/service/$intervalng/service/$localeng/service/$locationng/service/$logng/service/$parseng/service/$qng/service/$rootElementng/service/$rootScopeng/service/$sceng/service/$sceDelegateng/service/$templateCacheng/service/$timeoutng/service/$windowng/typeng/type/$cacheFactory.Cacheng/type/$compile.directive.Attributesng/type/$rootScope.Scopeng/type/angular.Moduleng/type/form.FormControllerng/type/ngModel.NgModelControllerngAnimatengAnimate/providerngAnimate/provider/$animateProviderngAnimate/servicengAnimate/service/$animatengCookiesngCookies/servicengCookies/service/$cookiesngCookies/service/$cookieStorengMessagesngMessages/directivengMessages/directive/ngMessagengMessages/directive/ngMessagesngMockngMock/functionngMock/function/angular.mock.dumpngMock/function/angular.mock.injectngMock/function/angular.mock.modulengMock/objectngMock/object/angular.mockngMock/providerngMock/provider/$exceptionHandlerProviderngMock/servicengMock/service/$exceptionHandlerngMock/service/$httpBackendngMock/service/$intervalngMock/service/$logngMock/service/$timeoutngMock/typengMock/type/angular.mock.TzDatengMockE2EngMockE2E/servicengMockE2E/service/$httpBackendngResourcengResource/servicengResource/service/$resourcengRoutengRoute/directivengRoute/directive/ngViewngRoute/providerngRoute/provider/$routeProviderngRoute/servicengRoute/service/$routengRoute/service/$routeParamsngSanitizengSanitize/filterngSanitize/filter/linkyngSanitize/servicengSanitize/service/$sanitizengTouchngTouch/directivengTouch/directive/ngClickngTouch/directive/ngSwipeLeftngTouch/directive/ngSwipeRightngTouch/servicengTouch/service/$swipe
文字

AngularJS: API: ngMessages


ngMessages

The ngMessages module provides enhanced support for displaying messages within templates (typically within forms or when rendering message objects that return key/value data). Instead of relying on JavaScript code and/or complex ng-if statements within your form template to show and hide error messages specific to the state of an input field, the ngMessages and ngMessage directives are designed to handle the complexity, inheritance and priority sequencing based on the order of how the messages are defined in the template.

Currently, the ngMessages module only contains the code for the ngMessages and ngMessage directives.

用法

The ngMessages directive listens on a key/value collection which is set on the ngMessages attribute. Since the ngModel directive exposes an $error object, this error object can be used with ngMessages to display control error messages in an easier way than with just regular angular template directives.

<form name="myForm">
  <input Type="text" ng-model="field" name="myField" required minlength="5" />
  <div ng-messages="myForm.myField.$error">
    <div ng-message="required">You did not enter a field</div>
    <div ng-message="minlength">The value entered is too short</div>
  </div>
</form>

Now whatever key/value entries are present within the provided object (in this case $error) then the ngMessages directive will render the inner first ngMessage directive (depending if the key values match the attribute value present on each ngMessage directive). In other words, if your errors object contains the following data:

<!-- 记住, that ngModel automatically sets these error flags -->
myField.$error = { minlength : true, required : false };

Then the required message will be displayed first. When required is false then the minlength message will be displayed right after (since these messages are ordered this way in the template HTML code). The prioritization of each message is determined by what order they're present in the DOM. Therefore, instead of having custom JavaScript code determine the priority of what errors are present before others, the presentation of the errors are handled within the template.

默认情况下, ngMessages will only display one error at a time. However, if you wish to display all messages then the ng-messages-multiple attribute flag can be used on the element containing the ngMessages directive to make this happen.

<div ng-messages="myForm.myField.$error" ng-messages-multiple>...</div>

Reusing and Overriding Messages

In addition to prioritization, ngMessages also allows for including messages from a remote or an inline template. This allows for generic collection of messages to be reused across multiple parts of an application.

<script Type="text/ng-template" id="error-messages">
  <div ng-message="required">This field is required</div>
  <div ng-message="minlength">This field is too short</div>
</script>
<div ng-messages="myForm.myField.$error" ng-messages-include="error-messages"></div>

However, including generic messages may not be useful enough to match all input fields, therefore, ngMessages provides the ability to override messages defined in the remote template by redefining then within the directive container.

<!-- a generic template of error messages known as "my-custom-messages" -->
<script Type="text/ng-template" id="my-custom-messages">
  <div ng-message="required">This field is required</div>
  <div ng-message="minlength">This field is too short</div>
</script>

<form name="myForm">
  <input Type="email"
         id="email"
         name="myEmail"
         ng-model="email"
         minlength="5"
         required />

  <div ng-messages="myForm.myEmail.$error" ng-messages-include="my-custom-messages">
    <!-- this required message has overridden the template message -->
    <div ng-message="required">You did not enter your email address</div>

    <!-- this is a brand new message and will appear last in the prioritization -->
    <div ng-message="email">Your email address is invalid</div>
  </div>
</form>

In the example HTML code above the message that is set on required will override the corresponding required message defined within the remote template. Therefore, with particular input fields (such email addresses, date fields, autocomplete inputs, etc...), specialized error messages can be applied while more generic messages can be used to handle other, more general input errors.

动画

If the ngAnimate module is active within the application then both the ngMessages and ngMessage directives will trigger animations whenever any messages are added and removed from the DOM by the ngMessages directive.

Whenever the ngMessages directive contains one or more visible messages then the .ng-active CSS class will be added to the element. The .ng-inactive CSS class will be applied when there are no animations present. Therefore, CSS transitions and keyframes as well as JavaScript animations can hook into the animations whenever these classes are added/removed.

Let's say that our HTML code for our messages container looks like so:

<div ng-messages="myMessages" class="my-messages">
  <div ng-message="alert" class="some-message">...</div>
  <div ng-message="fail" class="some-message">...</div>
</div>

Then the CSS animation code for the message container looks like so:

.my-messages {
  transition:1s linear all;
}
.my-messages.ng-active {
  // messages are visible
}
.my-messages.ng-inactive {
  // messages are hidden
}

Whenever an inner message is attached (becomes visible) or removed (becomes hidden) then the enter and leave animation is triggered for each particular element bound to the ngMessage directive.

Therefore, the CSS code for the inner messages looks like so:

.some-message {
  transition:1s linear all;
}

.some-message.ng-enter {}
.some-message.ng-enter.ng-enter-active {}

.some-message.ng-leave {}
.some-message.ng-leave.ng-leave-active {}

点击这里 to learn how to use JavaScript animations or to learn more about ngAnimate.

Installation

First include angular-messages.js in your HTML:

    <script src="angular.js">
    <script src="angular-messages.js">

You can download this file from the following places:

  • Google CDN
    例如 //ajax.googleapis.com/ajax/libs/angularjs/X.Y.Z/angular-messages.js
  • Bower
    例如
    bower install angular-messages@X.Y.Z
  • code.angularjs.org
    例如
    "//code.angularjs.org/X.Y.Z/angular-messages.js"

where X.Y.Z is the AngularJS version you are running.

Then load the module in your application by adding it as a dependent module:

  angular.module('app', ['ngMessages']);

With that you're ready to get started!

模块组件

Directive

名称 描述
ngMessages

ngMessages is a directive that is designed to show and hide messages based on the state of a key/value object that it listens on. The directive itself compliments error message reporting with the ngModel $error object (which stores a key/value state of validation errors).

ngMessage

ngMessage is a directive with the purpose to show and hide a particular message. For ngMessage to operate, a parent ngMessages directive on a parent DOM element must be situated since it determines which messages are visible based on the state of the provided key/value map that ngMessages listens on.


上一篇:下一篇: