AngularJS API Reference

AngularJS API 参考

AngularJS API 文档

欢迎访问AngularJS API文档页面. 这些页面是对1.3.0-beta.15 unbelievable-advancement版本的AngularJS参考资料。

文档按多个模块的形式进行组织，每个模块包含AngularJS应用程序所需的包含各种组件，这些组件有 directives、services、filters、providers、templates、global APIs, 和 testing mocks。

Angular 命名空间 $ and $$ 为防止和你的代码的名称产生冲突，Angular公共对象的前缀名使用$ ，私有对象名使用$$。请不要在你的代码中使用 $或$$ 前缀。

Angular 命名空间

ng (核心模块)

这个模块是默认提供的，它包含了AngularJS的核心组件。

Directives | 这些核心指令集可用于你的AngularJS应用的模板代码中。 例如：ngClick, ngInclude, ngRepeat…
Services / Factories | 这些核心服务集可通过依赖注入(DI)来供你的应用使用。 例如：$compile, $http, $location…
Filters | 这些ng模块中的核心过滤器用于在指令和表达式被渲染前转换模板数据。 例如：filter, date, currency, lowercase, uppercase...
Global APIs | 附加在angular对象上的核心公共API函数。这些核心函数对于你应用中的低级JavaScript操作很有用。 例如：angular.copy(), angular.equals(), angular.element()...

ngRoute

使用ngRoute让你的应用具有URL路由功能。ngRoute模块支持hashbang和HTML5 pushState方式的URL管理。

你的应用要使用此功能，需导入angular-route.js文件，并且将ngRoute 设为依赖。
Services / Factories 下面这些服务用于路由管理：
  • $routeParams 用于访问在URL中querystring中的值。
  • $route 用于当前被访问的路由的细节。
  • $routeProvider用于为应用注册路由。
Directives ngView用于在页面中根据当前路由显示模板。

ngAnimate

Use ngAnimate to enable animation features into your application. Various core ng directives will provide animation hooks into your application when ngAnimate is included. Animations are defined by using CSS transitions/animations or JavaScript callbacks.

你的应用要使用此功能，需导入 angular-animate.js文件，并且将ngAnimate设为依赖。
Services / Factories | Use $animate to trigger animation operations within your directive code.
CSS-based animations | Follow ngAnimate’s CSS naming structure to reference CSS transitions / keyframe animations in AngularJS. Once defined the animation can be triggered by referencing the CSS class within the HTML template code.
JS-based animations | Use module.animation() to register a JavaScript animation. Once registered the animation can be triggered by referencing the CSS class within the HTML template code.

ngResource

Use the ngResource module when querying and posting data to a REST API.

你的应用要使用此功能，需导入 angular-resource.js文件，并且将ngResource设为依赖。
Services / Factories The $resource service is used to define RESTful objects which communicate with a REST API.

ngCookies

Use the ngCookies module to handle cookie management within your application.

你的应用要使用此功能，需导入 angular-cookies.js文件，并且将ngCookies设为依赖。
Services / Factories The following services are used for cookie management:
  • The $cookie service is a convenient wrapper to store simple data within browser cookies.
  • $cookieStore is used to store more complex data using serialization.

ngTouch

Use ngTouch when developing for mobile browsers/devices.

你的应用要使用此功能，需导入 angular-touch.js文件，并且将ngTouch设为依赖。
Services / Factories | The $swipe service is used to register and manage mobile DOM events.
Directives | Various directives are available in ngTouch to emulate mobile DOM events.

ngSanitize

Use ngSanitize to securely parse and manipulate HTML data in your application.

你的应用要使用此功能，需导入 angular-sanitize.js文件，并且将ngSanitize设为依赖。
Services / Factories | The $sanitize service is used to clean up dangerous HTML code in a quick and convenient way.
Filters | The linky filter is used to turn URLs into HTML links within the provided string.

ngMock

Use ngMock to inject and mock modules, factories, services and providers within your unit tests

要使用此功能，需导入angular-mocks.js文件到你的测试用例中。
Services / Factories | ngMock will extend the behavior of various core services to become testing aware and manageable in a synchronous manner. Some examples include: $timeout, $interval, $log, $httpBackend, etc...
Global APIs | Various helper functions are available to inject and mock modules within unit test code. Some examples inject(), module(), dump(), etc...


AngularJS: API: auto

auto

Implicit module which gets automatically added to each $injector.

模块组件

Service

名称 | 描述
$injector | $injector is used to retrieve object instances as defined by Provider, instantiate types, invoke methods, and load modules.
$provide | The $provide service has a number of methods for registering components with the $injector. Many of these functions are also exposed on angular.Module.


AngularJS: API: auto/service

Service components in auto

名称 | 描述
$injector | $injector is used to retrieve object instances as defined by Provider, instantiate types, invoke methods, and load modules.
$provide | The $provide service has a number of methods for registering components with the $injector. Many of these functions are also exposed on angular.Module.


AngularJS: API: auto/service/$injector

$injector

  1. - service in module auto

$injector is used to retrieve object instances as defined by Provider, instantiate types, invoke methods, and load modules.

The following always holds true:

  var $injector = angular.injector();
  expect($injector.get('$injector')).toBe($injector);
  expect($injector.invoke(Function($injector){
    return $injector;
  }).toBe($injector);

Injection Function Annotation

JavaScript does not have annotations, and annotations are needed for 依赖注入. The following are all valid ways of annotating function with injection arguments and are equivalent.

  // inferred (only works if code not minified/obfuscated)
  $injector.invoke(Function(serviceA){});

  // annotated
  Function explicit(serviceA) {};
  explicit.$inject = ['serviceA'];
  $injector.invoke(explicit);

  // inline
  $injector.invoke(['serviceA', Function(serviceA){}]);

Inference

In JavaScript calling toString() on a function returns the function definition. The definition can then be parsed and the function arguments can be extracted. 注意： This does not work with minification, and obfuscation tools since these tools change the argument names.

$inject Annotation

By adding an $inject property onto a function the injection parameters can be specified.

Inline

As an array of injection names, where the last item in the array is the function to call.

用法

$injector();

方法

  • get(名称);

    Return an instance of the service.

    参数

    参数 类型 详述
    name string

    The name of the instance to retrieve.

    返回值

    *

    The instance.

  • invoke(fn, [self], [locals]);

    Invoke the method and supply the method arguments from the $injector.

    参数

    参数 类型 详述
    fn !Function

    The function to invoke. Function parameters are injected according to the $inject Annotation rules.
    self
    (可选)
             Object

    The this for the invoked method.
    locals
    (可选)
             Object

    Optional object. If preset then any argument names are read from this object first, before the $injector is consulted.

    返回值

    *

    the value returned by the invoked fn function.

  • has(名称);

    Allows the user to query if the particular service exists.

    参数

    参数 类型 详述
    Name string

    of the service to query.

    返回值

    boolean

    returns true if injector has given service.

  • instantiate(Type, [locals]);

    Create a new instance of JS type. The method takes a constructor function, invokes the new operator, and supplies all of the arguments to the constructor function as specified by the constructor annotation.

    参数

    参数 类型 详述
    Type Function

    Annotated constructor function.
    locals
    (可选)
             Object

    Optional object. If preset then any argument names are read from this object first, before the $injector is consulted.

    返回值

    Object

    new instance of Type.

  • annotate(fn);

    Returns an array of service names which the function is requesting for injection. This API is used by the injector to determine which services need to be injected into the function when the function is invoked. There are three ways in which the function can be annotated with the needed dependencies.

    Argument names

    The simplest form is to extract the dependencies from the arguments of the function. This is done by converting the function into a string using toString() method and extracting the argument names.

      // Given
  Function MyController($scope, $route) {
    // ...
  }

  // Then
  expect(injector.annotate(MyController)).toEqual(['$scope', '$route']);

    This method does not work with code minification / obfuscation. For this reason the following annotation strategies are supported.

    The $inject property

    If a function has an $inject property and its value is an array of strings, then the strings represent names of services to be injected into the function.

      // Given
  var MyController = Function(obfuscatedScope, obfuscatedRoute) {
    // ...
  }
  // Define function dependencies
  MyController['$inject'] = ['$scope', '$route'];

  // Then
  expect(injector.annotate(MyController)).toEqual(['$scope', '$route']);

    The array notation

    It is often desirable to inline Injected functions and that's when setting the $inject property is very inconvenient. In these situations using the array notation to specify the dependencies in a way that survives minification is a better choice:

      // We wish to write this (not minification / obfuscation safe)
  injector.invoke(Function($compile, $rootScope) {
    // ...
  });

  // We are forced to write break inlining
  var tmpFn = Function(obfuscatedCompile, obfuscatedRootScope) {
    // ...
  };
  tmpFn.$inject = ['$compile', '$rootScope'];
  injector.invoke(tmpFn);

  // To better support inline function the inline annotation is supported
  injector.invoke(['$compile', '$rootScope', Function(obfCompile, obfRootScope) {
    // ...
  }]);

  // Therefore
  expect(injector.annotate(
     ['$compile', '$rootScope', Function(obfus_$compile, obfus_$rootScope) {}])
   ).toEqual(['$compile', '$rootScope']);

    参数

    参数 类型 详述
    fn function() Array.<(string|function())>

    Function for which dependent service names need to be retrieved as described above.

    返回值

    Array.<string>

    The names of the services which the function requires.


AngularJS: API: auto/service/$provide

$provide

  1. - service in module auto

The $provide service has a number of methods for registering components with the $injector. Many of these functions are also exposed on angular.Module.

An Angular Service is a singleton object created by a service factory. These service factories are functions which, in turn, are created by a service provider. The service providers are constructor functions. When instantiated they must contain a property called $get, which holds the service factory function.

When you request a service, the $injector is responsible for finding the correct service provider, instantiating it and then calling its $get service factory function to get the instance of the Service.

Often services have no configuration options and there is no need to add methods to the service provider. The provider will be no more than a constructor function with a $get property. For these cases the $provide service has additional helper methods to register services without specifying a provider.

  • provider(provider) - registers a service provider with the $injector
  • constant(obj) - registers a value/object that can be accessed by providers and services.
  • value(obj) - registers a value/object that can only be accessed by services, not providers.
  • factory(fn) - registers a service factory function, fn, that will be wrapped in a service provider object, whose $get property will contain the given factory function.
  • service(class) - registers a constructor function, class that will be wrapped in a service provider object, whose $get property will instantiate a new object using the given constructor function.

See the individual methods for more information and examples.

方法

  • Provider(名称, provider);

    Register a provider function with the $injector. Provider functions are constructor functions, whose instances are responsible for "providing" a factory for a service.

    Service provider names start with the name of the service they provide followed by Provider. 例如，the $log service has a provider called $logProvider.

    Service provider objects can have additional methods which allow configuration of the provider and its service. Importantly, you can configure what kind of service is created by the $get method, or how that service will act. 例如，the $logProvider has a method debugEnabled which lets you specify whether the $log service will log debug messages to the console or not.

    参数

    参数 类型 详述
    name string

    The name of the instance. 注意： the provider will be available under 名称+ 'Provider' key.
    provider Object function()

    If the provider is:

    • Object: then it should have a $get method. The $get method will be invoked using $injector.invoke() when an instance needs to be created.
    • Constructor: a new instance of the provider will be created using $injector.instantiate(), then treated as Object.

    返回值

    Object

    registered provider instance

  • factory(名称, $getFn);

    Register a service factory, which will be called to return the service instance. This is short for registering a service where its provider consists of only a $get property, which is the given service factory function. You should use $provide.factory(getFn) if you do not need to configure your service in a provider.

    参数

    参数 类型 详述
    name string

    The name of the instance.
    $getFn function()

    The $getFn for the instance creation. Internally this is a short hand for $provide.Provider(名称, {$get: $getFn}).

    返回值

    Object

    registered provider instance

  • Service(名称, constructor);

    Register a service constructor, which will be invoked with new to create the service instance. This is short for registering a service where its provider's $get property is the service constructor function that will be used to instantiate the service instance.

    You should use $provide.service(class) if you define your service as a type/class.

    参数

    参数 类型 详述
    name string

    The name of the instance.
    constructor Function

    A class (constructor function) that will be instantiated.

    返回值

    Object

    registered provider instance

  • value(名称, value);

    Register a value service with the $injector, such as a string, a number, an array, an object or a function. This is short for registering a service where its provider's $get property is a factory function that takes no arguments and returns the value service.

    Value services are similar to constant services, except that they cannot be injected into a module configuration function (see config) but they can be overridden by an Angular decorator.

    参数

    参数 类型 详述
    name string

    The name of the instance.
    value *

    The value.

    返回值

    Object

    registered provider instance

  • constant(名称, value);

    Register a constant service, such as a string, a number, an array, an object or a function, with the $injector. Unlike value it can be injected into a module configuration function (see config) and it cannot be overridden by an Angular decorator.

    参数

    参数 类型 详述
    name string

    The name of the constant.
    value *

    The constant value.

    返回值

    Object

    registered instance

  • decorator(名称, decorator);

    Register a service decorator with the $injector. A service decorator intercepts the creation of a service, allowing it to override or modify the behaviour of the service. The object returned by the decorator may be the original service, or a new service object which replaces or wraps and delegates to the original service.

    参数

    参数 类型 详述
    name string

    The name of the service to decorate.
    decorator function()

    This function will be invoked when the service needs to be instantiated and should return the decorated service instance. The function is called using the injector.invoke method and is therefore fully injectable. Local injection arguments:

    • $delegate - The original service instance, which can be monkey patched, configured, decorated or delegated to.


AngularJS: API: ng

ng

ng (core module)

The ng module is loaded by default when an AngularJS application is started. The module itself contains the essential components for an AngularJS application to function. The table below lists a high level breakdown of each of the services/factories, filters, directives and testing components available within this core module.

模块组件

Function

名称 描述
angular.lowercase

转换指定的字符串到小写。
angular.uppercase

Converts the specified string to uppercase.
angular.forEach

Invokes the iterator function once for each item in obj collection, which can be either an object or an array. The iterator function is invoked with iterator(value, key), where value is the value of an object property or an array element and key is the object property key or array element index. Specifying a context for the function is optional.
angular.extend

Extends the destination object dst by copying all of the properties from the src object(s) to dst. You can specify multiple src objects.
angular.noop

A function that performs no operations. 这个函数在使用函数风格写代码时很有用。

     Function foo(callback) {
       var result = calculateResult();
       (callback || angular.noop)(result);
     }
angular.identity

A function that returns its first argument. This function is useful when writing code in the functional style.
angular.isUndefined

检测引用是否未定义。
angular.isDefined

检测引用是否已定义。
angular.isObject

检测引用是否为一个Object. Unlike typeof in JavaScript, nulls are not considered to be objects. Note that JavaScript arrays are objects.
angular.isString

检测引用是否是一个 String.
angular.isNumber

检测引用是否是一个 Number.
angular.isDate

检测值是否为日期。
angular.isArray

检测引用是否为一个Array.
angular.isFunction

检测引用是否是一个 Function.
angular.isElement

检测引用是否为一个DOM元素（或是封装的jQuery元素）。
angular.copy

Creates a deep copy of source, which should be an object or an array.
angular.equals

Determines if two objects or two values are equivalent. Supports value types, regular expressions, arrays and objects.
angular.bind

Returns a function which calls function fn bound to self (self becomes the this for fn). You can supply optional args that are prebound to the function. This feature is also known as partial application, as distinguished from function currying.
angular.toJson

Serializes input into a JSON-formatted string. Properties with leading $$ characters will be stripped since angular uses this notation internally.
angular.fromJson

反序列化JSON字符串。
angular.bootstrap

Use this function to manually start up angular application.
angular.injector

Creates an injector function that can be used for retrieving services as well as for 依赖注入 (see 依赖注入).
angular.element

Wraps a raw DOM element or HTML string as a jQuery element.
angular.module

The angular.module is a global place for creating, registering and retrieving Angular modules. All modules (angular core or 3rd party) that should be available to an application must be registered using this mechanism.

Directive

名称 描述
ngApp

Use this directive to auto-bootstrap an AngularJS application. The ngApp directive designates the root element of the application and is typically placed near the root element of the page -例如 on the <body> or <html> tags.
a

Modifies the default behavior of the html A tag so that the default action is prevented when the href attribute is empty.
ngHref

Using Angular markup like {{hash}} in an href attribute will make the link go to the wrong URL if the user clicks it before Angular has a chance to replace the {{hash}} markup with its value. Until Angular replaces the markup the link will be broken and will most likely return a 404 error.
ngSrc

Using Angular markup like {{hash}} in a src attribute doesn't work right: The browser will fetch from the URL with the literal text {{hash}} until Angular replaces the expression inside {{hash}}. The ngSrc directive solves this problem.
ngSrcset

Using Angular markup like {{hash}} in a srcset attribute doesn't work right: The browser will fetch from the URL with the literal text {{hash}} until Angular replaces the expression inside {{hash}}. The ngSrcset directive solves this problem.
ngDisabled

The following markup will make the button enabled on Chrome/Firefox but not on IE8 and older IEs:

<div ng-init="scope = { isDisabled: false }">
 <button disabled="{{scope.isDisabled}}">Disabled</button>
</div>
ngChecked

HTML规范不要求浏览器对布尔型属性必须给出值，例如checked(它们存在表示true，不存在表示false)。 如果我们放置了一个Angular动态表达式到这样的属性上，在浏览器删除属性时绑定信息将会丢失。 The ngChecked directive solves this problem for the checked attribute. 这个指令不会被浏览器删除，并提供了一个永久的可靠的地方存放绑定信息。
ngReadonly

HTML规范不要求浏览器对布尔型属性必须给出值，例如readonly(它们存在表示true，不存在表示false)。 如果我们放置了一个Angular动态表达式到这样的属性上，在浏览器删除属性时绑定信息将会丢失。 The ngReadonly directive solves this problem for the readonly attribute. 这个指令不会被浏览器删除，并提供了一个永久的可靠的地方存放绑定信息。
ngSelected

HTML规范不要求浏览器对布尔型属性必须给出值，例如selected(它们存在表示true，不存在表示false)。 如果我们放置了一个Angular动态表达式到这样的属性上，在浏览器删除属性时绑定信息将会丢失。 The ngSelected directive solves this problem for the selected attribute. 这个指令不会被浏览器删除，并提供了一个永久的可靠的地方存放绑定信息。
ngOpen

HTML规范不要求浏览器对布尔型属性必须给出值，例如open(它们存在表示true，不存在表示false)。 如果我们放置了一个Angular动态表达式到这样的属性上，在浏览器删除属性时绑定信息将会丢失。 The ngOpen directive solves this problem for the open attribute. 这个指令不会被浏览器删除，并提供了一个永久的可靠的地方存放绑定信息。
ngForm

可嵌套的form指令别名。HTML不允许form元素嵌套。 It is useful to nest forms, for example if the validity of a sub-group of controls needs to be determined.
form

Directive that instantiates FormController.
textarea

HTML textarea element control with angular data-binding. The data-binding and validation properties of this element are exactly the same as those of the input element.
input

HTML input element control with angular data-binding. Input control follows HTML5 input types and polyfills the HTML5 validation behavior for older browsers.
ngModel

The ngModel directive binds an input,select, textarea (or custom form control) to a property on the scope using NgModelController, which is created and exposed by this directive.
ngChange

Evaluate the given expression when the user changes the input. The expression is evaluated immediately, unlike the JavaScript onchange event which only triggers at the end of a change (usually, when the user leaves the form element or presses the return key). The expression is not evaluated when the value change is coming from the model.
ngList

Text input that converts between a delimited string and an array of strings. The delimiter can be a fixed string (by default a comma) or a regular expression.
ngValue

Binds the given expression to the value of input[select] or input[radio], so that when the element is selected, the ngModel of that element is set to the bound value.
ngModelOptions

Allows tuning how model updates are done. Using ngModelOptions you can specify a custom list of events that will trigger a model update and/or a debouncing delay so that the actual update only takes place when a timer expires; this timer will be reset after another change takes place.
ngBind

The ngBind attribute tells Angular to replace the text content of the specified HTML element with the value of a given expression, and to update the text content when the value of that expression changes.
ngBindTemplate

The ngBindTemplate directive specifies that the element text content should be replaced with the interpolation of the template in the ngBindTemplate attribute. Unlike ngBind, the ngBindTemplate can contain multiple {{ }} expressions. This directive is needed since some HTML elements (such as TITLE and OPTION) cannot contain SPAN elements.
ngBindHtml

Creates a binding that will innerHTML the result of evaluating the expression into the current element in a secure way. 默认情况下， the innerHTML-ed content will be sanitized using the $sanitize service. To utilize this functionality, ensure that $sanitize is available, 例如，by including ngSanitize in your module's dependencies (not in core Angular.) You may also bypass sanitization for values you know are safe. To do so, bind to an explicitly trusted value via $sce.trustAsHtml. See the example under Strict Contextual Escaping (SCE).
ngClass

The ngClass directive allows you to dynamically set CSS classes on an HTML element by databinding an expression that represents all classes to be added.
ngClassOdd

The ngClassOdd and ngClassEven directives work exactly as ngClass, except they work in conjunction with ngRepeat and take effect only on odd (even) rows.
ngClassEven

The ngClassOdd and ngClassEven directives work exactly as ngClass, except they work in conjunction with ngRepeat and take effect only on odd (even) rows.
ngCloak

The ngCloak directive is used to prevent the Angular html template from being briefly displayed by the browser in its raw (uncompiled) form while your application is loading. Use this directive to avoid the undesirable flicker effect caused by the html template display.
ngController

The ngController directive attaches a controller class to the view. This is a key aspect of how angular supports the principles behind the Model-View-Controller design pattern.
ngCsp

Enables CSP (Content Security Policy) support.
ngClick

The ngClick directive allows you to specify custom behavior when an element is clicked.
ngDblclick

The ngDblclick directive allows you to 指定自定义行为到a dblclick事件上。
ngMousedown

The ngMousedown directive allows you to 指定自定义行为到mousedown事件上。
ngMouseup

指定自定义行为到mouseup事件上。
ngMouseover

指定自定义行为到mouseover事件上。
ngMouseenter

指定自定义行为到mouseenter事件上。
ngMouseleave

指定自定义行为到mouseleave事件上。
ngMousemove

指定自定义行为到mousemove事件上。
ngKeydown

指定自定义行为到keydown事件上。
ngKeyup

指定自定义行为到keyup事件上。
ngKeypress

指定自定义行为到keypress事件上。
ngSubmit

Enables binding Angular表达式s to onsubmit events.
ngFocus

指定自定义行为到focus事件上。
ngBlur

指定自定义行为到blur事件上。
ngCopy

指定自定义行为到copy事件上。
ngCut

为剪切事件指定自定义行为。
ngPaste

指定自定义行为到paste事件上。
ngIf

The ngIf directive removes or recreates a portion of the DOM tree based on an {expression}. If the expression assigned to ngIf evaluates to a false value then the element is removed from the DOM, otherwise a clone of the element is reinserted into the DOM.
ngInclude

Fetches, compiles and includes an external HTML fragment.
ngInit

The ngInit directive allows you to evaluate an expression in the current scope.
ngNonBindable

The ngNonBindable directive tells Angular not to compile or bind the contents of the current DOM element. This is useful if the element contains what appears to be Angular directives and bindings but which should be ignored by Angular. This could be the case if you have a site that displays snippets of code, for instance.
ngPluralize

ngPluralize is a directive that displays messages according to en-US localization rules. These rules are bundled with angular.js, but can be overridden (see Angular i18n dev guide). You configure ngPluralize directive by specifying the mappings between 多元化条目 and the strings to be displayed.
ngRepeat

The ngRepeat directive instantiates a template once per item from a collection. Each template instance gets its own scope, where the given loop variable is set to the current collection item, and $index is set to the item index or key.
ngShow

The ngShow directive shows or hides the given HTML element based on the expression provided to the ngShow attribute. The element is shown or hidden by removing or adding the ng-hide CSS class onto the element. The .ng-hide CSS class is predefined in AngularJS and sets the display style to none (using an !important flag). For CSP mode please add angular-csp.css to your html file (see ngCsp).
ngHide

The ngHide directive shows or hides the given HTML element based on the expression provided to the ngHide attribute. The element is shown or hidden by removing or adding the ng-hide CSS class onto the element. The .ng-hide CSS class is predefined in AngularJS and sets the display style to none (using an !important flag). For CSP mode please add angular-csp.css to your html file (see ngCsp).
ngStyle

The ngStyle directive allows you to set CSS style on an HTML element conditionally.
ngSwitch

The ngSwitch directive is used to conditionally swap DOM structure on your template based on a scope expression. Elements within ngSwitch but without ngSwitchWhen or ngSwitchDefault directives will be preserved at the location as specified in the template.
ngTransclude

Directive that marks the insertion point for the transcluded DOM of the nearest parent directive that uses transclusion.
script

Load the content of a <script> element into $templateCache, so that the template can be used by ngInclude, ngView, or directives. The type of the <script> element must be specified as text/ng-template, and a cache name for the template must be assigned through the element's id, which can then be used as a directive's templateUrl.
select

HTML SELECT element with angular data-binding.

Object

名称 | 描述
angular.version | An object that contains information about the current AngularJS version. This object has the following properties:

Type

名称 | 描述
angular.Module | Interface for configuring angular modules.
$cacheFactory.Cache | A cache object used to store and retrieve data, primarily used by $http and the script directive to cache templates and other data.
$compile.directive.Attributes | A shared object between directive compile / linking functions which contains normalized DOM element attributes. The values reflect current binding state {{ }}. The normalization is needed since all of these are treated as equivalent in Angular:
form.FormController | FormController keeps track of all its controls and nested forms as well as the state of them, such as being valid/invalid or dirty/pristine.
ngModel.NgModelController | NgModelController provides API for the ng-model directive. The controller contains services for data-binding, validation, CSS updates, and value formatting and parsing. It purposefully does not contain any logic which deals with DOM rendering or listening to DOM events. Such DOM related logic should be provided by other directives which make use of NgModelController for data-binding.
$rootScope.Scope | A root scope can be retrieved using the $rootScope key from the $injector. Child scopes are created using the $new() method. (Most scopes are created automatically when compiled HTML template is executed.)

Service

名称 | 描述
$anchorScroll | When called, it checks current value of $location.hash() and scrolls to the related element, according to rules specified in Html5 spec.
$animate | The $animate service provides rudimentary DOM manipulation functions to insert, remove and move elements within the DOM, as well as adding and removing classes. This service is the core service used by the ngAnimate $animator service which provides high-level animation hooks for CSS and JavaScript.
$cacheFactory | Factory that constructs Cache objects and gives access to them.
$templateCache | The first time a template is used, it is loaded in the template cache for quick retrieval. You can load templates directly into the cache in a script tag, or by consuming the $templateCache service directly.
$compile | Compiles an HTML string or DOM into a template and produces a template function, which can then be used to link scope and the template together.
$controller | $controller service is responsible for instantiating controllers.
$document | A jQuery or jqLite wrapper for the browser's window.document object.
$exceptionHandler | Any uncaught exception in Angular表达式s is delegated to this service. The default implementation simply delegates to $log.error which logs it into the browser console.
$filter | Filters are used for formatting data displayed to the user.
$http | The $http service is a core Angular service that facilitates communication with the remote HTTP servers via the browser's XMLHttpRequest object or via JSONP.
$httpBackend | HTTP backend used by the Service that delegates to XMLHttpRequest object or JSONP and deals with browser incompatibilities.
$interpolate | Compiles a string with markup into an interpolation function. This service is used by the HTML $compile service for data binding. See $interpolateProvider for configuring the interpolation markup.
$interval | Angular's wrapper for window.setInterval. The fn function is executed every delay milliseconds.
$locale | $locale service provides localization rules for various Angular components. As of right now the only public api is:
$location | The $location service parses the URL in the browser address bar (based on the window.location) and makes the URL available to your application. Changes to the URL in the address bar are reflected into $location service and changes to $location are reflected into the browser address bar.
$log | Simple service for logging. Default implementation safely writes the message into the browser's console (if present).
$parse | Converts Angular expression into a function.
$q | A promise/deferred implementation inspired by Kris Kowal's Q.
$rootElement | The root element of Angular application. This is either the element where ngApp was declared or the element passed into angular.bootstrap. The element represent the root element of application. It is also the location where the applications $injector service gets published, it can be retrieved using $rootElement.injector().
$rootScope | Every application has a single root scope. All other scopes are descendant scopes of the root scope. Scopes provide separation between the model and the view, via a mechanism for watching the model for changes. They also provide an event emission/broadcast and subscription facility. See the developer guide on scopes.
$sceDelegate | $sceDelegate is a service that is used by the $sce service to provide Strict Contextual Escaping (SCE) services to AngularJS.
$sce | $sce is a service that provides Strict Contextual Escaping services to AngularJS.
$timeout | Angular's wrapper for window.setTimeout. The fn function is wrapped into a try/catch block and delegates any exceptions to $exceptionHandler service.
$window | A reference to the browser's window object. While window is globally available in JavaScript, it causes testability problems, because it is a global variable. In angular we always refer to it through the $window service, so it may be overridden, removed or mocked for testing.

Provider

名称 描述
$animateProvider

Default implementation of $animate that doesn't perform any animations, instead just synchronously performs DOM updates and calls done() callbacks.
$compileProvider
$controllerProvider

The $controller service is used by Angular to create new controllers.
$filterProvider

Filters are just functions which transform input to an output. However filters need to be Dependency Injected. To achieve this a filter definition consists of a factory function which is annotated with dependencies and is responsible for creating a filter function.
$httpProvider

Use $httpProvider to change the default behavior of the $http service.
$interpolateProvider

Used for configuring the interpolation markup. Defaults to {{ and }}.
$locationProvider

Use the $locationProvider to configure how the application deep linking paths are stored.
$logProvider

Use the $logProvider to configure how the application logs messages
$parseProvider

$parseProvider can be used for configuring the default behavior of the $parse service.
$rootScopeProvider

Provider for the $rootScope service.
$sceDelegateProvider

The $sceDelegateProvider provider allows developers to configure the $sceDelegate service. This allows one to get/set the whitelists and blacklists used to ensure that the URLs used for sourcing Angular templates are safe. Refer $sceDelegateProvider.resourceUrlWhitelist and $sceDelegateProvider.resourceUrlBlacklist
$sceProvider

The $sceProvider provider allows developers to configure the $sce service.

  • enable/disable Strict Contextual Escaping (SCE) in a module
  • override the default implementation with a custom delegate

Input

名称 | 描述
input[text] | Standard HTML text input with angular data binding.
input[date] | 目前的浏览器还不支持HTML5的日期输入控件,所以将使用文本输入。 在这种情况下，输入的文本必须符合ISO-8601的日期格式(yyyy-MM-dd)的校验规范，例如： 2009-01-06. 模型必须永远是一个Date对象。
input[dateTimeLocal] | Input with datetime validation and transformation. In browsers that do not yet support the HTML5 date input, a text element will be used. In that case, the text must be entered in a valid ISO-8601 local datetime format (yyyy-MM-ddTHH:mm), 例如: 2010-12-28T14:57. 模型必须永远是一个Date对象。
input[time] | Input with time validation and transformation. In browsers that do not yet support the HTML5 date input, a text element will be used. In that case, the text must be entered in a valid ISO-8601 local time format (HH:mm), 例如: 14:57. 模型必须是一个Date对象。 This binding will always output a Date object to the model of January 1, 1900, or local date new Date(0, 0, 1, HH, mm).
input[week] | Input with week-of-the-year validation and transformation to Date. In browsers that do not yet support the HTML5 week input, a text element will be used. In that case, the text must be entered in a valid ISO-8601 week format (yyyy-W##), 例如: 2013-W02. 模型必须永远是一个Date对象。
input[month] | Input with month validation and transformation. In browsers that do not yet support the HTML5 month input, a text element will be used. In that case, the text must be entered in a valid ISO-8601 month format (yyyy-MM), 例如: 2009-01. 模型必须永远是一个Date对象。 In the event the model is not set to the first of the month, the first of that model's month is assumed.
input[number] | Text input with number validation and transformation. Sets the number validation error if not a valid number.
input[url] | Text input with URL validation. Sets the url validation error key if the content is not a valid URL.
input[email] | Text input with email validation. Sets the email validation error key if not a valid email address.
input[radio] | HTML radio button.
input[checkbox] | HTML checkbox.

Filter

名称 | 描述
Filter | Selects a subset of items from array and returns it as a new array.
currency | Formats a number as a currency (ie $1,234.56). When no currency symbol is provided, default symbol for current locale is used.
number | Formats a number as text.
date | Formats date to a string based on the requested format.
json | Allows you to convert a JavaScript object into JSON string.
lowercase | Converts string to lowercase.
uppercase | Converts string to uppercase.
limitTo | Creates a new array or string containing only a specified number of elements. The elements are taken from either the beginning or the end of the source array or string, as specified by the value and sign (positive or negative) of limit.
orderBy | Orders a specified array by the expression predicate. It is ordered alphabetically for strings and numerically for numbers. 注意： if you notice numbers are not being sorted correctly, make sure they are actually being saved as numbers and not strings.


AngularJS: API: ng/directive

Directive components in ng

名称 描述
ngApp

Use this directive to auto-bootstrap an AngularJS application. The ngApp directive designates the root element of the application and is typically placed near the root element of the page -例如 on the <body> or <html> tags.
a

Modifies the default behavior of the html A tag so that the default action is prevented when the href attribute is empty.
ngHref

Using Angular markup like {{hash}} in an href attribute will make the link go to the wrong URL if the user clicks it before Angular has a chance to replace the {{hash}} markup with its value. Until Angular replaces the markup the link will be broken and will most likely return a 404 error.
ngSrc

Using Angular markup like {{hash}} in a src attribute doesn't work right: The browser will fetch from the URL with the literal text {{hash}} until Angular replaces the expression inside {{hash}}. The ngSrc directive solves this problem.
ngSrcset

Using Angular markup like {{hash}} in a srcset attribute doesn't work right: The browser will fetch from the URL with the literal text {{hash}} until Angular replaces the expression inside {{hash}}. The ngSrcset directive solves this problem.
ngDisabled

The following markup will make the button enabled on Chrome/Firefox but not on IE8 and older IEs:

<div ng-init="scope = { isDisabled: false }">
 <button disabled="{{scope.isDisabled}}">Disabled</button>
</div>
ngChecked

HTML规范不要求浏览器对布尔型属性必须给出值，例如checked(它们存在表示true，不存在表示false)。 如果我们放置了一个Angular动态表达式到这样的属性上，在浏览器删除属性时绑定信息将会丢失。 The ngChecked directive solves this problem for the checked attribute. 这个指令不会被浏览器删除，并提供了一个永久的可靠的地方存放绑定信息。
ngReadonly

HTML规范不要求浏览器对布尔型属性必须给出值，例如readonly(它们存在表示true，不存在表示false)。 如果我们放置了一个Angular动态表达式到这样的属性上，在浏览器删除属性时绑定信息将会丢失。 The ngReadonly directive solves this problem for the readonly attribute. 这个指令不会被浏览器删除，并提供了一个永久的可靠的地方存放绑定信息。
ngSelected

HTML规范不要求浏览器对布尔型属性必须给出值，例如selected(它们存在表示true，不存在表示false)。 如果我们放置了一个Angular动态表达式到这样的属性上，在浏览器删除属性时绑定信息将会丢失。 The ngSelected directive solves this problem for the selected attribute. 这个指令不会被浏览器删除，并提供了一个永久的可靠的地方存放绑定信息。
ngOpen

HTML规范不要求浏览器对布尔型属性必须给出值，例如open(它们存在表示true，不存在表示false)。 如果我们放置了一个Angular动态表达式到这样的属性上，在浏览器删除属性时绑定信息将会丢失。 The ngOpen directive solves this problem for the open attribute. 这个指令不会被浏览器删除，并提供了一个永久的可靠的地方存放绑定信息。
ngForm

可嵌套的form指令别名。HTML不允许form元素嵌套。 It is useful to nest forms, for example if the validity of a sub-group of controls needs to be determined.
form

Directive that instantiates FormController.
textarea

HTML textarea element control with angular data-binding. The data-binding and validation properties of this element are exactly the same as those of the input element.
input

HTML input element control with angular data-binding. Input control follows HTML5 input types and polyfills the HTML5 validation behavior for older browsers.
ngModel

The ngModel directive binds an input,select, textarea (or custom form control) to a property on the scope using NgModelController, which is created and exposed by this directive.
ngChange

Evaluate the given expression when the user changes the input. The expression is evaluated immediately, unlike the JavaScript onchange event which only triggers at the end of a change (usually, when the user leaves the form element or presses the return key). The expression is not evaluated when the value change is coming from the model.
ngList

Text input that converts between a delimited string and an array of strings. The delimiter can be a fixed string (by default a comma) or a regular expression.
ngValue

Binds the given expression to the value of input[select] or input[radio], so that when the element is selected, the ngModel of that element is set to the bound value.
ngModelOptions

Allows tuning how model updates are done. Using ngModelOptions you can specify a custom list of events that will trigger a model update and/or a debouncing delay so that the actual update only takes place when a timer expires; this timer will be reset after another change takes place.
ngBind

The ngBind attribute tells Angular to replace the text content of the specified HTML element with the value of a given expression, and to update the text content when the value of that expression changes.
ngBindTemplate

The ngBindTemplate directive specifies that the element text content should be replaced with the interpolation of the template in the ngBindTemplate attribute. Unlike ngBind, the ngBindTemplate can contain multiple {{ }} expressions. This directive is needed since some HTML elements (such as TITLE and OPTION) cannot contain SPAN elements.
ngBindHtml

Creates a binding that will innerHTML the result of evaluating the expression into the current element in a secure way. 默认情况下， the innerHTML-ed content will be sanitized using the $sanitize service. To utilize this functionality, ensure that $sanitize is available, 例如，by including ngSanitize in your module's dependencies (not in core Angular.) You may also bypass sanitization for values you know are safe. To do so, bind to an explicitly trusted value via $sce.trustAsHtml. See the example under Strict Contextual Escaping (SCE).
ngClass

The ngClass directive allows you to dynamically set CSS classes on an HTML element by databinding an expression that represents all classes to be added.
ngClassOdd

The ngClassOdd and ngClassEven directives work exactly as ngClass, except they work in conjunction with ngRepeat and take effect only on odd (even) rows.
ngClassEven

The ngClassOdd and ngClassEven directives work exactly as ngClass, except they work in conjunction with ngRepeat and take effect only on odd (even) rows.
ngCloak

The ngCloak directive is used to prevent the Angular html template from being briefly displayed by the browser in its raw (uncompiled) form while your application is loading. Use this directive to avoid the undesirable flicker effect caused by the html template display.
ngController

The ngController directive attaches a controller class to the view. This is a key aspect of how angular supports the principles behind the Model-View-Controller design pattern.
ngCsp

Enables CSP (Content Security Policy) support.
ngClick

The ngClick directive allows you to specify custom behavior when an element is clicked.
ngDblclick

The ngDblclick directive allows you to 指定自定义行为到a dblclick事件上。
ngMousedown

The ngMousedown directive allows you to 指定自定义行为到mousedown事件上。
ngMouseup

指定自定义行为到mouseup事件上。
ngMouseover

指定自定义行为到mouseover事件上。
ngMouseenter

指定自定义行为到mouseenter事件上。
ngMouseleave

指定自定义行为到mouseleave事件上。
ngMousemove

指定自定义行为到mousemove事件上。
ngKeydown

指定自定义行为到keydown事件上。
ngKeyup

指定自定义行为到keyup事件上。
ngKeypress

指定自定义行为到keypress事件上。
ngSubmit

Enables binding Angular表达式s to onsubmit events.
ngFocus

指定自定义行为到focus事件上。
ngBlur

指定自定义行为到blur事件上。
ngCopy

指定自定义行为到copy事件上。
ngCut

为剪切事件指定自定义行为。
ngPaste

指定自定义行为到paste事件上。
ngIf

The ngIf directive removes or recreates a portion of the DOM tree based on an {expression}. If the expression assigned to ngIf evaluates to a false value then the element is removed from the DOM, otherwise a clone of the element is reinserted into the DOM.
ngInclude

Fetches, compiles and includes an external HTML fragment.
ngInit

The ngInit directive allows you to evaluate an expression in the current scope.
ngNonBindable

The ngNonBindable directive tells Angular not to compile or bind the contents of the current DOM element. This is useful if the element contains what appears to be Angular directives and bindings but which should be ignored by Angular. This could be the case if you have a site that displays snippets of code, for instance.
ngPluralize

ngPluralize is a directive that displays messages according to en-US localization rules. These rules are bundled with angular.js, but can be overridden (see Angular i18n dev guide). You configure ngPluralize directive by specifying the mappings between 多元化条目 and the strings to be displayed.
ngRepeat

The ngRepeat directive instantiates a template once per item from a collection. Each template instance gets its own scope, where the given loop variable is set to the current collection item, and $index is set to the item index or key.
ngShow

The ngShow directive shows or hides the given HTML element based on the expression provided to the ngShow attribute. The element is shown or hidden by removing or adding the ng-hide CSS class onto the element. The .ng-hide CSS class is predefined in AngularJS and sets the display style to none (using an !important flag). For CSP mode please add angular-csp.css to your html file (see ngCsp).
ngHide

The ngHide directive shows or hides the given HTML element based on the expression provided to the ngHide attribute. The element is shown or hidden by removing or adding the ng-hide CSS class onto the element. The .ng-hide CSS class is predefined in AngularJS and sets the display style to none (using an !important flag). For CSP mode please add angular-csp.css to your html file (see ngCsp).
ngStyle

The ngStyle directive allows you to set CSS style on an HTML element conditionally.
ngSwitch

The ngSwitch directive is used to conditionally swap DOM structure on your template based on a scope expression. Elements within ngSwitch but without ngSwitchWhen or ngSwitchDefault directives will be preserved at the location as specified in the template.
ngTransclude

Directive that marks the insertion point for the transcluded DOM of the nearest parent directive that uses transclusion.
script

Load the content of a <script> element into $templateCache, so that the template can be used by ngInclude, ngView, or directives. The type of the <script> element must be specified as text/ng-template, and a cache name for the template must be assigned through the element's id, which can then be used as a directive's templateUrl.
select

HTML SELECT element with angular data-binding.


AngularJS: API: ng/directive/a

a

  1. - directive in module ng

修改Html的A标签的默认行为，防止href属性为空时的默认操作。

这个改变更容易创建基于 ngClick 指令的操作，而不会引起地址跳转或页面刷新, 例如: <a href="" ng-click="list.addItem()">Add Item</a>

指令信息

  • 这个指令执行优先级为0.

用法

  • 作为元素使用:
    <a>
...
</a>


AngularJS: API: ng/directive/form

form

  1. - directive in module ng

指令会实例化 FormController。

如果声明了 name 属性，表单控制器会被发布到name对应的作用域下。

别名: ngForm

Angular中的表单能够嵌套。 意思是当所有子表单有效时外部表单也会有效。然而，浏览器不允许 <form> 元素嵌套，所以Angular提供了 ngForm 指令来实现 <form> 相同的行为，并能进行嵌套。嵌套表单让你在使用 ngRepeat 指令动态生成的表单上使用Angula的校验指令时更方便。在此以前，由于使用修改方式不能动态生成输入元素的 name 属性，你必须使用 ngForm 指令包裹重复生成的集合中的每个输入对象，再在外部嵌套 form元素。

CSS类

  • ng-valid 表单通过验证时设置
  • ng-invalid 表单未通过验证时设置
  • ng-pristine 表单没有改动时设置
  • ng-dirty 表单有改动时设置

记住 ngAnimate 能侦测这些类中每个的添加和删除。

提交一个表单并防止默认动作

在富客户端式Angular应用中的表单身份不同于在以往的循环链式应用中的身份。为防止浏览器在发送数据到服务器时不会由于表单提交引起整个页面重载，所以在应用中通过特殊手段触发javascript逻辑来处理表单提交。

为此，Angular防止默认操作（表单提交到服务器），除非 <form> 元素指定了 action 属性.

你可以使用以下两种方法之一来指定表单提交时要调用的javascript方法：

  • form元素上的ngSubmit 指令
  • 第一个按钮或类型为submit的input字段(input[type=submit])上的ngClick 指令

为了防止处理程序的双重执行，你只能使用 ngSubmit 或 ngClick 指令的其中一个。这是因为HTML规范有以下表单提交规则:

  • 如果表单只有一个input字段，在这个字段按回车将触发表单提交(ngSubmit)
  • 如果表单有两个以上input字段并且没有按钮或没有input[type=submit] ,按回车不会触发提交
  • 如果表单有一个或多个input字段，并且有一个或多个按钮，或有input[type=submit]，在任意input字段中按回车后将触发 第一个 按钮或 input[type=submit]上的click事件 (ngClick) 和 整个表单的submit事件 (ngSubmit)

当整个表单提交时，任何挂起的 ngModelOptions 更改将立即生效。注意， ngClick 事件将在模型被更新前触发。可以使用 ngSubmit访问更新的模型。

指令信息

  • 这个指令执行优先级为0.

用法

  • 作为元素使用:
    <form
  [name=""]>
...
</form>

参数

参数 类型 详述
name
(可选)
string

表单名称。如果指定，表单控制器将被发布到这个名字下相关的域范围中。

动画钩子

ngForm中的动画将在任何级联CSS类被添加或删除时触发。这此类有: .ng-pristine, .ng-dirty, .ng-invalid 和 .ng-valid ，以及表单执行的任何其他验证。ngForm中的动画类似ngClass中的工作方式，并且动画可以挂在 CSS 过渡、关键帧、JS动画上。

下面的例子简单的演示了一个利用 CSS 样式过渡来渲染一个验证时未通过验证的表单元素:

//be sure to include ngAnimate as a module to hook into more
//advanced animations
.my-form {
  transition:0.5s linear all;
  background: white;
}
.my-form.ng-invalid {
  background: red;
  color:white;
}

示例

index.html
<script>
  angular.module('formExample', [])
    .controller('FormController', ['$scope', Function($scope) {
      $scope.userType = 'guest';
    }]);
</script>
<style>
 .my-form {
   -webkit-transition:all linear 0.5s;
   transition:all linear 0.5s;
   background: transparent;
 }
 .my-form.ng-invalid {
   background: red;
 }
</style>
<form name="myForm" ng-controller="FormController" class="my-form">
  userType: <input name="input" ng-model="userType" required>
  <span class="error" ng-show="myForm.input.$error.required">Required!</span><br>
  <tt>userType = {{userType}}</tt><br>
  <tt>myForm.input.$valid = {{myForm.input.$valid}}</tt><br>
  <tt>myForm.input.$error = {{myForm.input.$error}}</tt><br>
  <tt>myForm.$valid = {{myForm.$valid}}</tt><br>
  <tt>myForm.$error.required = {{!!myForm.$error.required}}</tt><br>
 </form>
protractor.js
it('should initialize to model', Function() {
  var userType = element(by.binding('userType'));
  var valid = element(by.binding('myForm.input.$valid'));

  expect(userType.getText()).toContain('guest');
  expect(valid.getText()).toContain('true');});

it('should be invalid if empty', Function() {
  var userType = element(by.binding('userType'));
  var valid = element(by.binding('myForm.input.$valid'));
  var userInput = element(by.model('userType'));

  userInput.clear();
  userInput.sendKeys('');

  expect(userType.getText()).toEqual('userType =');
  expect(valid.getText()).toContain('false');});


AngularJS: API: ng/directive/input

input

  1. - directive in module ng

Angular数据绑定HTML输入元素控制。输入控制跟随HTML5的输入类型，并为旧的浏览器模拟(polyfills)HTML5验证行为。

指令信息

  • 这个指令执行优先级为0.

用法

  • 作为元素使用:
    <input
  ng-model=""
  [name=""]
  [required=""]
  [ng-required=""]
  [ng-minlength=""]
  [ng-maxlength=""]
  [ng-pattern=""]
  [ng-change=""]>
...
</input>

参数

参数 | 类型 | 详述
ngModel | string | 声明用于数据绑定的Angular表达式。
name (可选) | string | 发布到表单下的控件的属性名称。
required (可选) | string | 如果未输入值就设置 required 验证错误键。
ngRequired (可选) | boolean | 如果值为true则置为 required 属性
ngMinlength (可选) | number | 如果值短于minlength则设置 minlength 验证错误键。
ngMaxlength (可选) | number | 如果值长于maxlength则设置 maxlength 验证错误键。
ngPattern (可选) | string | 如果值不匹配正则表达式则设置 pattern 验证错误键。 值可以是 /regexp/ 形式的内嵌正则表达式，或者是用 regexp 定义在scope中的表达式。
ngChange (可选) | string | Angular表达式，当输入元素通过用户交互方式发生输入变化时会执行这个表达式。

示例

index.html
<script>
   angular.module('inputExample', [])
     .controller('ExampleController', ['$scope', Function($scope) {
       $scope.user = {name: 'guest', last: 'visitor'};
     }]);
</script>
<div ng-controller="ExampleController">
  <form name="myForm">
    User name: <input Type="text" name="userName" ng-model="user.name" required>
    <span class="error" ng-show="myForm.userName.$error.required">
      Required!</span><br>
    Last name: <input Type="text" name="lastName" ng-model="user.last"
      ng-minlength="3" ng-maxlength="10">
    <span class="error" ng-show="myForm.lastName.$error.minlength">
      Too short!</span>
    <span class="error" ng-show="myForm.lastName.$error.maxlength">
      Too long!</span><br>
  </form>
  <hr>
  <tt>user = {{user}}</tt><br/>
  <tt>myForm.userName.$valid = {{myForm.userName.$valid}}</tt><br>
  <tt>myForm.userName.$error = {{myForm.userName.$error}}</tt><br>
  <tt>myForm.lastName.$valid = {{myForm.lastName.$valid}}</tt><br>
  <tt>myForm.lastName.$error = {{myForm.lastName.$error}}</tt><br>
  <tt>myForm.$valid = {{myForm.$valid}}</tt><br>
  <tt>myForm.$error.required = {{!!myForm.$error.required}}</tt><br>
  <tt>myForm.$error.minlength = {{!!myForm.$error.minlength}}</tt><br>
  <tt>myForm.$error.maxlength = {{!!myForm.$error.maxlength}}</tt><br>
</div>
protractor.js
var user = element(by.binding('{{user}}'));
var userNameValid = element(by.binding('myForm.userName.$valid'));
var lastNameValid = element(by.binding('myForm.lastName.$valid'));
var lastNameError = element(by.binding('myForm.lastName.$error'));
var formValid = element(by.binding('myForm.$valid'));
var userNameInput = element(by.model('user.name'));
var userLastInput = element(by.model('user.last'));

it('should initialize to model', Function() {
  expect(user.getText()).toContain('{"name":"guest","last":"visitor"}');
  expect(userNameValid.getText()).toContain('true');
  expect(formValid.getText()).toContain('true');});

it('should be invalid if empty when required', Function() {
  userNameInput.clear();
  userNameInput.sendKeys('');

  expect(user.getText()).toContain('{"last":"visitor"}');
  expect(userNameValid.getText()).toContain('false');
  expect(formValid.getText()).toContain('false');});

it('should be valid if empty when min length is set', Function() {
  userLastInput.clear();
  userLastInput.sendKeys('');

  expect(user.getText()).toContain('{"name":"guest","last":""}');
  expect(lastNameValid.getText()).toContain('true');
  expect(formValid.getText()).toContain('true');});

it('should be invalid if less than required min length', Function() {
  userLastInput.clear();
  userLastInput.sendKeys('xx');

  expect(user.getText()).toContain('{"name":"guest"}');
  expect(lastNameValid.getText()).toContain('false');
  expect(lastNameError.getText()).toContain('minlength');
  expect(formValid.getText()).toContain('false');});

it('should be invalid if longer than max length', Function() {
  userLastInput.clear();
  userLastInput.sendKeys('some ridiculously long name');

  expect(user.getText()).toContain('{"name":"guest"}');
  expect(lastNameValid.getText()).toContain('false');
  expect(lastNameError.getText()).toContain('maxlength');
  expect(formValid.getText()).toContain('false');});


AngularJS: API: ng/directive/input[checkbox]

input[checkbox]

  1. - input in module ng

HTML复选框。

指令信息

  • 这个指令执行优先级为0.

用法

<input Type="checkbox"
       ng-model=""
       [name=""]
       [ng-true-value=""]
       [ng-false-value=""]
       [ng-change=""]>

参数

参数 | 类型 | 详述
ngModel | string | 声明用于数据绑定的Angular表达式。
name (可选) | string | 发布到表单下的控件的属性名称。
ngTrueValue (可选) | expression | 当被选中时，value会被置为表达式的值。
ngFalseValue (可选) | expression | 当未被选中时，value会被置为表达式的值。
ngChange (可选) | string | Angular表达式，当输入元素通过用户交互方式发生输入变化时会执行这个表达式。

示例

index.html
<script>
  angular.module('checkboxExample', [])
    .controller('ExampleController', ['$scope', Function($scope) {
      $scope.value1 = true;
      $scope.value2 = 'YES'
    }]);
</script>
<form name="myForm" ng-controller="ExampleController">
  Value1: <input Type="checkbox" ng-model="value1"> <br/>
  Value2: <input Type="checkbox" ng-model="value2"
                 ng-true-value="'YES'" ng-false-value="'NO'"> <br/>
  <tt>value1 = {{value1}}</tt><br/>
  <tt>value2 = {{value2}}</tt><br/>
</form>
protractor.js
it('should change state', Function() {
  var value1 = element(by.binding('value1'));
  var value2 = element(by.binding('value2'));

  expect(value1.getText()).toContain('true');
  expect(value2.getText()).toContain('YES');

  element(by.model('value1')).click();
  element(by.model('value2')).click();

  expect(value1.getText()).toContain('false');
  expect(value2.getText()).toContain('NO');});


AngularJS: API: ng/directive/input[date]

input[date]

  1. - input in module ng

日期输入的验证和转换。目前的浏览器还不支持HTML5的日期输入控件,所以将使用文本输入。 在这种情况下，输入的文本必须符合ISO-8601的日期格式(yyyy-MM-dd)的校验规范，例如： 2009-01-06. 模型必须永远是一个Date对象。

指令信息

  • 这个指令执行优先级为0.

用法

<input Type="date"
       ng-model=""
       [name=""]
       [min=""]
       [max=""]
       [required=""]
       [ng-required=""]
       [ng-change=""]>

参数

参数 | 类型 | 详述
ngModel | string | 声明用于数据绑定的Angular表达式。
name (可选) | string | 发布到表单下的控件的属性名称。
min (可选) | string | 当输入的值小于min时，设置min 验证错误键。 值必须是符合ISO的日期字符串(yyyy-MM-dd)。
max (可选) | string | 当输入的值大于max时，设置max验证错误键。值必须是符合ISO的日期字符串(yyyy-MM-dd)。
required (可选) | string | 如果未输入值就设置 required 验证错误键。
ngRequired (可选) | string | 当ngRequired表达式等于true时，添加required属性和required验证约束到元素上。 使用ngRequired替换required，当你想数据绑定到required属性上时。
ngChange (可选) | string | Angular表达式，当输入元素通过用户交互方式发生输入变化时会执行这个表达式。

示例

index.html
<script>
   angular.module('dateInputExample', [])
     .controller('DateController', ['$scope', Function($scope) {
       $scope.value = new Date(2013, 9, 22);
     }]);
</script>
<form name="myForm" ng-controller="DateController as dateCtrl">
   Pick a date between in 2013:
   <input Type="date" id="exampleInput" name="input" ng-model="value"
       placeholder="yyyy-MM-dd" min="2013-01-01" max="2013-12-31" required />
   <span class="error" ng-show="myForm.input.$error.required">
       Required!</span>
   <span class="error" ng-show="myForm.input.$error.date">
       Not a valid date!</span>
    <tt>value = {{value | date: "yyyy-MM-dd"}}</tt><br/>
    <tt>myForm.input.$valid = {{myForm.input.$valid}}</tt><br/>
    <tt>myForm.input.$error = {{myForm.input.$error}}</tt><br/>
    <tt>myForm.$valid = {{myForm.$valid}}</tt><br/>
    <tt>myForm.$error.required = {{!!myForm.$error.required}}</tt><br/>
</form>
protractor.js
var value = element(by.binding('value | date: "yyyy-MM-dd"'));
var valid = element(by.binding('myForm.input.$valid'));
var input = element(by.model('value'));

// currently protractor/webdriver does not support
// sending keys to all known HTML5 input controls
// for various browsers (see https:
//github.com/angular/protractor/issues/562).
Function setInput(val) {
  // set the value of the element and force validation.
  var scr = "var ipt = document.getElementById('exampleInput'); " +
  "ipt.value = '" + val + "';" +
  "angular.element(ipt).scope().$apply(function(s) { s.myForm[ipt.name].$setViewValue('" + val + "'); });";
  browser.executeScript(scr);}

it('should initialize to model', Function() {
  expect(value.getText()).toContain('2013-10-22');
  expect(valid.getText()).toContain('myForm.input.$valid = true');});

it('should be invalid if empty', Function() {
  setInput('');
  expect(value.getText()).toEqual('value =');
  expect(valid.getText()).toContain('myForm.input.$valid = false');});

it('should be invalid if over max', Function() {
  setInput('2015-01-01');
  expect(value.getText()).toContain('');
  expect(valid.getText()).toContain('myForm.input.$valid = false');});


AngularJS: API: ng/directive/input[dateTimeLocal]

input[dateTimeLocal]

  1. - input in module ng

日期时间输入的验证和转换。目前的浏览器还不支持HTML5的日期输入控件,所以将使用文本输入。 在这种情况下，输入的文本必须符合ISO-8601的本地日期时间格式(yyyy-MM-ddTHH:mm)的校验规范，例如：2010-12-28T14:57。 模型必须永远是一个Date对象。

指令信息

  • 这个指令执行优先级为0.

用法

<input Type="dateTimeLocal"
       ng-model=""
       [name=""]
       [min=""]
       [max=""]
       [required=""]
       [ng-required=""]
       [ng-change=""]>

参数

参数 | 类型 | 详述
ngModel | string | 声明用于数据绑定的Angular表达式。
name (可选) | string | 发布到表单下的控件的属性名称。
min (可选) | string | 当输入的值小于min时，设置min 验证错误键。 值必须是符合ISO的日期时间格式(yyyy-MM-ddTHH:mm)。
max (可选) | string | 当输入的值大于max时，设置max验证错误键。值必须是符合ISO的日期时间格式(yyyy-MM-ddTHH:mm)。
required (可选) | string | 如果未输入值就设置 required 验证错误键。
ngRequired (可选) | string | 当ngRequired表达式等于true时，添加required属性和required验证约束到元素上。 使用ngRequired替换required，当你想数据绑定到required属性上时。
ngChange (可选) | string | Angular表达式，当输入元素通过用户交互方式发生输入变化时会执行这个表达式。

示例

index.html
<script>
  angular.module('dateExample', [])
    .controller('DateController', ['$scope', Function($scope) {
      $scope.value = new Date(2010, 11, 28, 14, 57);
    }]);
</script>
<form name="myForm" ng-controller="DateController as dateCtrl">
  Pick a date between in 2013:
  <input Type="datetime-local" id="exampleInput" name="input" ng-model="value"
      placeholder="yyyy-MM-ddTHH:mm" min="2001-01-01T00:00" max="2013-12-31T00:00" required />
  <span class="error" ng-show="myForm.input.$error.required">
      Required!</span>
  <span class="error" ng-show="myForm.input.$error.datetimelocal">
      Not a valid date!</span>
  <tt>value = {{value | date: "yyyy-MM-ddTHH:mm"}}</tt><br/>
  <tt>myForm.input.$valid = {{myForm.input.$valid}}</tt><br/>
  <tt>myForm.input.$error = {{myForm.input.$error}}</tt><br/>
  <tt>myForm.$valid = {{myForm.$valid}}</tt><br/>
  <tt>myForm.$error.required = {{!!myForm.$error.required}}</tt><br/>
</form>
protractor.js
var value = element(by.binding('value | date: "yyyy-MM-ddTHH:mm"'));
var valid = element(by.binding('myForm.input.$valid'));
var input = element(by.model('value'));

// currently protractor/webdriver does not support
// sending keys to all known HTML5 input controls
// for various browsers (https://github.com/angular/protractor/issues/562).
Function setInput(val) {
  // set the value of the element and force validation.
  var scr = "var ipt = document.getElementById('exampleInput'); " +
  "ipt.value = '" + val + "';" +
  "angular.element(ipt).scope().$apply(function(s) { s.myForm[ipt.name].$setViewValue('" + val + "'); });";
  browser.executeScript(scr);}

it('should initialize to model', Function() {
  expect(value.getText()).toContain('2010-12-28T14:57');
  expect(valid.getText()).toContain('myForm.input.$valid = true');});

it('should be invalid if empty', Function() {
  setInput('');
  expect(value.getText()).toEqual('value =');
  expect(valid.getText()).toContain('myForm.input.$valid = false');});

it('should be invalid if over max', Function() {
  setInput('2015-01-01T23:59');
  expect(value.getText()).toContain('');
  expect(valid.getText()).toContain('myForm.input.$valid = false');});


AngularJS: API: ng/directive/input[email]

input[email]

  1. - input in module ng

Email格式的文本输入验证。如果验证结果不是有效的email地址，则设置 email 验证错误键。

指令信息

  • 这个指令执行优先级为0.

用法

<input Type="email"
       ng-model=""
       [name=""]
       [required=""]
       [ng-required=""]
       [ng-minlength=""]
       [ng-maxlength=""]
       [ng-pattern=""]
       [ng-change=""]>

参数

参数 | 类型 | 详述
ngModel | string | 声明用于数据绑定的Angular表达式。
name (可选) | string | 发布到表单下的控件的属性名称。
required (可选) | string | 如果未输入值就设置 required 验证错误键。
ngRequired (可选) | string | 当ngRequired表达式等于true时，添加required属性和required验证约束到元素上。 使用ngRequired替换required，当你想数据绑定到required属性上时。
ngMinlength (可选) | number | 如果值短于minlength则设置 minlength 验证错误键。
ngMaxlength (可选) | number | 如果值长于maxlength则设置 maxlength 验证错误键。
ngPattern (可选) | string | 如果值不匹配正则表达式则设置 pattern 验证错误键。 值可以是 /regexp/ 形式的内嵌正则表达式，或者是用 regexp 定义在scope中的表达式。
ngChange (可选) | string | Angular表达式，当输入元素通过用户交互方式发生输入变化时会执行这个表达式。

示例

index.html
<script>
angular.module('emailExample', [])
  .controller('ExampleController', ['$scope', Function($scope) {
    $scope.text = 'me@example.com';
  }]);
</script>
<form name="myForm" ng-controller="ExampleController">
  Email: <input Type="email" name="input" ng-model="text" required>
  <span class="error" ng-show="myForm.input.$error.required">
    Required!</span>
  <span class="error" ng-show="myForm.input.$error.email">
    Not valid email!</span>
  <tt>text = {{text}}</tt><br/>
  <tt>myForm.input.$valid = {{myForm.input.$valid}}</tt><br/>
  <tt>myForm.input.$error = {{myForm.input.$error}}</tt><br/>
  <tt>myForm.$valid = {{myForm.$valid}}</tt><br/>
  <tt>myForm.$error.required = {{!!myForm.$error.required}}</tt><br/>
  <tt>myForm.$error.email = {{!!myForm.$error.email}}</tt><br/>
</form>
protractor.js
var text = element(by.binding('text'));
var valid = element(by.binding('myForm.input.$valid'));
var input = element(by.model('text'));

it('should initialize to model', Function() {
  expect(text.getText()).toContain('me@example.com');
  expect(valid.getText()).toContain('true');});

it('should be invalid if empty', Function() {
  input.clear();
  input.sendKeys('');
  expect(text.getText()).toEqual('text =');
  expect(valid.getText()).toContain('false');});

it('should be invalid if not email', Function() {
  input.clear();
  input.sendKeys('xxx');

  expect(valid.getText()).toContain('false');});


AngularJS: API: ng/directive/input[month]

input[month]

  1. - input in module ng

月份输入的验证和转换。目前的浏览器还不支持HTML5的日期输入控件,所以将使用文本输入。 在这种情况下，输入的文本必须符合ISO-8601的月份格式(yyyy-MM)的校验规范，例如：2009-01。 模型必须永远是一个Date对象。In the event the model is not set to the first of the month, the first of that model's month is assumed.

指令信息

  • 这个指令执行优先级为0.

用法

<input Type="month"
       ng-model=""
       [name=""]
       [min=""]
       [max=""]
       [required=""]
       [ng-required=""]
       [ng-change=""]>

参数

参数 | 类型 | 详述
ngModel | string | 声明用于数据绑定的Angular表达式。
name (可选) | string | 发布到表单下的控件的属性名称。
min (可选) | string | 当输入的值小于min时，设置min 验证错误键。 This must be a valid ISO month format (yyyy-MM).
max (可选) | string | 当输入的值大于max时，设置max验证错误键。This must be a valid ISO month format (yyyy-MM).
required (可选) | string | 如果未输入值就设置 required 验证错误键。
ngRequired (可选) | string | 当ngRequired表达式等于true时，添加required属性和required验证约束到元素上。 使用ngRequired替换required，当你想数据绑定到required属性上时。
ngChange (可选) | string | Angular表达式，当输入元素通过用户交互方式发生输入变化时会执行这个表达式。

示例

index.html
<script>
 angular.module('monthExample', [])
   .controller('DateController', ['$scope', Function($scope) {
     $scope.value = new Date(2013, 9, 1);
   }]);
</script>
<form name="myForm" ng-controller="DateController as dateCtrl">
  Pick a month int 2013:
  <input id="exampleInput" Type="month" name="input" ng-model="value"
     placeholder="yyyy-MM" min="2013-01" max="2013-12" required />
  <span class="error" ng-show="myForm.input.$error.required">
     Required!</span>
  <span class="error" ng-show="myForm.input.$error.month">
     Not a valid month!</span>
  <tt>value = {{value | date: "yyyy-MM"}}</tt><br/>
  <tt>myForm.input.$valid = {{myForm.input.$valid}}</tt><br/>
  <tt>myForm.input.$error = {{myForm.input.$error}}</tt><br/>
  <tt>myForm.$valid = {{myForm.$valid}}</tt><br/>
  <tt>myForm.$error.required = {{!!myForm.$error.required}}</tt><br/>
</form>
protractor.js
var value = element(by.binding('value | date: "yyyy-MM"'));
var valid = element(by.binding('myForm.input.$valid'));
var input = element(by.model('value'));

// currently protractor/webdriver does not support
// sending keys to all known HTML5 input controls
// for various browsers (https://github.com/angular/protractor/issues/562).
Function setInput(val) {
  // set the value of the element and force validation.
  var scr = "var ipt = document.getElementById('exampleInput'); " +
  "ipt.value = '" + val + "';" +
  "angular.element(ipt).scope().$apply(function(s) { s.myForm[ipt.name].$setViewValue('" + val + "'); });";
  browser.executeScript(scr);}

it('should initialize to model', Function() {
  expect(value.getText()).toContain('2013-10');
  expect(valid.getText()).toContain('myForm.input.$valid = true');});

it('should be invalid if empty', Function() {
  setInput('');
  expect(value.getText()).toEqual('value =');
  expect(valid.getText()).toContain('myForm.input.$valid = false');});

it('should be invalid if over max', Function() {
  setInput('2015-01');
  expect(value.getText()).toContain('');
  expect(valid.getText()).toContain('myForm.input.$valid = false');});


AngularJS: API: ng/directive/input[number]

input[number]

  1. - input in module ng

数字格式的文本输入验证和转换。如果验证结果不是数字，则设置 number验证错误键。

指令信息

  • 这个指令执行优先级为0.

用法

<input Type="number"
       ng-model=""
       [name=""]
       [min=""]
       [max=""]
       [required=""]
       [ng-required=""]
       [ng-minlength=""]
       [ng-maxlength=""]
       [ng-pattern=""]
       [ng-change=""]>

参数

参数 | 类型 | 详述
ngModel | string | 声明用于数据绑定的Angular表达式。
name (可选) | string | 发布到表单下的控件的属性名称。
min (可选) | string | 当输入的值小于min时，设置min 验证错误键。
max (可选) | string | 当输入的值大于max时，设置max验证错误键。
required (可选) | string | 如果未输入值就设置 required 验证错误键。
ngRequired (可选) | string | 当ngRequired表达式等于true时，添加required属性和required验证约束到元素上。 使用ngRequired替换required，当你想数据绑定到required属性上时。
ngMinlength (可选) | number | 如果值短于minlength则设置 minlength 验证错误键。
ngMaxlength (可选) | number | 如果值长于maxlength则设置 maxlength 验证错误键。
ngPattern (可选) | string | 如果值不匹配正则表达式则设置 pattern 验证错误键。 值可以是 /regexp/ 形式的内嵌正则表达式，或者是用 regexp 定义在scope中的表达式。
ngChange (可选) | string | Angular表达式，当输入元素通过用户交互方式发生输入变化时会执行这个表达式。

示例

index.html
<script>
  angular.module('numberExample', [])
    .controller('ExampleController', ['$scope', Function($scope) {
      $scope.value = 12;
    }]);
</script>
<form name="myForm" ng-controller="ExampleController">
  Number: <input Type="number" name="input" ng-model="value"
                 min="0" max="99" required>
  <span class="error" ng-show="myForm.input.$error.required">
    Required!</span>
  <span class="error" ng-show="myForm.input.$error.number">
    Not valid number!</span>
  <tt>value = {{value}}</tt><br/>
  <tt>myForm.input.$valid = {{myForm.input.$valid}}</tt><br/>
  <tt>myForm.input.$error = {{myForm.input.$error}}</tt><br/>
  <tt>myForm.$valid = {{myForm.$valid}}</tt><br/>
  <tt>myForm.$error.required = {{!!myForm.$error.required}}</tt><br/>
 </form>
protractor.js
var value = element(by.binding('value'));
var valid = element(by.binding('myForm.input.$valid'));
var input = element(by.model('value'));

it('should initialize to model', Function() {
  expect(value.getText()).toContain('12');
  expect(valid.getText()).toContain('true');});

it('should be invalid if empty', Function() {
  input.clear();
  input.sendKeys('');
  expect(value.getText()).toEqual('value =');
  expect(valid.getText()).toContain('false');});

it('should be invalid if over max', Function() {
  input.clear();
  input.sendKeys('123');
  expect(value.getText()).toEqual('value =');
  expect(valid.getText()).toContain('false');});


AngularJS: API: ng/directive/input[radio]

input[radio]

  1. - input in module ng

HTML单选框。

指令信息

  • 这个指令执行优先级为0.

用法

<input Type="radio"
       ng-model=""
       value=""
       [name=""]
       [ng-change=""]
       ng-value="">

参数

参数 | 类型 | 详述
ngModel | string | 声明用于数据绑定的Angular表达式。
value | string | 当被选中时，value会被置为表达式的值。
name (可选) | string | 发布到表单下的控件的属性名称。
ngChange (可选) | string | Angular表达式，当输入元素通过用户交互方式发生输入变化时会执行这个表达式。
ngValue | string | 当被选中时，value会被置为表达式的值。

示例

index.html
<script>
  angular.module('radioExample', [])
    .controller('ExampleController', ['$scope', Function($scope) {
      $scope.color = 'blue';
      $scope.specialValue = {
        "id": "12345",
        "value": "green"
      };
    }]);
</script>
<form name="myForm" ng-controller="ExampleController">
  <input Type="radio" ng-model="color" value="red">  Red <br/>
  <input Type="radio" ng-model="color" ng-value="specialValue"> Green <br/>
  <input Type="radio" ng-model="color" value="blue"> Blue <br/>
  <tt>color = {{color | json}}</tt><br/>
</form>
 Note that `ng-value="specialValue"` sets radio item's value to be the value of `$scope.specialValue`.
protractor.js
it('should change state', Function() {
  var color = element(by.binding('color'));

  expect(color.getText()).toContain('blue');

  element.all(by.model('color')).get(0).click();

  expect(color.getText()).toContain('red');});


AngularJS: API: ng/directive/input[text]

input[text]

  1. - input in module ng

可以进行angular数据绑定的标准HTML文本输入框。

指令信息

  • 这个指令执行优先级为0.

用法

<input Type="text"
       ng-model=""
       [name=""]
       [required=""]
       [ng-required=""]
       [ng-minlength=""]
       [ng-maxlength=""]
       [ng-pattern=""]
       [ng-change=""]
       [ng-trim=""]>

参数

参数 | 类型 | 详述
ngModel | string | 声明用于数据绑定的Angular表达式。
name (可选) | string | 发布到表单下的控件的属性名称。
required (可选) | string | 如果值没有输入，则设置required验证错误键。
ngRequired (可选) | string | 当ngRequired表达式等于true时，添加required属性和required验证约束到元素上。 使用ngRequired替换required，当你想数据绑定到required属性上时。
ngMinlength (可选) | number | 如果值短于minlength则设置 minlength 验证错误键。
ngMaxlength (可选) | number | 如果值长于maxlength则设置 maxlength 验证错误键。
ngPattern (可选) | string | 如果值不匹配正则表达式则设置 pattern 验证错误键。 值可以是 /regexp/ 形式的内嵌正则表达式，或者是用 regexp 定义在scope中的表达式。
ngChange (可选) | string | Angular表达式，当输入元素通过用户交互方式发生输入变化时会执行这个表达式。
ngTrim (可选) | boolean | 如果设置为false，Angular将不自动去除输入内容的空格。

示例

index.html
<script>
  angular.module('textInputExample', [])
    .controller('ExampleController', ['$scope', Function($scope) {
      $scope.text = 'guest';
      $scope.word = /^\s*\w*\s*$/;
    }]);
</script>
<form name="myForm" ng-controller="ExampleController">
  Single word: <input Type="text" name="input" ng-model="text"
                      ng-pattern="word" required ng-trim="false">
  <span class="error" ng-show="myForm.input.$error.required">
    Required!</span>
  <span class="error" ng-show="myForm.input.$error.pattern">
    Single word only!</span>

  <tt>text = {{text}}</tt><br/>
  <tt>myForm.input.$valid = {{myForm.input.$valid}}</tt><br/>
  <tt>myForm.input.$error = {{myForm.input.$error}}</tt><br/>
  <tt>myForm.$valid = {{myForm.$valid}}</tt><br/>
  <tt>myForm.$error.required = {{!!myForm.$error.required}}</tt><br/>
 </form>
protractor.js
var text = element(by.binding('text'));var valid = element(by.binding('myForm.input.$valid'));var input = element(by.model('text'));

it('should initialize to model', Function() {
  expect(text.getText()).toContain('guest');
  expect(valid.getText()).toContain('true');});

it('should be invalid if empty', Function() {
  input.clear();
  input.sendKeys('');

  expect(text.getText()).toEqual('text =');
  expect(valid.getText()).toContain('false');});

it('should be invalid if multi word', Function() {
  input.clear();
  input.sendKeys('hello world');

  expect(valid.getText()).toContain('false');});


AngularJS: API: ng/directive/input[time]

input[time]

  1. - input in module ng

时间输入的验证和转换。目前的浏览器还不支持HTML5的日期输入控件,所以将使用文本输入。 在这种情况下，输入的文本必须符合ISO-8601的月份格式(HH:mm)的校验规范，例如：14:57。 模型必须永远是一个Date对象。这个绑定将永远输出一个日期对象到模型，值为1900年1月1日，或者是本地日期 new Date(0, 0, 1, HH, mm)。

指令信息

  • 这个指令执行优先级为0.

用法

<input Type="time"
       ng-model=""
       [name=""]
       [min=""]
       [max=""]
       [required=""]
       [ng-required=""]
       [ng-change=""]>

参数

参数 | 类型 | 详述
ngModel | string | 声明用于数据绑定的Angular表达式。
name (可选) | string | 发布到表单下的控件的属性名称。
min (可选) | string | 当输入的值小于min时，设置min 验证错误键。 值必须符合ISO时间格式(HH:mm)。
max (可选) | string | 当输入的值大于max时，设置max验证错误键。值必须符合ISO时间格式(HH:mm)。
required (可选) | string | 如果未输入值就设置 required 验证错误键。
ngRequired (可选) | string | 当ngRequired表达式等于true时，添加required属性和required验证约束到元素上。 使用ngRequired替换required，当你想数据绑定到required属性上时。
ngChange (可选) | string | Angular表达式，当输入元素通过用户交互方式发生输入变化时会执行这个表达式。

示例

index.html
<script>
 angular.module('timeExample', [])
   .controller('DateController', ['$scope', Function($scope) {
     $scope.value = new Date(0, 0, 1, 14, 57);
   }]);
</script>
<form name="myForm" ng-controller="DateController as dateCtrl">
   Pick a between 8am and 5pm:
   <input Type="time" id="exampleInput" name="input" ng-model="value"
       placeholder="HH:mm" min="08:00" max="17:00" required />
   <span class="error" ng-show="myForm.input.$error.required">
       Required!</span>
   <span class="error" ng-show="myForm.input.$error.time">
       Not a valid date!</span>
   <tt>value = {{value | date: "HH:mm"}}</tt><br/>
   <tt>myForm.input.$valid = {{myForm.input.$valid}}</tt><br/>
   <tt>myForm.input.$error = {{myForm.input.$error}}</tt><br/>
   <tt>myForm.$valid = {{myForm.$valid}}</tt><br/>
   <tt>myForm.$error.required = {{!!myForm.$error.required}}</tt><br/>
</form>
protractor.js
var value = element(by.binding('value | date: "HH:mm"'));
var valid = element(by.binding('myForm.input.$valid'));
var input = element(by.model('value'));

// currently protractor/webdriver does not support
// sending keys to all known HTML5 input controls
// for various browsers (https://github.com/angular/protractor/issues/562).
Function setInput(val) {
  // set the value of the element and force validation.
  var scr = "var ipt = document.getElementById('exampleInput'); " +
  "ipt.value = '" + val + "';" +
  "angular.element(ipt).scope().$apply(function(s) { s.myForm[ipt.name].$setViewValue('" + val + "'); });";
  browser.executeScript(scr);}

it('should initialize to model', Function() {
  expect(value.getText()).toContain('14:57');
  expect(valid.getText()).toContain('myForm.input.$valid = true');});

it('should be invalid if empty', Function() {
  setInput('');
  expect(value.getText()).toEqual('value =');
  expect(valid.getText()).toContain('myForm.input.$valid = false');});

it('should be invalid if over max', Function() {
  setInput('23:59');
  expect(value.getText()).toContain('');
  expect(valid.getText()).toContain('myForm.input.$valid = false');});


AngularJS: API: ng/directive/input[url]

input[url]

  1. - input in module ng

URL文本输入校验。如果内容不是有效的URL，则设置url验证错误键。

指令信息

  • 这个指令执行优先级为0.

用法

<input Type="url"
       ng-model=""
       [name=""]
       [required=""]
       [ng-required=""]
       [ng-minlength=""]
       [ng-maxlength=""]
       [ng-pattern=""]
       [ng-change=""]>

参数

参数 | 类型 | 详述
ngModel | string | 声明用于数据绑定的Angular表达式。
name (可选) | string | 发布到表单下的控件的属性名称。
required (可选) | string | 如果未输入值就设置 required 验证错误键。
ngRequired (可选) | string | 当ngRequired表达式等于true时，添加required属性和required验证约束到元素上。 使用ngRequired替换required，当你想数据绑定到required属性上时。
ngMinlength (可选) | number | 如果值短于minlength则设置 minlength 验证错误键。
ngMaxlength (可选) | number | 如果值长于maxlength则设置 maxlength 验证错误键。
ngPattern (可选) | string | 如果值不匹配正则表达式则设置 pattern 验证错误键。 值可以是 /regexp/ 形式的内嵌正则表达式，或者是用 regexp 定义在scope中的表达式。
ngChange (可选) | string | Angular表达式，当输入元素通过用户交互方式发生输入变化时会执行这个表达式。

示例

index.html
<script>
  angular.module('urlExample', [])
    .controller('ExampleController', ['$scope', Function($scope) {
      $scope.text = 'http://google.com';
    }]);
</script>
<form name="myForm" ng-controller="ExampleController">
  URL: <input Type="url" name="input" ng-model="text" required>
  <span class="error" ng-show="myForm.input.$error.required">
    Required!</span>
  <span class="error" ng-show="myForm.input.$error.url">
    Not valid url!</span>
  <tt>text = {{text}}</tt><br/>
  <tt>myForm.input.$valid = {{myForm.input.$valid}}</tt><br/>
  <tt>myForm.input.$error = {{myForm.input.$error}}</tt><br/>
  <tt>myForm.$valid = {{myForm.$valid}}</tt><br/>
  <tt>myForm.$error.required = {{!!myForm.$error.required}}</tt><br/>
  <tt>myForm.$error.url = {{!!myForm.$error.url}}</tt><br/>
 </form>
protractor.js
var text = element(by.binding('text'));
var valid = element(by.binding('myForm.input.$valid'));
var input = element(by.model('text'));

it('should initialize to model', Function() {
  expect(text.getText()).toContain('http://google.com');
  expect(valid.getText()).toContain('true');});

it('should be invalid if empty', Function() {
  input.clear();
  input.sendKeys('');

  expect(text.getText()).toEqual('text =');
  expect(valid.getText()).toContain('false');});

it('should be invalid if not url', Function() {
  input.clear();
  input.sendKeys('box');

  expect(valid.getText()).toContain('false');});


AngularJS: API: ng/directive/input[week]

input[week]

  1. - input in module ng

年的周数输入的验证和转换到日期。目前的浏览器还不支持HTML5的周输入控件,所以将使用文本输入。 在这种情况下，输入的文本必须符合ISO-8601的日期格式(yyyy-W##)的校验规范，例如：2013-W02。模型必须永远是一个Date对象。

指令信息

  • 这个指令执行优先级为0.

用法

<input Type="week"
       ng-model=""
       [name=""]
       [min=""]
       [max=""]
       [required=""]
       [ng-required=""]
       [ng-change=""]>

参数

参数 | 类型 | 详述
ngModel | string | 声明用于数据绑定的Angular表达式。
name (可选) | string | 发布到表单下的控件的属性名称。
min (可选) | string | 当输入的值小于min时，设置min 验证错误键。 值必须符合ISO周格式(yyyy-W##)。
max (可选) | string | 当输入的值大于max时，设置max验证错误键。值必须符合ISO周格式(yyyy-W##)。
required (可选) | string | 如果未输入值就设置 required 验证错误键。
ngRequired (可选) | string | 当ngRequired表达式等于true时，添加required属性和required验证约束到元素上。 使用ngRequired替换required，当你想数据绑定到required属性上时。
ngChange (可选) | string | Angular表达式，当输入元素通过用户交互方式发生输入变化时会执行这个表达式。

示例

index.html
<script>
angular.module('weekExample', [])
  .controller('DateController', ['$scope', Function($scope) {
    $scope.value = new Date(2013, 0, 3);
  }]);
</script>
<form name="myForm" ng-controller="DateController as dateCtrl">
  Pick a date between in 2013:
  <input id="exampleInput" Type="week" name="input" ng-model="value"
      placeholder="YYYY-W##" min="2012-W32" max="2013-W52" required />
  <span class="error" ng-show="myForm.input.$error.required">
      Required!</span>
  <span class="error" ng-show="myForm.input.$error.week">
      Not a valid date!</span>
  <tt>value = {{value | date: "yyyy-Www"}}</tt><br/>
  <tt>myForm.input.$valid = {{myForm.input.$valid}}</tt><br/>
  <tt>myForm.input.$error = {{myForm.input.$error}}</tt><br/>
  <tt>myForm.$valid = {{myForm.$valid}}</tt><br/>
  <tt>myForm.$error.required = {{!!myForm.$error.required}}</tt><br/>
</form>
protractor.js
var value = element(by.binding('value | date: "yyyy-Www"'));
var valid = element(by.binding('myForm.input.$valid'));
var input = element(by.model('value'));

// currently protractor/webdriver does not support
// sending keys to all known HTML5 input controls
// for various browsers (https://github.com/angular/protractor/issues/562).
Function setInput(val) {
  // set the value of the element and force validation.
  var scr = "var ipt = document.getElementById('exampleInput'); " +
  "ipt.value = '" + val + "';" +
  "angular.element(ipt).scope().$apply(function(s) { s.myForm[ipt.name].$setViewValue('" + val + "'); });";
  browser.executeScript(scr);}

it('should initialize to model', Function() {
  expect(value.getText()).toContain('2013-W01');
  expect(valid.getText()).toContain('myForm.input.$valid = true');});

it('should be invalid if empty', Function() {
  setInput('');
  expect(value.getText()).toEqual('value =');
  expect(valid.getText()).toContain('myForm.input.$valid = false');});

it('should be invalid if over max', Function() {
  setInput('2015-W01');
  expect(value.getText()).toContain('');
  expect(valid.getText()).toContain('myForm.input.$valid = false');});


AngularJS: API: ng/directive/ngApp

ngApp

  1. - directive in module ng

使用这个指令自动载入启动一个AngularJS应用。 ngApp 指令设计为应用的根元素，一般把它放在页面的根元素附近，例如<body>或<html>标签。

每个HTML文档只有一个AngularJS应用能被自动载入启动。文档中找到的第一个ngApp将被用于定义自动载入启动的应用的根元素。要在一个HTML文档中运行多个应用，你必须使用angular.bootstrap来手工启动。AngularJS应用间不能嵌套。

你能指定一个 AngularJS module 作为应用的根模块。当应用被启动后，这个模块将被载入到$injector，并且应包含所需要的应用代码或必须依赖的包含代码的其它模块。 参考 angular.modul获取更多信息。

在下面的例子中，如果 ngApp 指令没被放在 html 元素上，文档将不会被编译， AppController 将不会被实例化，并且 {{ a+b }} 将不会被解析为 3。

使用ngApp 是简单、通用的启动应用的途径。

index.html
<div ng-controller="ngAppDemoController">
I can add: {{a}} + {{b}} =  {{ a+b }}
</div>
script.js
angular.module('ngAppDemo', []).controller('ngAppDemoController', Function($scope) {
$scope.a = 1;
$scope.b = 2;});
使用 ngStrictDi，你会看到这样的效果：

index.html
<div ng-app="ngAppStrictDemo" ng-strict-di>
<div ng-controller="GoodController1">
    I can add: {{a}} + {{b}} =  {{ a+b }}

    <p>This renders because the controller does not fail to
       instantiate, by using explicit annotation style (see
       script.js for details)
    </p>
</div>

<div ng-controller="GoodController2">
    Name: <input ng-model="name"><br />
    Hello, {{name}}!

    <p>This renders because the controller does not fail to
       instantiate, by using explicit annotation style
       (see script.js for details)
    </p>
</div>

<div ng-controller="BadController">
    I can add: {{a}} + {{b}} =  {{ a+b }}

    <p>The controller could not be instantiated, due to relying
       on automatic function annotations (which are disabled in
       strict mode). As such, the content of this section is not
       interpolated, and there should be an error in your web console.
    </p>
</div>
</div>
script.js
angular.module('ngAppStrictDemo', [])
// BadController will fail to instantiate, due to relying on automatic function annotation,
// rather than an explicit annotation
.controller('BadController', Function($scope) {
  $scope.a = 1;
  $scope.b = 2;})
// Unlike BadController, GoodController1 and GoodController2 will not fail to be instantiated,
// due to using explicit annotations using the array style and $inject property, respectively.
.controller('GoodController1', ['$scope', Function($scope) {
  $scope.a = 1;
  $scope.b = 2;}])
.controller('GoodController2', GoodController2);
Function GoodController2($scope) {
  $scope.name= "World";}
GoodController2.$inject = ['$scope'];
style.css
div[ng-controller] {
margin-bottom: 1em;-webkit-border-radius: 4px;
border-radius: 4px;
border: 1px solid;
padding: .5em;}
div[ng-controller^=Good] {
border-color: #d6e9c6;
background-color: #dff0d8;
color: #3c763d;}
div[ng-controller^=Bad] {
border-color: #ebccd1;
background-color: #f2dede;
color: #a94442;
margin-bottom: 0;}

指令信息

  • 这个指令执行优先级为0.

用法

  • 作为属性使用:
    <ANY
  ng-app=""
  [ng-strict-di=""]>
...
</ANY>

参数

参数 | 类型 | 详述
ngApp | angular.Module | 用于载入的可选的应用 module 名称。
ngStrictDi (可选) | boolean | 如果在app元素上设置这个属性， 注入器将使用 "strict-di" 模式创建。意思是，应用将调用函数失败在没有使用明确的函数标注时 (并且因此不适合于JavaScript压缩), 在 依赖注入指南中，一些有用的调试信息将有助于追踪这些错误的根源。


AngularJS: API: ng/directive/ngBind

ngBind

  1. - directive in module ng

ngBind 属性告诉Angular使用所给表达式的值替换指定HTML元素的文本内容，并且在表达式的值改变时更新文本内容。

一般情况下，你不需要使用ngBind指令，可以使用像{{ expression }}形式的双花括号来替换，达到同样的效果并且只需少量命令。

使用 ngBind 替换 {{ expression }} 是更好的方法，在处于Angular编译前的原生状态时的模板被浏览器立即显示时。由于ngBind只是一个元素属性，当页面载入时它创建的绑定对用户是不可见。

这个问题的另一个替代解决方案是使用 ngCloak 指令。

指令信息

  • 这个指令执行优先级为0.

用法

  • 作为属性使用:
    <ANY
  ng-bind="">
...
</ANY>
  • 作为CSS类使用:
    <ANY class="ng-bind: ;"> ... </ANY>

参数

参数 | 类型 | 详述
ngBind | expression | 可求值表达式。

示例

在实时预览文本框输入名称，文本框的下方会立即刷新问候信息。

index.html
<script>
  angular.module('bindExample', [])
    .controller('ExampleController', ['$scope', Function($scope) {
      $scope.name= 'Whirled';
    }]);
</script>
<div ng-controller="ExampleController">
  Enter name: <input Type="text" ng-model="name"><br>
  Hello <span ng-bind="name"></span>!
</div>
protractor.js
it('should check ng-bind', Function() {
  var nameInput = element(by.model('name'));

  expect(element(by.binding('name')).getText()).toBe('Whirled');
  nameInput.clear();
  nameInput.sendKeys('world');
  expect(element(by.binding('name')).getText()).toBe('world');});


AngularJS: API: ng/directive/ngBindHtml

ngBindHtml

  1. - directive in module ng

创建一个绑定，使用安全的方式使当前元素的innerHTML为 expression 的计算结果。默认情况下，innerHTML中的内容会使用 $sanitize 服务进行净化。为使用这个功能，确保 $sanitize 有效，例如，包含 ngSanitize 到你的模块依赖中 (它不在 Angular核心中)。如果你知道值是安全的，你也可以忽略净化。如要这样做，需要通过 $sce.trustAsHtml来绑定一个明确可信的值。 请参见Strict Contextual Escaping (SCE)下的例子。

注意：如果 $sanitize 服务无效，并且绑定的值不是明确可信的，你将得到一个错误（而不会使用它）。

指令信息

  • 这个指令执行优先级为0.

用法

  • 作为属性使用:
    <ANY
  ng-bind-html="">
...
</ANY>

参数

参数 | 类型 | 详述
ngBindHtml | expression | 可求值表达式。

示例

试下这里： 在文本框输入文本并查看问候信息的变化。

index.html
<div ng-controller="ExampleController">
 <p ng-bind-html="myHTML"></p>
</div>
script.js
angular.module('bindHtmlExample', ['ngSanitize'])
  .controller('ExampleController', ['$scope', Function($scope) {
    $scope.myHTML =
       'I am an <code>HTML</code>string with ' +
       '<a href="#">links!</a> and other <em>stuff</em>';
  }]);
protractor.js
it('should check ng-bind-html', Function() {
  expect(element(by.binding('myHTML')).getText()).toBe(
      'I am an HTMLstring with links! and other stuff');});


AngularJS: API: ng/directive/ngBindTemplate

ngBindTemplate

  1. - directive in module ng

ngBindTemplate指令使元素的文本内容会被替换为 ngBindTemplate属性中给出的模板内容。不像 ngBind， ngBindTemplate 可以使用 {{ }} 表达式。这个指令主要用于一些HTML元素 (像TITLE和OPTION)不能包含SPAN元素的状况下。

指令信息

  • 这个指令执行优先级为0.

用法

  • 作为属性使用:
    <ANY
  ng-bind-template="">
...
</ANY>

参数

参数 | 类型 | 详述
ngBindTemplate | string | template of form {{ expression }} to eval.

示例

试下这里：在文本框输入文本并查看问候信息的变化。

index.html
<script>
  angular.module('bindExample', [])
    .controller('ExampleController', ['$scope', Function ($scope) {
      $scope.salutation = 'Hello';
      $scope.name= 'World';
    }]);
</script>
<div ng-controller="ExampleController">
 Salutation: <input Type="text" ng-model="salutation"><br>
 Name: <input Type="text" ng-model="name"><br>
 <pre ng-bind-template="{{salutation}} {{name}}!"></pre>
</div>
protractor.js
it('should check ng-bind', Function() {
  var salutationElem = element(by.binding('salutation'));
  var salutationInput = element(by.model('salutation'));
  var nameInput = element(by.model('name'));

  expect(salutationElem.getText()).toBe('Hello World!');

  salutationInput.clear();
  salutationInput.sendKeys('Greetings');
  nameInput.clear();
  nameInput.sendKeys('user');

  expect(salutationElem.getText()).toBe('Greetings user!');});


AngularJS: API: ng/directive/ngBlur

ngBlur

  1. - directive in module ng

给blur事件添加定制行为。

指令信息

  • 这个指令执行优先级为0.

用法

  • 作为属性使用:
    <window, input, select, textarea, a
  ng-blur="">
...
</window, input, select, textarea, a>

参数

参数 | 类型 | 详述
ngBlur | expression | 在blur触发时执行的表达式 (事件对象存放于 $event)

示例

参见 ngClick


AngularJS: API: ng/directive/ngChange

ngChange

  1. - directive in module ng

当用户改变输入时计算给出的表达式。表达式会被立即计算，不像 JavaScript的onchange事件只会在最后一次改变时触发(通常，当用户离开表单元素或按回车键时)。当值的变化来自于模型时，不会对表达式进行计算。

注意，这个指令需要同时给出 ngModel 。

指令信息

  • 这个指令执行优先级为0.

用法

  • 作为属性使用:
    <input
  ng-change="">
...
</input>

参数

参数 | 类型 | 详述
ngChange | expression | 在输入值改变时执行的表达式。

示例

index.html
<script>
  angular.module('changeExample', [])
    .controller('ExampleController', ['$scope', Function($scope) {
      $scope.counter = 0;
      $scope.change = Function() {
        $scope.counter++;
      };
    }]);
</script>
<div ng-controller="ExampleController">
  <input Type="checkbox" ng-model="confirmed" ng-change="change()" id="ng-change-example1" />
  <input Type="checkbox" ng-model="confirmed" id="ng-change-example2" />
  <label for="ng-change-example2">Confirmed</label><br />
  <tt>debug = {{confirmed}}</tt><br/>
  <tt>counter = {{counter}}</tt><br/>
</div>
protractor.js
var counter = element(by.binding('counter'));
var debug = element(by.binding('confirmed'));

it('should evaluate the expression if changing from view', Function() {
  expect(counter.getText()).toContain('0');

  element(by.id('ng-change-example1')).click();

  expect(counter.getText()).toContain('1');
  expect(debug.getText()).toContain('true');});

it('should not evaluate the expression if changing from model', Function() {
  element(by.id('ng-change-example2')).click();

  expect(counter.getText()).toContain('0');
  expect(debug.getText()).toContain('true');});


AngularJS: API: ng/directive/ngChecked

ngChecked

  1. - directive in module ng

在HTML规范中不要求浏览器必须结出像checked这种布尔型属性的值（例如为true时有值，为false时无值）。如何我们在这种属性上使用Angular表达式，则当值为false时会被浏览器把属性删除。ngChecked指令解决了 checked 属性存在的这个问题。这个指令不会被浏览器删除，并且可以进行数据绑定。

指令信息

  • 这个指令执行优先级为100.

用法

  • 作为属性使用:
    <INPUT
  ng-checked="">
...
</INPUT>

参数

参数 | 类型 | 详述
ngChecked | expression | 如果表达式为真，则在元素上放置"checked"属性。

示例

index.html
Check me to check both: <input type="checkbox" ng-model="master"><br/><input id="checkSlave" type="checkbox" ng-checked="master">
protractor.js
it('should check both checkBoxes', Function() {
  expect(element(by.id('checkSlave')).getAttribute('checked')).toBeFalsy();
  element(by.model('master')).click();
  expect(element(by.id('checkSlave')).getAttribute('checked')).toBeTruthy();});


AngularJS: API: ng/directive/ngClass

ngClass

  1. - directive in module ng

ngClass指令允许你动态设置HTML元素的CSS类，通过绑定到一个包含要添加的所有类的表达式。

这个指令有三种使用方式，这三种方式取决于表达式计算结果：

  1. 如果表达式结果为字符串，则字符串为使用空格分隔的一个或多个类名。

  2. 如果表达式结果为一个数组，则数组中每个元素为使用空格分隔的一个或多个类名字符串。

  3. 如果表达式结果为一个对象，对象中的每个key-value中如果键值为真时则键名作为类名。

这个指令不会添加重复的类，如果这个类已经存在的话。

当表达式改变时，以前添加的类会被移除，并且只会添加之后新产生的类。

指令信息

  • 这个指令执行优先级为0.

用法

  • 作为属性使用:
    <ANY
  ng-class="">
...
</ANY>
  • 作为CSS类使用:
    <ANY class="ng-class: ;"> ... </ANY>

动画

add - 在类被应用到元素前发生

remove - 在类从元素移除前发生

点击这里 了解更多关于涉及动画的步骤。

参数

参数 | 类型 | 详述
ngClass | expression | 用于计算的表达式。 计算结果可以为使用空格分隔的类名字符串、数组，或布尔值的类名映射(map)表。如果是映射表，那些值为真的属性名称将作为css类添加到元素上。

示例

下面演示使用ngClass指令的一些基本绑定用法。

index.html
<p ng-class="{strike: deleted, bold: important, red: error}">Map Syntax Example</p>
<input Type="checkbox" ng-model="deleted"> deleted (apply "strike" class)<br>
<input Type="checkbox" ng-model="important"> important (apply "bold" class)<br>
<input Type="checkbox" ng-model="error"> error (apply "red" class)<hr>
<p ng-class="style">Using String Syntax</p>
<input Type="text" ng-model="style" placeholder="Type: bold strike red"><hr>
<p ng-class="[style1, style2, style3]">Using Array Syntax</p>
<input ng-model="style1" placeholder="Type: bold, strike or red"><br>
<input ng-model="style2" placeholder="Type: bold, strike or red"><br>
<input ng-model="style3" placeholder="Type: bold, strike or red"><br>
style.css
.strike {
  text-decoration: line-through;}.bold {
    font-weight: bold;}.red {
    color: red;}
protractor.js
var ps = element.all(by.css('p'));

it('should let you toggle the class', Function() {

  expect(ps.first().getAttribute('class')).not.toMatch(/bold/);
  expect(ps.first().getAttribute('class')).not.toMatch(/red/);

  element(by.model('important')).click();
  expect(ps.first().getAttribute('class')).toMatch(/bold/);

  element(by.model('error')).click();
  expect(ps.first().getAttribute('class')).toMatch(/red/);});

it('should let you toggle string example', Function() {
  expect(ps.get(1).getAttribute('class')).toBe('');
  element(by.model('style')).clear();
  element(by.model('style')).sendKeys('red');
  expect(ps.get(1).getAttribute('class')).toBe('red');});

it('array example should have 3 classes', Function() {
  expect(ps.last().getAttribute('class')).toBe('');
  element(by.model('style1')).sendKeys('bold');
  element(by.model('style2')).sendKeys('strike');
  element(by.model('style3')).sendKeys('red');
  expect(ps.last().getAttribute('class')).toBe('bold strike red');});

动画

下面的例子演示使用ngClass来操作动画。

index.html
<input id="setbtn" Type="button" value="set" ng-click="myVar='my-class'">
<input id="clearbtn" Type="button" value="clear" ng-click="myVar=''"><br>
<span class="base-class" ng-class="myVar">Sample Text</span>
style.css
.base-class {
  -webkit-transition:all cubic-bezier(0.250, 0.460, 0.450, 0.940) 0.5s;
  transition:all cubic-bezier(0.250, 0.460, 0.450, 0.940) 0.5s;}

.base-class.my-class {
  color: red;
  font-size:3em;}
protractor.js
it('should check ng-class', Function() {
  expect(element(by.css('.base-class')).getAttribute('class')).not.
    toMatch(/my-class/);

  element(by.id('setbtn')).click();

  expect(element(by.css('.base-class')).getAttribute('class')).
    toMatch(/my-class/);

  element(by.id('clearbtn')).click();

  expect(element(by.css('.base-class')).getAttribute('class')).not.
    toMatch(/my-class/);});

ngClass 和 已经存在的 CSS3 Transitions/Animations

ngClass指令仍然支持CSS3 Transitions/Animations 事件上，如果它们不遵从ngAnimate CSS 命名结构的话。在动画阶段，ngAnimate将用于辅助CSS类来跟踪动画的开始和结束。但这并不妨碍任何元素上已经存在的CSS转换。要想了解基于类的动画过程中发生了什么，可参见 $animate.addClass 和 $animate.removeClass。


AngularJS: API: ng/directive/ngClassEven

ngClassEven

  1. - directive in module ng

ngClassOdd 和 ngClassEven 指令工作方法类似 ngClass, 只是它们只能配合 ngRepeat 进行工作来改变奇数（偶数）行的效果。

指令只在ngRepeat的域内有效。

指令信息

  • 指令执行优先级为0。

用法

  • 作为属性使用:
    <ANY
  ng-class-even="">
...
</ANY>
  • 作为CSS类使用:
    <ANY class="ng-class-even: ;"> ... </ANY>

参数

参数 | 类型 | 详述
ngClassEven | expression | 可求值表达式。表达式返回结果必须为空格分隔的CSS类名字符串或数组。

示例

index.html
<ol ng-init="names=['John', 'Mary', 'Cate', 'Suz']">
  <li ng-repeat="name in names">
   <span ng-class-odd="'odd'" ng-class-even="'even'">
     {{name}}
   </span>
  </li>
</ol>
style.css
.odd {
  color: red;
}
.even {
  color: blue;
}
protractor.js
it('should check ng-class-odd and ng-class-even', Function() {
  expect(element(by.repeater('name in names').row(0).column('name')).getAttribute('class')).
    toMatch(/odd/);
  expect(element(by.repeater('name in names').row(1).column('name')).getAttribute('class')).
    toMatch(/even/);});


AngularJS: API: ng/directive/ngClassOdd

ngClassOdd

  1. - directive in module ng

ngClassOdd 和 ngClassEven 指令工作方法类似 ngClass, 只是它们只能配合 ngRepeat 进行工作来改变奇数（偶数）行的效果。

指令只在ngRepeat的域内有效。

指令信息

  • 指令执行优先级为0。

用法

  • 作为属性使用:
  • <ANY
  ng-class-odd="">
...
</ANY>
  • 作为CSS类使用:
    <ANY class="ng-class-odd: ;"> ... </ANY>

参数

参数 | 类型 | 详述
ngClassOdd | expression | 可求值表达式。表达式返回结果必须为空格分隔的CSS类名字符串或数组。

示例

index.html
<ol ng-init="names=['John', 'Mary', 'Cate', 'Suz']">
  <li ng-repeat="name in names">
   <span ng-class-odd="'odd'" ng-class-even="'even'">
     {{name}}
   </span>
  </li>
</ol>
style.css
.odd {
  color: red;
}
.even {
  color: blue;
}
protractor.js
it('should check ng-class-odd and ng-class-even', Function() {
  expect(element(by.repeater('name in names').row(0).column('name')).getAttribute('class')).
    toMatch(/odd/);
  expect(element(by.repeater('name in names').row(1).column('name')).getAttribute('class')).
    toMatch(/even/);});


AngularJS: API: ng/directive/ngClick

ngClick

  1. - directive in module ng

ngClick指令允许你为元素的点击时指定一个自定义动作。

指令信息

  • 这个指令执行优先级为0.

用法

  • 作为属性使用:
    <ANY
  ng-click="">
...
</ANY>

参数

参数 | 类型 | 详述
ngClick | expression | 在click触发时执行的表达式。 (事件对象存放于$event)

示例

index.html
<button ng-click="count = count + 1" ng-init="count=0">
  Increment
</button>
count: {{count}}
protractor.js
it('should check ng-click', Function() {
  expect(element(by.binding('count')).getText()).toMatch('0');
  element(by.css('button')).click();
  expect(element(by.binding('count')).getText()).toMatch('1');});


AngularJS: API: ng/directive/ngCloak

ngCloak

  1. - directive in module ng

该ngCloak 指令是用来防止应用程序加载时Angular HTML模板的原始形式（未编译的）被浏览器显示为简要形式。使用这个指令，避免由HTML模板显示造成不舒服的闪烁效果。

这个指令能被应用到 <body> 元素上，但推荐的用法是将多个ngCloak 指令应用到页面的一小部分来允许浏览器视图渐进式渲染。

ngCloak的使用要配合angular.js和 angular.min.js内嵌的css规则。对于CSP模式，请添加 angular-csp.css到你的html文件(参见ngCsp)。

[ng\:cloak], [ng-cloak], [data-ng-cloak], [x-ng-cloak], .ng-cloak, .x-ng-cloak {
  display: none !important;}

当这个CSS规则被浏览器加载时，所有的HTML元素（包括孩子）的ngCloak 指令对应的标签是隐藏的。当Angular在模板编译时遇到这个指令，它删除ngCloak元素属性，使编译后的元素可见。

为获得最佳效果， angular.js脚本必须在HTML文档的头部加载；另外，上面的CSS规则必须包含在应用程序的外部样式表中。

传统的浏览器，如IE7，不提供属性选择支持（CSS2.1才支持），所以他们不能匹配[ng\:cloak] 选择器。为了绕过这个限制，除ngCloak指令之外，你必须添加CSS类 ng-cloak，如下面的例子所示。

指令信息

  • 这个指令执行优先级为0.

用法

  • 作为属性使用:
    <ANY>
...
</ANY>
  • 作为CSS类使用:
    <ANY class=""> ... </ANY>

示例

index.html
<div id="template1" ng-cloak>{{ 'hello' }}</div>
<div id="template2" ng-cloak class="ng-cloak">{{ 'hello IE7' }}</div>
protractor.js
it('should remove the template directive and css class', Function() {
  expect($('#template1').getAttribute('ng-cloak')).
    toBeNull();
  expect($('#template2').getAttribute('ng-cloak')).
    toBeNull();});


AngularJS: API: ng/directive/ngController

ngController

  1. - directive in module ng

ngController指令给视图添加一个控制器。这是angular支持基于“视图-模型-控制器”设计模式原则的主要方面。

Angular中的MVC组件有：

  • 模型 — 模型是一个域的属性集合；域被附加到DOM上，通过绑定来存取域属性。
  • 视图 — 模板(进行数据绑定的HTML)会被呈现到视图中。
  • 控制器 — ngController指令声明一个控制器类；该类包含了业务逻辑，在应用后台使用函数和值来操控域中的属性。

注意，你也能使用$route服务定义一个路由来将控制器附加到DOM上。一个常见错误是在模板上再次使用ng-controller定义一个控制器。这将引起控制器被附加和执行两次。

指令信息

  • 这个指令会创建新的作用域(scope)。
  • 这个指令执行优先级为0.

用法

  • 作为属性使用:
    <ANY
  ng-controller="">
...
</ANY>

参数

参数 | 类型 | 详述
ngController | expression | 一个全局构造函数，或是当前域的一个表达式，执行后得到一个构造函数。控制器实例能够发布到域属性上，通过as propertyName指定一个属性名。

示例

这是一个编辑用户联系信息的简单表单。添加、删除、清除和欢迎方法定义在控制器中。这些方法能很方便的从angular标记被调用。任何数据的改变都会自动反应到视图，而不需要手动更新。

下面是两种不同的定义风格：

  • 直接在控制器上使用 this来绑定方面和属性: ng-controller="SettingsController1 as settings"
  • 在控制器里注入$scope: ng-controller="SettingsController2"

第二个形式在 Angular社区中是最常使用的方法，它常用在示例和本指南中。然而，直接绑定属性到控制器也有它们的优势和适用范围。

  • 使用controller as 能够明确在模板中使用哪一个控制器来存取，当您有多个控制器适用于一个元素时。
  • 如果你正在作为类来写你的控制器，你可以更轻松地访问属性与方法，控制器代码内不用关心是否会应用在域上。
  • 因为绑定时总是有一个 . ，你不必担心原型继承覆盖本体。

下面的例子演示使用 controller as 的语法。

index.html
<div id="ctrl-as-exmpl" ng-controller="SettingsController1 as settings">
  Name: <input Type="text" ng-model="settings.name"/>
  [ <a href="" ng-click="settings.greet()">greet</a> ]<br/>
  Contact:
  <ul>
    <li ng-repeat="contact in settings.contacts">
      <select ng-model="contact.type">
         <option>phone</option>
         <option>email</option>
      </select>
      <input Type="text" ng-model="contact.value"/>
      [ <a href="" ng-click="settings.clearContact(contact)">clear</a>
      | <a href="" ng-click="settings.removeContact(contact)">X</a> ]
    </li>
    <li>[ <a href="" ng-click="settings.addContact()">add</a> ]</li>
 </ul>
</div>
app.js
angular.module('controllerAsExample', [])
  .controller('SettingsController1', SettingsController1);

Function SettingsController1() {
  this.名称= "John Smith";
  this.contacts = [
    {Type: 'phone', value: '408 555 1212'},
    {Type: 'email', value: 'john.smith@example.org'} ];}

SettingsController1.prototype.greet = Function() {
  alert(this.名称);};

SettingsController1.prototype.addContact = Function() {
  this.contacts.push({Type: 'email', value: 'yourname@example.org'});};

SettingsController1.prototype.removeContact = Function(contactToRemove) {
 var index = this.contacts.indexOf(contactToRemove);
  this.contacts.splice(index, 1);};

SettingsController1.prototype.clearContact = Function(contact) {
  contact.Type= 'phone';
  contact.value = '';};
protractor.js
it('should check controller as', Function() {
  var container = element(by.id('ctrl-as-exmpl'));
    expect(container.element(by.model('settings.name'))
      .getAttribute('value')).toBe('John Smith');

  var firstRepeat =
      container.element(by.repeater('contact in settings.contacts').row(0));
  var secondRepeat =
      container.element(by.repeater('contact in settings.contacts').row(1));

  expect(firstRepeat.element(by.model('contact.value')).getAttribute('value'))
      .toBe('408 555 1212');

  expect(secondRepeat.element(by.model('contact.value')).getAttribute('value'))
      .toBe('john.smith@example.org');

  firstRepeat.element(by.linkText('clear')).click();

  expect(firstRepeat.element(by.model('contact.value')).getAttribute('value'))
      .toBe('');

  container.element(by.linkText('add')).click();

  expect(container.element(by.repeater('contact in settings.contacts').row(2))
      .element(by.model('contact.value'))
      .getAttribute('value'))
      .toBe('yourname@example.org');});
下面的例子演示“注入$scope”到控制器的方式：

index.html
<div id="ctrl-exmpl" ng-controller="SettingsController2">
  Name: <input Type="text" ng-model="name"/>
  [ <a href="" ng-click="greet()">greet</a> ]<br/>
  Contact:
  <ul>
    <li ng-repeat="contact in contacts">
      <select ng-model="contact.type">
         <option>phone</option>
         <option>email</option>
      </select>
      <input Type="text" ng-model="contact.value"/>
      [ <a href="" ng-click="clearContact(contact)">clear</a>
      | <a href="" ng-click="removeContact(contact)">X</a> ]
    </li>
    <li>[ <a href="" ng-click="addContact()">add</a> ]</li>
 </ul>
</div>
app.js
angular.module('controllerExample', [])
  .controller('SettingsController2', ['$scope', SettingsController2]);

Function SettingsController2($scope) {
  $scope.name= "John Smith";
  $scope.contacts = [
    {Type:'phone', value:'408 555 1212'},
    {Type:'email', value:'john.smith@example.org'} ];

  $scope.greet = Function() {
    alert($scope.name);
  };

  $scope.addContact = Function() {
    $scope.contacts.push({Type:'email', value:'yourname@example.org'});
  };

  $scope.removeContact = Function(contactToRemove) {
    var index = $scope.contacts.indexOf(contactToRemove);
    $scope.contacts.splice(index, 1);
  };

  $scope.clearContact = Function(contact) {
    contact.Type= 'phone';
    contact.value = '';
  };}
protractor.js
it('should check controller', Function() {
  var container = element(by.id('ctrl-exmpl'));

  expect(container.element(by.model('name'))
      .getAttribute('value')).toBe('John Smith');

  var firstRepeat =
      container.element(by.repeater('contact in contacts').row(0));
  var secondRepeat =
      container.element(by.repeater('contact in contacts').row(1));

  expect(firstRepeat.element(by.model('contact.value')).getAttribute('value'))
      .toBe('408 555 1212');
  expect(secondRepeat.element(by.model('contact.value')).getAttribute('value'))
      .toBe('john.smith@example.org');

  firstRepeat.element(by.linkText('clear')).click();

  expect(firstRepeat.element(by.model('contact.value')).getAttribute('value'))
      .toBe('');

  container.element(by.linkText('add')).click();

  expect(container.element(by.repeater('contact in contacts').row(2))
      .element(by.model('contact.value'))
      .getAttribute('value'))
      .toBe('yourname@example.org');});


AngularJS: API: ng/directive/ngCopy

ngCopy

  1. - directive in module ng

在复制事件上指定自定义行为。

指令信息

  • 这个指令执行优先级为0.

用法

  • 作为属性使用:
    <window, input, select, textarea, a
  ng-copy="">
...
</window, input, select, textarea, a>

参数

参数 | 类型 | 详述
ngCopy | expression | 在复制触发时执行的表达式 。 (事件对象存放于$event)

示例

index.html
<input ng-copy="copied=true" ng-init="copied=false; value='copy me'" ng-model="value">
copied: {{copied}}


AngularJS: API: ng/directive/ngCsp

ngCsp

  1. - directive in module ng

激活CSP (Content Security Policy，上下文安全策略) 支持。

这是开发像Google Chrome Extensions等东西时所必须的。

CSP禁止应用使用 eval 或 Function(string) 生成的函数 (以及其它东西)。让 Angular兼容CSP我们只要做两件不同的事：

  • 不要使用Function构造来生成优化的值获取(value getters)
  • 不要注入定制的样式表到文档

AngularJS 使用 Function(string) 生成函数来优化速度。使用 ngCsp 指令会引起Angular使用CSP兼容模式。 当AngularJS处于这个模式时，计算所有表达式的速度会比非CSP模式慢30%，但是不会发生安全违规行为。

CSP禁止JavaScript内联样式表规则。在非CSP模式，Angular自动包含一些CSS规则(例如ngCloak)。为了使这些指令能在CSP模式下工作，请手工包含angular-csp.css。

Angular尝试自动检测CSP是否激活来自动打开CSP安全模式。这个自动检测会引发一个CSP错误并输出到控制台：

Refused to evaluate a string as JavaScript because 'unsafe-eval' is not an allowed source of
script in the following Content Security Policy directive: "default-src 'self'". Note that
'script-src' was not explicitly set, so 'default-src' is used as a fallback.

这个错误是无害的，但很讨厌。为了防止错误显示，放置ngCsp指令到应用的根元素上，或放在angular.js 脚本标签中，不管哪种方式，必须是在html文档中最先出现。

注意：这个指令只会在ng-csp 和 data-ng-csp 属性表单中生效。

指令信息

  • 这个指令执行优先级为0.

用法

  • 作为属性使用:
    <html>
...
</html>

示例

这个例子演示如何放置 ngCsp指令到 html标签上。

     <!doctype html>
     <html ng-app ng-csp>
     ...
     ...
     </html>


AngularJS: API: ng/directive/ngCut

ngCut

  1. - directive in module ng

为剪切事件指定自定义行为。

指令信息

  • 这个指令执行优先级为0.

用法

  • 作为属性使用:
    <window, input, select, textarea, a
  ng-cut="">
...
</window, input, select, textarea, a>

参数

参数 | 类型 | 详述
ngCut | expression | 在cut触发时执行的表达式 (事件对象存放于$event)。

示例

index.html
<input ng-cut="cut=true" ng-init="cut=false; value='cut me'" ng-model="value">
cut: {{cut}}


AngularJS: API: ng/directive/ngDblclick

ngDblclick

  1. - directive in module ng

使用ngDblclick指令为双击(dblclick)事件指定一个自定义行为。

指令信息

  • 这个指令执行优先级为0.

用法

  • 作为属性使用:
    <ANY
  ng-dblclick="">
...
</ANY>

参数

参数 | 类型 | 详述
ngDblclick | expression | 在dblclick触发时执行的表达式。 (事件对象存放于$event)

示例

index.html
<button ng-dblclick="count = count + 1" ng-init="count=0">
  Increment (on double click)
</button>
count: {{count}}


AngularJS: API: ng/directive/ngDisabled

ngDisabled

  1. - directive in module ng

下面的标记会让按钮在Chrome/Firefox下有效，但是在IE8及以前的版本除外：

<div ng-init="scope = { isDisabled: false }">
 <button disabled="{{scope.isDisabled}}">Disabled</button></div>

HTML规范不要求浏览器对布尔型属性必须给出值，例如disabled (它们存在表示true，不存在表示false)。如果我们放置了一个Angular动态表达式到这样的属性上，在浏览器删除属性时绑定信息将会丢失。 ngDisabled指令解决了 disabled属性存在的这个问题。这个指令不会被浏览器删除，并提供了一个永久的可靠的地方存放绑定信息。

指令信息

  • 这个指令执行优先级为100.

用法

  • 作为属性使用:
    <INPUT
  ng-disabled="">
...
</INPUT>

参数

参数 | 类型 | 详述
ngDisabled | expression | 如果表达式为真， 指定的属性“disabled”会被设到元素上。

示例

index.html
Click me to toggle: <input type="checkbox" ng-model="checked"><br/>
<button ng-model="button" ng-disabled="checked">Button</button>
protractor.js
it('should toggle button', Function() {
  expect(element(by.css('button')).getAttribute('disabled')).toBeFalsy();
  element(by.model('checked')).click();
  expect(element(by.css('button')).getAttribute('disabled')).toBeTruthy();});


AngularJS: API: ng/directive/ngFocus

ngFocus

  1. - directive in module ng

指定自定义行为到focus事件上。

指令信息

  • 这个指令执行优先级为0.

用法

  • 作为属性使用:
    <window, input, select, textarea, a
  ng-focus="">
...
</window, input, select, textarea, a>

参数

参数 | 类型 | 详述
ngFocus | expression | 在focus触发时执行的表达式 (事件对象存放于$event)

示例

参见 ngClick


AngularJS: API: ng/directive/ngForm

ngForm

  1. - directive in module ng

可嵌套的form指令别名。HTML不允许form元素嵌套。嵌套表单很有用，例如需要对小组内的控件有效性进行检测。

注意：ngForm的目的是用于分组控件，并不能替代<form>标签的所有功能 (例如，提交数据到服务器，...)。

指令信息

  • 这个指令执行优先级为0.

用法

  • 作为元素使用: (这个指令能用于自定义元素，但要注意IE限制)。
    <ng-form
  [name=""]>
...
</ng-form>
  • 作为属性使用:
    <ANY
  [ng-form=""]>
...
</ANY>
  • 作为CSS类使用:
    <ANY class="[ng-form: ;]"> ... </ANY>

参数

参数 | 类型 | 详述
ngForm | name (可选) | string | 表单名称。如果存在，表单控制器会使用这个名称发布到相关的域中。


AngularJS: API: ng/directive/ngHide

ngHide

  1. - directive in module ng

ngHide指令根据ngHide属性上表达式来显示或隐藏给定的HTML元素。元素的显示或隐藏是通过删除或添加ng-hide CSS 类到元素上来实现的。.ng-hide CSS 类是在AngularJS预定义的，并且设置显示样式为空(使用!important标记)。 对于CSP 模式请添加 angular-csp.css 到你的html文件(参见ngCsp)。

<!-- when $scope.myValue is truthy (element is hidden) -->
<div ng-hide="myValue" class="ng-hide"></div>

<!-- when $scope.myValue is falsy (element is visible) -->
<div ng-hide="myValue"></div>

当ngHide表达式计算结果为真时，ng-hide CSS 类会被加到元素的class属性中，从而让它变为隐藏。当为假时，ng-hide CSS 类会从元素移除，这样元素就不会被隐藏。

为什么使用!important?

你可能想知道为什么要在ng-hide CSS类上使用!important。这是因为 .ng-hide选择器很容易被级别更高的选择器覆盖。例如，一些简单的改变HTML列表条目的显示样式会让隐藏的元素显示。这成为了处理CSS框架时最大的问题。

通过使用!important，显示和隐藏行为会按预期工作，而不管CSS选择器间的任何冲突(当!important没用在任何相矛盾的样式上时)。如果开发者决定覆盖样式来改变如何隐藏元素，那只需要在自己的CSS代码中配合使!important即可。

覆盖 .ng-hide

默认情况下，.ng-hide类使用display:none!important格式化元素。如果你希望改变ngShow/ngHide的隐藏行为，可通过在CSS中重新定义.ng-hide类来实现：

.ng-hide {
  /* this is just another form of hiding an element */
  display:block!important;
  position:absolute;
  top:-9999px;
  left:-9999px;}

默认情况下你不需要覆盖CSS中任何东西，动画就会针对显示样式生效。

关于ngHide动画的一个注意点

ngShow/ngHide中动画的显示和隐藏事件会在指令表达式为真或假时触发。 这个系统工作方式像ngClass的动画系统。除了.ng-hide CSS 类的添加、删除可以用你自己替换的CSS类。

////a working example can be found at the bottom of this page
//.my-element.ng-hide-add, .my-element.ng-hide-remove {transition:0.5s linear all;}

.my-element.ng-hide-add { ... }
.my-element.ng-hide-add.ng-hide-add-active { ... }
.my-element.ng-hide-remove { ... }
.my-element.ng-hide-remove.ng-hide-remove-active { ... }

记住，AngularJS的1.3.0-beta.11版本里， 不需要通过阻塞动画过程来改变显示属性，ngAnimate会为你自动处理样式的切换。

指令信息

  • 这个指令执行优先级为0.

用法

  • 作为属性使用:
    <ANY
  ng-hide="">
...
</ANY>

动画

removeClass: .ng-hide - 在ngHide表达式计算结果为真时生效，并且是在内容被隐藏前。

addClass: .ng-hide - 在ngHide表达式计算结果为非真时生效，并且是在内容被显示前。

点击这里 了解更多关于涉及动画的步骤。

参数

参数 | 类型 | 详述
ngHide | expression | 如果表达式为真则隐藏元素，否则显示。

示例

index.html
Click me: <input type="checkbox" ng-model="checked"><br/><div>
  Show:
  <div class="check-element animate-hide" ng-show="checked">
    <span class="glyphicon glyphicon-thumbs-up"></span> I show up when your checkbox is checked.
  </div>
</div><div>
  Hide:
  <div class="check-element animate-hide" ng-hide="checked">
    <span class="glyphicon glyphicon-thumbs-down"></span> I hide when your checkbox is checked.
  </div>
</div>
glyphicons.css
@import url(//netdna.bootstrapcdn.com/bootstrap/3.0.0/css/bootstrap-glyphicons.css);
animations.css
.animate-hide {
  -webkit-transition:all linear 0.5s;
  transition:all linear 0.5s;
  line-height:20px;
  opacity:1;
  padding:10px;
  border:1px solid black;
  background:white;}

.animate-hide.ng-hide {
  line-height:0;
  opacity:0;
  padding:0 10px;}

.check-element {
  padding:10px;
  border:1px solid black;
  background:white;}
protractor.js
var thumbsUp = element(by.css('span.glyphicon-thumbs-up'));var thumbsDown = element(by.css('span.glyphicon-thumbs-down'));

it('should check ng-show / ng-hide', Function() {
  expect(thumbsUp.isDisplayed()).toBeFalsy();
  expect(thumbsDown.isDisplayed()).toBeTruthy();

  element(by.model('checked')).click();

  expect(thumbsUp.isDisplayed()).toBeTruthy();
  expect(thumbsDown.isDisplayed()).toBeFalsy();});


AngularJS: API: ng/directive/ngHref

ngHref

  1. - directive in module ng

在href属性使用Angular的{{hash}}等标记会使链接跳转到错误的URL，当用户在Angular用值替换 {{hash}}标记前点击了它。在Angular替换标记前链接都是错误的，会返回类似404错误。

ngHref指令解决了这个问题。

错误的写法：

<a href="http://www.gravatar.com/avatar/{{hash}}"/>

正确的写法：

<a ng-href="http://www.gravatar.com/avatar/{{hash}}"/>

指令信息

  • 这个指令执行优先级为99.

用法

  • 作为属性使用:
    <A
  ng-href="">
...
</A>

参数

参数 | 类型 | 详述
ngHref | template | 可以包含 {{}} 标记的任意字符串。

示例

这个例子演示几种在链接中使用 href、ng-href和ng-click 属性的组合，以及它们不同的行为：

index.html
<input ng-model="value" /><br />
<a id="link-1" href ng-click="value = 1">link 1</a> (link, don't reload)<br />
<a id="link-2" href="" ng-click="value = 2">link 2</a> (link, don't reload)<br />
<a id="link-3" ng-href="/{{'123'}}">link 3</a> (link, reload!)<br />
<a id="link-4" href="" name="xx" ng-click="value = 4">anchor</a> (link, don't reload)<br />
<a id="link-5" name="xxx" ng-click="value = 5">anchor</a> (no link)<br />
<a id="link-6" ng-href="{{value}}">link</a> (link, change location)
protractor.js
it('should execute ng-click but not reload when href without value', Function() {
  element(by.id('link-1')).click();
  expect(element(by.model('value')).getAttribute('value')).toEqual('1');
  expect(element(by.id('link-1')).getAttribute('href')).toBe('');});

it('should execute ng-click but not reload when href empty string', Function() {
  element(by.id('link-2')).click();
  expect(element(by.model('value')).getAttribute('value')).toEqual('2');
  expect(element(by.id('link-2')).getAttribute('href')).toBe('');});

it('should execute ng-click and change url when ng-href specified', Function() {
  expect(element(by.id('link-3')).getAttribute('href')).toMatch(/\/123$/);

  element(by.id('link-3')).click();

  // At this point, we navigate away from an Angular page, so we need
  // to use browser.driver to get the base webdriver.

  browser.wait(Function() {
    return browser.driver.getCurrentUrl().then(Function(url) {
      return url.match(/\/123$/);
    });
  }, 5000, 'page should navigate to /123');});

xit('should execute ng-click but not reload when href empty string and name specified', Function() {
  element(by.id('link-4')).click();
  expect(element(by.model('value')).getAttribute('value')).toEqual('4');
  expect(element(by.id('link-4')).getAttribute('href')).toBe('');});

it('should execute ng-click but not reload when no href but name specified', Function() {
  element(by.id('link-5')).click();
  expect(element(by.model('value')).getAttribute('value')).toEqual('5');
  expect(element(by.id('link-5')).getAttribute('href')).toBe(null);});

it('should only change url when only ng-href', Function() {
  element(by.model('value')).clear();
  element(by.model('value')).sendKeys('6');
  expect(element(by.id('link-6')).getAttribute('href')).toMatch(/\/6$/);

  element(by.id('link-6')).click();

  // At this point, we navigate away from an Angular page, so we need
  // to use browser.driver to get the base webdriver.
  browser.wait(Function() {
    return browser.driver.getCurrentUrl().then(Function(url) {
      return url.match(/\/6$/);
    });
  }, 5000, 'page should navigate to /6');});


AngularJS: API: ng/directive/ngIf

ngIf

  1. - directive in module ng

ngIf指令基于{表达式}来移除或重建DOM树的一部分。如果赋给 ngIf的表达式计算结果为假，元素会从DOM移除，其它情况会复制一份元素插入到DOM中。

ngIf 不同于 ngShow 和 ngHide ， ngIf 是在DOM中完全移除或重建元素，而不是通过 display css 属性改变可见。一种常见的情况是，这种差异表现在依靠一个元素在DOM的位置使用CSS选择器时，例如 :first-child 或 :last-child 伪类。

注意，当一个元素使用 ngIf 移除时，它的域会被销毁，并且当它恢复时一个新域会被创建。使用 ngIf 创建的域通过 原型继承继承它的父域。这个的重要含义是，如果在 ngIf 中使用ngModel会绑定到一个父域的javascript原始定义。这种情况下任何修改都会使子域的变化覆盖父域的值。

同时， ngIf使用自己编译状态来重建元素。 这种行为的一个例子是，如果一个元素的class属性在它编译后被直接修改，使用像 jQuery's .addClass() 方法等，并且元素之后被删掉。当ngIf 重建元素，class属性中已添加的类会丢失，因为会使用原始编译状态来重生成元素。

此外， 你可以通过 ngAnimate 模块来执行动画，控制 enter 和 leave 的效果。

指令信息

  • 这个指令会创建新的作用域(scope)。
  • 这个指令执行优先级为600.

用法

  • 作为属性使用:
    <ANY
  ng-if="">
...
</ANY>

动画

enter - 在ngIf内容改变时发生，并且一个新DOM元素会被创建和加入到ngIf容器中。

leave - 在ngIf内容从DOM移除时发生。

点击这里 了解更多关于涉及动画的步骤。

参数

参数 | 类型 | 详述
ngIf | expression | 如果表达式为假，元素从DOM树移除。如果为真，复制一份已编译过的元素添加到DOM树。

示例

index.html
Click me: <input type="checkbox" ng-model="checked" ng-init="checked=true" /><br/>
Show when checked:<span ng-if="checked" class="animate-if">
  I'm removed when the checkbox is unchecked.
</span>
animations.css
.animate-if {
  background:white;
  border:1px solid black;
  padding:10px;}

.animate-if.ng-enter, .animate-if.ng-leave {
  -webkit-transition:all cubic-bezier(0.250, 0.460, 0.450, 0.940) 0.5s;
  transition:all cubic-bezier(0.250, 0.460, 0.450, 0.940) 0.5s;}

.animate-if.ng-enter,.animate-if.ng-leave.ng-leave-active {
  opacity:0;}

.animate-if.ng-leave,.animate-if.ng-enter.ng-enter-active {
  opacity:1;}


AngularJS: API: ng/directive/ngInclude

ngInclude

  1. - directive in module ng

获取、编译并引用一个外部HTML片段。

默认情况下，模板URL被强制为使用与应用文档相同的域名和协议。这是通过调用$sce.getTrustedResourceUrl 实现的。为了从其它的域名和协议载入模板，你可以采用 白名单化 或 包裹化 任一手段来作为可信任值。参考 Angular的 强上下文转义。

此外，浏览器的 同源策略 和 交叉源资源共享(CORS) 策略会进一步限制模板是否能成功载入。例如，ngInclude 在所有浏览器上不能进行交叉域请求，一些浏览不能访问 file:// 等。

指令信息

  • 这个指令会创建新的作用域(scope)。
  • 这个指令执行优先级为400.

用法

  • 作为元素使用: (这个指令能用于自定义元素，但要注意IE限制)。
    <ng-include
  src=""
  [onload=""]
  [autoscroll=""]>
...
</ng-include>
  • 作为属性使用:
    <ANY
  ng-include=""
  [onload=""]
  [autoscroll=""]>
...
</ANY>
  • 作为CSS类使用:
    <ANY class="ng-include: ; [onload: ;] [autoscroll: ;]"> ... </ANY>

动画

enter - 动画用于新内容加入到浏览器时。

leave - 动画应用于现有内容去除时。

enter和 leave动画会并行发生。

点击这里 了解更多关于涉及动画的步骤。

参数

参数 类型 详述
ngInclude | src string

计算结果为URL的angular表达式。 如果来源是一个字符串常量，请确保使用单引号包裹它，例如 src="'myPartialTemplate.html'".

onload
(可选)
string

当新的部分被载入时的计算表达式。

autoscroll
(可选)
string

是否 ngInclude 可以调用 $anchorScroll 来滚动可视区域，在内容被加载后。

- 如果属性未设置，禁止滚动。
- 如果存在属性但没有值，允许滚动。
- 其它情况下只有表达式计算结果为真时才允许滚动。

事件

  • $includeContentRequested

    每次请求ngInclude内容时触发。

    类型:

    emit

    目标:

    ngInclude定义所在的域

  • $includeContentLoaded

    每次ngInclude内容载入时触发。

    类型:

    emit

    目标:

    当前ngInclude域

  • $includeContentError

    当一个模板的HTTP请求得到错误响应(status < 200 || status > 299)时触发。

    类型:

    emit

    目标:

    ngInclude定义所在的域

示例

index.html
<div ng-controller="ExampleController">
  <select ng-model="template" ng-options="t.name for t in templates">
   <option value="">(blank)</option>
  </select>
  url of the template: <tt>{{template.url}}</tt>
  <hr/>
  <div class="slide-animate-container">
    <div class="slide-animate" ng-include="template.url"></div>
  </div>
</div>
script.js
angular.module('includeExample', ['ngAnimate'])
  .controller('ExampleController', ['$scope', Function($scope) {
    $scope.templates =
      [ { name: 'template1.html', url: 'template1.html'},
        { name: 'template2.html', url: 'template2.html'} ];
    $scope.template = $scope.templates[0];
  }]);
template1.html
Content of template1.html
template2.html
Content of template2.html
animations.css
.slide-animate-container {
  position:relative;
  background:white;
  border:1px solid black;
  height:40px;
  overflow:hidden;}

.slide-animate {
  padding:10px;}

.slide-animate.ng-enter, .slide-animate.ng-leave {
  -webkit-transition:all cubic-bezier(0.250, 0.460, 0.450, 0.940) 0.5s;
  transition:all cubic-bezier(0.250, 0.460, 0.450, 0.940) 0.5s;

  position:absolute;
  top:0;
  left:0;
  right:0;
  bottom:0;
  display:block;
  padding:10px;}

.slide-animate.ng-enter {
  top:-50px;}.slide-animate.ng-enter.ng-enter-active {
  top:0;}

.slide-animate.ng-leave {
  top:0;}.slide-animate.ng-leave.ng-leave-active {
  top:50px;}
protractor.js
var templateSelect = element(by.model('template'));var includeElem = element(by.css('[ng-include]'));

it('should load template1.html', Function() {
  expect(includeElem.getText()).toMatch(/Content of template1.html/);});

it('should load template2.html', Function() {
  if (browser.params.browser == 'firefox') {
    // Firefox can't handle using selects
    // See https://github.com/angular/protractor/issues/480
    return;
  }
  templateSelect.click();
  templateSelect.all(by.css('option')).get(2).click();
  expect(includeElem.getText()).toMatch(/Content of template2.html/);});

it('should change to blank', Function() {
  if (browser.params.browser == 'firefox') {
    // Firefox can't handle using selects
    return;
  }
  templateSelect.click();
  templateSelect.all(by.css('option')).get(0).click();
  expect(includeElem.isPresent()).toBe(false);});


AngularJS: API: ng/directive/ngInit

ngInit

  1. - directive in module ng

ngInit指令允许你在执行一个当前域中的表达式。

ngInit只适用于ngRepeat这种特殊性质的属性，参见下面的示例。除此之外，你应该使用 控制器 而不是 ngInit来初始化域中的值。
注意: 如果你在 ngInit中同时使用了 $filter，请确认使用括号来保证正确的优先级：
 <div ng-init="test1 = (data | orderBy:'name')"></div>

指令信息

  • 这个指令执行优先级为450.

用法

  • 作为属性使用:
    <ANY
  ng-init="">
...
</ANY>
  • 作为CSS类使用:
    <ANY class="ng-init: ;"> ... </ANY>

参数

参数 | 类型 | 详述
ngInit | expression | 用于计算的表达式。

示例

index.html
<script>
angular.module('initExample', [])
  .controller('ExampleController', ['$scope', Function($scope) {
    $scope.list = [['a', 'b'], ['c', 'd']];
  }]);
</script>
<div ng-controller="ExampleController">
<div ng-repeat="innerList in list" ng-init="outerIndex = $index">
  <div ng-repeat="value in innerList" ng-init="innerIndex = $index">
     <span class="example-init">list[ {{outerIndex}} ][ {{innerIndex}} ] = {{value}};</span>
  </div>
</div>
</div>
protractor.js
it('should alias index positions', Function() {
  var elements = element.all(by.css('.example-init'));
  expect(elements.get(0).getText()).toBe('list[ 0 ][ 0 ] = a;');
  expect(elements.get(1).getText()).toBe('list[ 0 ][ 1 ] = b;');
  expect(elements.get(2).getText()).toBe('list[ 1 ][ 0 ] = c;');
  expect(elements.get(3).getText()).toBe('list[ 1 ][ 1 ] = d;');});


AngularJS: API: ng/directive/ngKeydown

ngKeydown

  1. - directive in module ng

指定自定义行为到keydown事件上。

指令信息

  • 这个指令执行优先级为0.

用法

  • 作为属性使用:
    <ANY
  ng-keydown="">
...
</ANY>

参数

参数 | 类型 | 详述
ngKeydown | expression | 在 keydown触发时执行的表达式 (事件对象存于$event ，并且能取到keyCode, altKey等信息)。

示例

index.html
<input ng-keydown="count = count + 1" ng-init="count=0">
key down count: {{count}}


AngularJS: API: ng/directive/ngKeypress

ngKeypress

  1. - directive in module ng

指定自定义行为到keypress事件上。

指令信息

  • 这个指令执行优先级为0.

用法

  • 作为属性使用:
    <ANY
  ng-keypress="">
...
</ANY>

参数

参数 | 类型 | 详述
ngKeypress | expression | 在 keypress触发时执行的表达式. (事件对象存放于$event ，并且能取到keyCode, altKey等信息)

示例

index.html
<input ng-keypress="count = count + 1" ng-init="count=0">
key press count: {{count}}


AngularJS: API: ng/directive/ngKeyup

ngKeyup

  1. - directive in module ng

指定自定义行为到keyup事件上。

指令信息

  • 这个指令执行优先级为0.

用法

  • 作为属性使用:
    <ANY
  ng-keyup="">
...
</ANY>

参数

参数 | 类型 | 详述
ngKeyup | expression | 在 keyup触发时执行的表达式. (事件对象存于 $event ，并且能取到keyCode, altKey等信息)

示例

index.html
<p>Typing in the input box below updates the key count</p>
<input ng-keyup="count = count + 1" ng-init="count=0"> key up count: {{count}}

<p>Typing in the input box below updates the keycode</p>
<input ng-keyup="event=$event">
<p>event keyCode: {{ event.keyCode }}</p>
<p>event altKey: {{ event.altKey }}</p>


AngularJS: API: ng/directive/ngList

ngList

  1. - directive in module ng

将文本输入在分隔的字符串和字符串数组之间转换。分隔符可以使用一个固定字符串 (默认为逗号) 或正则表达式。

指令信息

  • 这个指令执行优先级为0.

用法

  • 作为属性使用:
    <input
  [ng-list=""]>
...
</input>

参数

参数 | 类型 | 详述
ngList (可选) | string | 用于分隔值的可选分隔符。 如果格式为 /something/，则值使用正则表达式转换。

示例

index.html
<script>
  angular.module('listExample', [])
    .controller('ExampleController', ['$scope', Function($scope) {
      $scope.names = ['igor', 'misko', 'vojta'];
    }]);</script><form name="myForm" ng-controller="ExampleController">
  List: <input name="namesInput" ng-model="names" ng-list required>
  <span class="error" ng-show="myForm.namesInput.$error.required">
    Required!</span>
  <br>
  <tt>names = {{names}}</tt><br/>
  <tt>myForm.namesInput.$valid = {{myForm.namesInput.$valid}}</tt><br/>
  <tt>myForm.namesInput.$error = {{myForm.namesInput.$error}}</tt><br/>
  <tt>myForm.$valid = {{myForm.$valid}}</tt><br/>
  <tt>myForm.$error.required = {{!!myForm.$error.required}}</tt><br/>
 </form>
protractor.js
var listInput = element(by.model('names'));var names = element(by.binding('{{names}}'));var valid = element(by.binding('myForm.namesInput.$valid'));var error = element(by.css('span.error'));

it('should initialize to model', Function() {
  expect(names.getText()).toContain('["igor","misko","vojta"]');
  expect(valid.getText()).toContain('true');
  expect(error.getCssValue('display')).toBe('none');});

it('should be invalid if empty', Function() {
  listInput.clear();
  listInput.sendKeys('');

  expect(names.getText()).toContain('');
  expect(valid.getText()).toContain('false');
  expect(error.getCssValue('display')).not.toBe('none');        });


AngularJS: API: ng/directive/ngModel

ngModel

  1. - directive in module ng

ngModel指令使用NgModelController绑定一个 input,select, textarea (或自定义表单控件) 到域上的一个属性。

ngModel 职责为：

  • 绑定视图到模型，如 input, textarea或select 等指令。
  • 提供验证操作 (如必输、数字、email、url)。
  • 维护控件的状态 (有效/无效, 有改动/无改动, 触摸过/未触摸, 验证错误等)。
  • 设置元素上相关的css类 (ng-valid, ng-invalid, ng-dirty, ng-pristine, ng-touched, ng-untouched) ，包括动画。
  • 注册控件到父 表单。

注意： ngModel 会尝试使用表达式的计算结果来绑定到当前域上的属性。如果属性在当前域上不存在，它会立即创建并添加到当前域。

使用 ngModel的最佳实践参见：

  • [https://github.com/angular/angular.js/wiki/Understanding-Scopes]

如何使用ngModel的一些简单例子参见：

  • input
    • text
    • checkbox
    • radio
    • number
    • email
    • url
    • date
    • dateTimeLocal
    • time
    • month
    • week
  • select
  • textarea

CSS类

以下CSS类会被添加或移除到相关联的input/select/textarea元素上，这取决于模型的变化。

  • ng-valid 模型有效时设置。
  • ng-invalid 模型无效时设置。
  • ng-pristine 模型纯净（未变化）时设置。
  • ng-dirty 模型脏（有变化）时设置。

记住， ngAnimate可以检测到每个类的添加和删除。

动画钩子

模型的动画会被触发，当绑定到模型上的输入元素关联的CSS样式被添加或删除时。这些类有: .ng-pristine, .ng-dirty, .ng-invalid 和 .ng-valid ，以及对模型本身进行的任何其他验证。ngModel触发的动画类似于ngClass上的工作方式，动画可以使用CSS的过渡、关键帧，以及JS动画。

下面的例子简单演示了使用CSS过渡来渲染输入元素上的样式，当它从有效变成无效时：

//be sure to include ngAnimate as a module to hook into more
//advanced animations
.my-input {
  transition:0.5s linear all;
  background: white;
}
.my-input.ng-invalid {
  background: red;
  color:white;
}

指令信息

  • 这个指令执行优先级为0.

用法

  • 作为属性使用:
    <input>
...
</input>

示例

index.html
<script>
 angular.module('inputExample', [])
   .controller('ExampleController', ['$scope', Function($scope) {
     $scope.val = '1';
   }]);
</script>
<style>
  .my-input {
    -webkit-transition:all linear 0.5s;
    transition:all linear 0.5s;
    background: transparent;
  }
  .my-input.ng-invalid {
    color:white;
    background: red;
  }
</style>
Update input to see transitions when valid/invalid.
Integer is a valid value.
<form name="testForm" ng-controller="ExampleController">
  <input ng-model="val" ng-pattern="/^\d+$/" name="anim" class="my-input" />
</form>

绑定到getter/setter

有时候绑定 ngModel到一个getter/setter函数时很有用的。getter是一种能返回一个模型表示的无参函数，setter是只有一个参数的用于设置模型内部状态的函数。 它对于模型内部与视图显示时所用的数据形式不一致时非常有用。

最佳实践： 最好保证getters执行很快，因为Angular可能会比你其它的代码更频繁的调用它。

要使用它，你需要添加 ng-model-options="{ getterSetter: true }"到一个有 ng-model 元素上。你也可以添加 ng-model-options="{ getterSetter: true }" 到 <form>上，使的表单中的所有<input>都生效。参见 ngModelOptions 获取更多信息。

下面的例子演示如何通过getter/setter使用 ngModel ：

index.html
<div ng-controller="ExampleController">
  <form name="userForm">
    Name:
    <input Type="text" name="userName"
           ng-model="user.name"
           ng-model-options="{ getterSetter: true }" />
  </form>
  <pre>user.name = <span ng-bind="user.name()"></span></pre></div>
app.js
angular.module('getterSetterExample', [])
  .controller('ExampleController', ['$scope', Function($scope) {
    var _name = 'Brian';
    $scope.user = {
      name: Function (newName) {
        if (angular.isDefined(newName)) {
          _name = newName;
        }
        return _name;
      }
    };
  }]);


AngularJS: API: ng/directive/ngModelOptions

ngModelOptions

  1. - directive in module ng

允许调整模型更新时机。使用 ngModelOptions 你可以指定一个触发模型更新和（或）消除抖动延迟事件列表，使实际更新只发生在计时器过期时。此计时器会被之后的其他变化重置。

鉴于ngModelOptions的性质， 在视图中显示的输入域的值可能不同于实际模型的值。这意味着如果你更新模型，你需要在新旧关的输入域上调用$rollbackViewValue，以确保它与模型同步，并会消除任何抖动。

引用控制的$rollbackViewValue方法的最简单的方法是确保输入组件被放置在一个具有name属性的表单中。这很重要，因为 form控制器使用它们的 name 属性发布到相关域。

任何挂起的更改会立即生效，当整个表单通过 submit事件提交时。注意 ngClick 事件会在模型更新前生效。使用 ngSubmit 来存取更新后的模型。

指令信息

  • 这个指令执行优先级为0.

用法

  • 作为属性使用:
    <ANY
  ng-model-options="">
...
</ANY>

参数

参数 类型 详述
ngModelOptions Object

应用于当前模型的可选项。有效的键名为：

  • updateOn: 用于指定输入绑定到哪个事件的字符串。你可以设置使用空格分隔的事件列表。有一个特殊事件叫 default ，用于匹配控件自身的默认事件。
  • debounce: 以毫秒为单位的整型值，用于防止模型更新抖动。值为0会立即触发更新。如果使用一个对象替代的话，你可以为每个事件指定值。例如：ngModelOptions="{ updateOn: 'default blur', debounce: {'default': 500, 'blur': 0} }"
  • getterSetter: 布尔值，用于声明 ngModel是否绑定到getters/setters函数上。

示例

下面的例子演示如何替换立即更新。表单内的输入控件只会在失去焦点时才更新模型 (blur 事件)。如果当前焦点在输入字段时按了escape键，当前模型的值会被重置。

index.html
<div ng-controller="ExampleController">
  <form name="userForm">
    Name:
    <input Type="text" name="userName"
           ng-model="user.name"
           ng-model-options="{ updateOn: 'blur' }"
           ng-keyup="cancel($event)" /><br />

    Other data:
    <input Type="text" ng-model="user.data" /><br />
  </form>
  <pre>user.name = <span ng-bind="user.name"></span></pre>
</div>
app.js
angular.module('optionsExample', [])
  .controller('ExampleController', ['$scope', Function($scope) {
    $scope.user = { name: 'say', data: '' };

    $scope.cancel = Function (e) {
      if (e.keyCode == 27) {
        $scope.userForm.userName.$rollbackViewValue();
      }
    };
  }]);
protractor.js
var model = element(by.binding('user.name'));
var input = element(by.model('user.name'));
var other = element(by.model('user.data'));

it('should allow custom events', Function() {
  input.sendKeys(' hello');
  input.click();
  expect(model.getText()).toEqual('say');
  other.click();
  expect(model.getText()).toEqual('say hello');});

it('should $rollbackViewValue when model changes', Function() {
  input.sendKeys(' hello');
  expect(input.getAttribute('value')).toEqual('say hello');
  input.sendKeys(protractor.Key.ESCAPE);
  expect(input.getAttribute('value')).toEqual('say');
  other.click();
  expect(model.getText()).toEqual('say');});

下面的例子演示如何消除模型改变时的抖动。模型会在最后一次改变的1秒后更新。如果按了Clear按钮，任何消除抖动操作会被取消，值会清空。

index.html
<div ng-controller="ExampleController">
  <form name="userForm">
    Name:
    <input Type="text" name="userName"
           ng-model="user.name"
           ng-model-options="{ debounce: 1000 }" />
    <button ng-click="userForm.userName.$rollbackViewValue(); user.name=''">Clear</button><br />
  </form>
  <pre>user.name = <span ng-bind="user.name"></span></pre>
</div>
app.js
angular.module('optionsExample', [])
  .controller('ExampleController', ['$scope', Function($scope) {
    $scope.user = { name: 'say' };
  }]);

下面的例子演示如何绑定到getter/setters:

index.html
<div ng-controller="ExampleController">
  <form name="userForm">
    Name:
    <input Type="text" name="userName"
           ng-model="user.name"
           ng-model-options="{ getterSetter: true }" />
  </form>
  <pre>user.name = <span ng-bind="user.name()"></span></pre>
</div>
app.js
angular.module('getterSetterExample', [])
  .controller('ExampleController', ['$scope', Function($scope) {
    var _name = 'Brian';
    $scope.user = {
      name: Function (newName) {
        return angular.isDefined(newName) ? (_name = newName) : _name;
      }
    };
  }]);


AngularJS: API: ng/directive/ngMousedown

ngMousedown

  1. - directive in module ng

ngMousedown指令允许你指定自定义行为到mousedown事件上。

指令信息

  • 这个指令执行优先级为0.

用法

  • 作为属性使用:
    <ANY
  ng-mousedown="">
...
</ANY>

参数

参数 | 类型 | 详述
ngMousedown | expression | 在mousedown触发时执行的表达式 . (事件对象存放于$event)

示例

index.html
<button ng-mousedown="count = count + 1" ng-init="count=0">
  Increment (on mouse down)
</button>
count: {{count}}


AngularJS: API: ng/directive/ngMouseenter

ngMouseenter

  1. - directive in module ng

指定自定义行为到mouseenter事件上。

指令信息

  • 这个指令执行优先级为0.

用法

  • 作为属性使用:
    <ANY
  ng-mouseenter="">
...
</ANY>

参数

参数 | 类型 | 详述
ngMouseenter | expression | 在mouseenter触发时执行的表达式 . (事件对象存放于$event)

示例

index.html
<button ng-mouseenter="count = count + 1" ng-init="count=0">
  Increment (when mouse enters)
</button>
count: {{count}}


AngularJS: API: ng/directive/ngMouseleave

ngMouseleave

  1. - directive in module ng

指定自定义行为到mouseleave事件上。

指令信息

  • 这个指令执行优先级为0.

用法

  • 作为属性使用:
    <ANY
  ng-mouseleave="">
...
</ANY>

参数

参数 | 类型 | 详述
ngMouseleave | expression | 在mouseleave触发时执行的表达式 . (事件对象存放于$event)

示例

index.html
<button ng-mouseleave="count = count + 1" ng-init="count=0">
  Increment (when mouse leaves)
</button>
count: {{count}}


AngularJS: API: ng/directive/ngMousemove

ngMousemove

  1. - directive in module ng

指定自定义行为到mousemove事件上。

指令信息

  • 这个指令执行优先级为0.

用法

  • 作为属性使用:
    <ANY
  ng-mousemove="">
...
</ANY>

参数

参数 | 类型 | 详述
ngMousemove | expression | 在mousemove触发时执行的表达式 . (事件对象存放于$event)

示例

index.html
<button ng-mousemove="count = count + 1" ng-init="count=0">
  Increment (when mouse moves)
</button>
count: {{count}}


AngularJS: API: ng/directive/ngMouseover

ngMouseover

  1. - directive in module ng

指定自定义行为到mouseover事件上。

指令信息

  • 这个指令执行优先级为0.

用法

  • 作为属性使用:
    <ANY
  ng-mouseover="">
...
</ANY>

参数

参数 | 类型 | 详述
ngMouseover | expression | 在mouseover触发时执行的表达式 . (事件对象存放于$event)

示例

index.html
<button ng-mouseover="count = count + 1" ng-init="count=0">
  Increment (when mouse is over)
</button>
count: {{count}}


AngularJS: API: ng/directive/ngMouseup

ngMouseup

  1. - directive in module ng

指定自定义行为到mouseup事件上。

指令信息

  • 这个指令执行优先级为0.

用法

  • 作为属性使用:
    <ANY
  ng-mouseup="">
...
</ANY>

参数

参数 | 类型 | 详述
ngMouseup | expression | 在mouseup触发时执行的表达式 . (事件对象存放于$event)

示例

index.html
<button ng-mouseup="count = count + 1" ng-init="count=0">
  Increment (on mouse up)
</button>
count: {{count}}


AngularJS: API: ng/directive/ngNonBindable

ngNonBindable

  1. - directive in module ng

ngNonBindable指令告诉Angular编译或绑定当前DOM元素的内容。这对于要求Angular忽略那些元素中包含Angular指令和绑定的情况下很有用。这种情况能让你的网站实时显示源码。

指令信息

  • 这个指令执行优先级为1000.

用法

  • 作为属性使用:
    <ANY>
...
</ANY>
  • 作为CSS类使用:
    <ANY class=""> ... </ANY>

示例

这个例子中有两处使用了绑定符 ({{}}) ，但是有一处声明了ngNonBindable。

index.html
<div>Normal: {{1 + 2}}</div><div ng-non-bindable>Ignored: {{1 + 2}}</div>
protractor.js
it('should check ng-non-bindable', Function() {
  expect(element(by.binding('1 + 2')).getText()).toContain('3');
  expect(element.all(by.css('div')).last().getText()).toMatch(/1 \+ 2/);});


AngularJS: API: ng/directive/ngOpen

ngOpen

  1. - directive in module ng

HTML规范不要求浏览器对布尔型属性必须给出值，例如open(它们存在表示true，不存在表示false)。 如果我们放置了一个Angular动态表达式到这样的属性上，在浏览器删除属性时绑定信息将会丢失。 ngOpen指令解决了open属性的这个问题。这个指令不会被浏览器删除，并提供了一个永久的可靠的地方存放绑定信息。

指令信息

  • 这个指令执行优先级为100.

用法

  • 作为属性使用:
    <DETAILS
  ng-open="">
...
</DETAILS>

参数

参数 | 类型 | 详述
ngOpen | expression | 如果表达式为真， 指定的属性"open" 会被设到元素上。

示例

index.html
Check me check multiple: <input type="checkbox" ng-model="open"><br/>
<details id="details" ng-open="open">
   <summary>Show/Hide me</summary>
</details>
protractor.js
it('should toggle open', Function() {
  expect(element(by.id('details')).getAttribute('open')).toBeFalsy();
  element(by.model('open')).click();
  expect(element(by.id('details')).getAttribute('open')).toBeTruthy();});


AngularJS: API: ng/directive/ngPaste

ngPaste

  1. - directive in module ng

指定自定义行为到paste事件上。

指令信息

  • 这个指令执行优先级为0.

用法

  • 作为属性使用:
    <window, input, select, textarea, a
  ng-paste="">
...
</window, input, select, textarea, a>

参数

参数 | 类型 | 详述
ngPaste | expression | 在paste触发时执行的表达式 . (事件对象存放于$event)

示例

index.html
<input ng-paste="paste=true" ng-init="paste=false" placeholder='paste here'>
pasted: {{paste}}


AngularJS: API: ng/directive/ngPluralize

ngPluralize

  1. - directive in module ng

ngPluralize指令依照en-US本地化规则显示信息。这些规则和angular.js捆绑在一起，但是可以被覆盖(参见 Angular i18n 开发指南)。配置ngPluralize指令的方式是通过给出多元化条目和显示字符串的映射实现的。

多元化条目和显式数字规则

有两个多元化条目在Angular的默认en-US本地化中: "one"和"other"。

一个多元化条目可以匹配多个数字(例如，在en-US本地化中，"other"可以匹配除1以外的任何数字)，一条显式数字规则只能匹配一个数字，例如，显式数字规则"3"只能匹配数字3。本文档的后面有很多多元化条目和显示数字规则的示例。

配置ngPluralize

你可以使用2个属性配置ngPluralize: count 和 when。你还能使用可选的属性offset。

count属性的值可以是字符串或一个Angular表达式；它会在绑定值的当前域上运算。

when属性指定多元化条目和实现显示字符串的映射关系。属性值可以是JSON对象。

下面的例子演示如何配置ngPluralize:

<ng-pluralize count="personCount"
                 when="{'0': 'Nobody is viewing.',
                     'one': '1 person is viewing.',
                     'other': '{} people are viewing.'}">
</ng-pluralize>

在例子中， "0: Nobody is viewing." 是一条显式数字规则。如果你未指定这条规则，0会被匹配到"other"条目，并且"0 people are viewing"会替代"Nobody is viewing"显示出来。你可以为其它数字指定一条显式数字规则，例如12，这样可以替代"12 people are viewing"的显示，你可以显示成"a dozen people are viewing"。

你可以使用一对花括号({}) 作为数字的占位符，将数字代入到多元化字符串中。在前一个例子中，Angular会替换{} 为 {{personCount}}。成对花括号{}作为{{numberExpression}}的点位符。

使用offset配置ngPluralize

offset 属性允许进一步定制化多元化文本，可以产生一个更好的用户体验。例如，替代信息"4 people are viewing this document"，你可以显示为"John, Kate and 2 others are viewing this document"。offset属性允许你使用任何所需的值来偏移一个数字。让我们来看一个例子：

<ng-pluralize count="personCount" offset=2
              when="{'0': 'Nobody is viewing.',
                     '1': '{{person1}} is viewing.',
                     '2': '{{person1}} and {{person2}} are viewing.',
                     'one': '{{person1}}, {{person2}} and one other person are viewing.',
                     'other': '{{person1}}, {{person2}} and {} other people are viewing.'}">
</ng-pluralize>

注意这里仍然使用了两条多元化条目(one, other)，但是我们增加了三条显式数字规则 0, 1 和 2。当一个人，也许是John，看了这个文档，将会显示"John is viewing"。当三个人看了这个文档，非显式数字规则被找到，因为偏移2后为3，Angular使用1来检索多元化条目。在这种情况下，多元化条目 'one'被匹配到，并且"John, Mary and one other person are viewing"被显示。

注意当你指定偏移时，你必须给从0到偏移值的数字提供显式数字规则。例如，如果你使用偏移值3， 你必须提供显式数字规则 0, 1, 2 和3。同时你也必须为多元化条目提供多元化字符串 "one" and "other"。

指令信息

  • 这个指令执行优先级为0.

用法

  • 作为元素使用: (这个指令能用于自定义元素，但要注意IE限制)。
    <ng-pluralize
  count=""
  when=""
  [offset=""]>
...
</ng-pluralize>
  • 作为属性使用:
    <ANY
  count=""
  when=""
  [offset=""]>
...
</ANY>

参数

参数 | 类型 | 详述
count | string expression | 要绑定的变量。
when | string | 多元化条目和对应字符串的映射。
offset (可选) | number | 从总数扣减的偏移值。

示例

index.html
<script>
  angular.module('pluralizeExample', [])
    .controller('ExampleController', ['$scope', Function($scope) {
      $scope.person1 = 'Igor';
      $scope.person2 = 'Misko';
      $scope.personCount = 1;
    }]);
</script>
<div ng-controller="ExampleController">
  Person 1:<input Type="text" ng-model="person1" value="Igor" /><br/>
  Person 2:<input Type="text" ng-model="person2" value="Misko" /><br/>
  Number of People:<input Type="text" ng-model="personCount" value="1" /><br/>

  <!--- Example with simple pluralization rules for en locale --->
  Without Offset:
  <ng-pluralize count="personCount"
                when="{'0': 'Nobody is viewing.',
                       'one': '1 person is viewing.',
                       'other': '{} people are viewing.'}">
  </ng-pluralize><br>

  <!--- Example with offset --->
  With Offset(2):
  <ng-pluralize count="personCount" offset=2
                when="{'0': 'Nobody is viewing.',
                       '1': '{{person1}} is viewing.',
                       '2': '{{person1}} and {{person2}} are viewing.',
                       'one': '{{person1}}, {{person2}} and one other person are viewing.',
                       'other': '{{person1}}, {{person2}} and {} other people are viewing.'}">
  </ng-pluralize>
</div>
protractor.js
it('should show correct pluralized string', Function() {
  var withoutOffset = element.all(by.css('ng-pluralize')).get(0);
  var withOffset = element.all(by.css('ng-pluralize')).get(1);
  var countInput = element(by.model('personCount'));

  expect(withoutOffset.getText()).toEqual('1 person is viewing.');
  expect(withOffset.getText()).toEqual('Igor is viewing.');

  countInput.clear();
  countInput.sendKeys('0');

  expect(withoutOffset.getText()).toEqual('Nobody is viewing.');
  expect(withOffset.getText()).toEqual('Nobody is viewing.');

  countInput.clear();
  countInput.sendKeys('2');

  expect(withoutOffset.getText()).toEqual('2 people are viewing.');
  expect(withOffset.getText()).toEqual('Igor and Misko are viewing.');

  countInput.clear();
  countInput.sendKeys('3');

  expect(withoutOffset.getText()).toEqual('3 people are viewing.');
  expect(withOffset.getText()).toEqual('Igor, Misko and one other person are viewing.');

  countInput.clear();
  countInput.sendKeys('4');

  expect(withoutOffset.getText()).toEqual('4 people are viewing.');
  expect(withOffset.getText()).toEqual('Igor, Misko and 2 other people are viewing.');});
it('should show data-bound names', Function() {
  var withOffset = element.all(by.css('ng-pluralize')).get(1);
  var personCount = element(by.model('personCount'));
  var person1 = element(by.model('person1'));
  var person2 = element(by.model('person2'));
  personCount.clear();
  personCount.sendKeys('4');
  person1.clear();
  person1.sendKeys('Di');
  person2.clear();
  person2.sendKeys('Vojta');
  expect(withOffset.getText()).toEqual('Di, Vojta and 2 other people are viewing.');});


AngularJS: API: ng/directive/ngReadonly

ngReadonly

  1. - directive in module ng

HTML规范不要求浏览器对布尔型属性必须给出值，例如readonly(它们存在表示true，不存在表示false)。 如果我们放置了一个Angular动态表达式到这样的属性上，在浏览器删除属性时绑定信息将会丢失。 ngReadonly指令解决了readonly属性的这个问题。这个指令不会被浏览器删除，并提供了一个永久的可靠的地方存放绑定信息。

指令信息

  • 这个指令执行优先级为100.

用法

  • 作为属性使用:
    <INPUT
  ng-readonly="">
...
</INPUT>

参数

参数 | 类型 | 详述
ngReadonly | expression | 如果表达式为真， 指定的属性"readonly" 会被设到元素上。

示例

index.html
Check me to make text readonly: <input type="checkbox" ng-model="checked"><br/><input type="text" ng-readonly="checked" value="I'm Angular"/>
protractor.js
it('should toggle readonly attr', Function() {
  expect(element(by.css('[type="text"]')).getAttribute('readonly')).toBeFalsy();
  element(by.model('checked')).click();
  expect(element(by.css('[type="text"]')).getAttribute('readonly')).toBeTruthy();});


AngularJS: API: ng/directive/ngRepeat

ngRepeat

  1. - directive in module ng

ngRepeat指令为集合中的每项实例化一个模板。每个模板的实例拥有自己的域，使用循环变量指向当前集合项上，$index指向当前项的索引或键值。

特殊属性应用于每个模板实例的本地域上，包括：

变量 | 类型 | 详述
$index | number | 重复元素的迭代偏移值(0..length-1)
$first | boolean | 如果是重复元素的第一个迭代项则为true
$middle | boolean | 如果是在重复元素的第一个和最后一个之间的迭代项则为true
$last | boolean | 如果是重复元素的最后一个迭代项则为true
$even | boolean | 如果迭代项的位置$index是偶数则为true(其它为false)
$odd | boolean | 如果迭代项的位置$index为奇数则为true(其它为false)

这些也可以用ngInit创建别名。这在实例化嵌套ngRepeats时很有用。

指定重复的开始和结束点

为了解决重复元素序列只有一个父元素的情况，ngRepeat (不同于其它ng指令)支持扩展重复范围，通过使用ng-repeat-start 和 ng-repeat-end分别定义明确的开始和结束点。ng-repeat-start 指令工作方法类似ng-repeat，但是会重复从标签定义本身位置开始到ng-repeat-end定义位置之间的所有HTML代码。

这个例子演示了它的使用场景：

  <header ng-repeat-start="item in items">
    Header {{ item }}
  </header>
  <div class="body">
    Body {{ item }}
  </div>
  <footer ng-repeat-end>
    Footer {{ item }}
  </footer>

如果上面例子中的items变量的值为['A','B']，则输出结果为：

  <header>
    Header A
  </header>
  <div class="body">
    Body A
  </div>
  <footer>
    Footer A
  </footer>
  <header>
    Header B
  </header>
  <div class="body">
    Body B
  </div>
  <footer>
    Footer B
  </footer>

为 ngRepeat指定开始和结束点也支持AngularJS中的所有其它HTML指令语法(例如data-ng-repeat-start, x-ng-repeat-start 和 ng:repeat-start)。

指令信息

  • 这个指令会创建新的作用域(scope)。
  • 这个指令执行优先级为1000.

用法

  • 作为属性使用:
    <ANY
  ng-repeat="">
...
</ANY>

动画

.enter - 当一个新的项添加到列表或条目经过过滤显示时

.leave - 当一个项从列表中删除或当一个项被过滤掉时

.move - 当相邻的一个项被过滤掉引起重新排序，或当条目内容进行重新排序时

点击这里 了解更多关于涉及动画的步骤。

参数

参数 类型 详述
ngRepeat repeat_expression

决定如果枚举集合的表达式。当前支持的格式有：

  • variable in expression – variable是用户定义的循环变量， expression是用于枚举集合的域表达式。

    例如: album in artist.albums.

  • (key, value) in expression – key 和 value 可以是任何用户定义的标识， expression是用于枚举集合的域表达式。

    例如: (name, age) in {'adam':10, 'amalie':12}.

  • variable in expression track by tracking_expression – 您也可以提供一个可选的跟踪函数，用来关联到DOM元素集合中的对象。如果没有给出跟踪函数，ng-repeat使用标识来关联集合中的元素。对于解决相同键，它会比使用一个跟踪函数产生更多错误。(意思是会有两个不同对象映射到相同的DOM元素，也许不会。) 表达式可以使用过滤器，它会在调用跟踪函数前生效。

    例如: item in items 等同于 item in items track by $id(item). 这意味着，DOM元素会关联到数组中的条目标识上。

    例如: item in items track by $id(item). 内建的$id()函数能够用于为数组内的条目分配一个唯一的$$hashKey属性。这个属性用于作为数组中的条目标识关联到DOM元素的键值。移动数组中的同一个对象同样会在DOM中移动DOM元素。

    例如: item in items track by item.id 是当items来自数据库时的典型模式。在这种情况下，对象的标识不会有问题。两个对象被认为是相等的，只要他们的 id属性是一样的。

    例如: item in items | Filter:searchText track by item.id 是对条目同时使用过滤器和跟踪表达式的模式。

示例

这个例子在域中初始化一个名字列表，并使用ngRepeat显示每个人：

index.html
<div ng-init="friends = [
  {name:'John', age:25, gender:'boy'},
  {name:'Jessie', age:30, gender:'girl'},
  {name:'Johanna', age:28, gender:'girl'},
  {name:'Joy', age:15, gender:'girl'},
  {name:'Mary', age:28, gender:'girl'},
  {name:'Peter', age:95, gender:'boy'},
  {name:'Sebastian', age:50, gender:'boy'},
  {name:'Erika', age:27, gender:'girl'},
  {name:'Patrick', age:40, gender:'boy'},
  {name:'Samantha', age:60, gender:'girl'}
]">
  I have {{friends.length}} friends. They are:
  <input Type="search" ng-model="q" placeholder="filter friends..." />
  <ul class="example-animate-container">
    <li class="animate-repeat" ng-repeat="friend in friends | filter:q">
      [{{$index + 1}}] {{friend.name}} who is {{friend.age}} years old.
    </li>
  </ul>
</div>
animations.css
.示例:-animate-container {
  background:white;
  border:1px solid black;
  list-style:none;
  margin:0;
  padding:0 10px;}

.animate-repeat {
  line-height:40px;
  list-style:none;
  box-sizing:border-box;}

.animate-repeat.ng-move,.animate-repeat.ng-enter,.animate-repeat.ng-leave {
  -webkit-transition:all linear 0.5s;
  transition:all linear 0.5s;}

.animate-repeat.ng-leave.ng-leave-active,.animate-repeat.ng-move,.animate-repeat.ng-enter {
  opacity:0;
  max-height:0;}

.animate-repeat.ng-leave,.animate-repeat.ng-move.ng-move-active,.animate-repeat.ng-enter.ng-enter-active {
  opacity:1;
  max-height:40px;}
protractor.js
var friends = element.all(by.repeater('friend in friends'));

it('should render initial data set', Function() {
  expect(friends.count()).toBe(10);
  expect(friends.get(0).getText()).toEqual('[1] John who is 25 years old.');
  expect(friends.get(1).getText()).toEqual('[2] Jessie who is 30 years old.');
  expect(friends.last().getText()).toEqual('[10] Samantha who is 60 years old.');
  expect(element(by.binding('friends.length')).getText())
      .toMatch("I have 10 friends. They are:");});

 it('should update repeater when filter predicate changes', Function() {
   expect(friends.count()).toBe(10);

   element(by.model('q')).sendKeys('ma');

   expect(friends.count()).toBe(2);
   expect(friends.get(0).getText()).toEqual('[1] Mary who is 28 years old.');
   expect(friends.last().getText()).toEqual('[2] Samantha who is 60 years old.');
 });


AngularJS: API: ng/directive/ngSelected

ngSelected

  1. - directive in module ng

HTML规范不要求浏览器对布尔型属性必须给出值，例如selected(它们存在表示true，不存在表示false)。 如果我们放置了一个Angular动态表达式到这样的属性上，在浏览器删除属性时绑定信息将会丢失。 ngSelected 指令解决了 selected 属性存在的问题。这个指令不会被浏览器删除，并提供了一个永久的可靠的地方存放绑定信息。

指令信息

  • 这个指令执行优先级为100.

用法

  • 作为属性使用:
    <OPTION
  ng-selected="">
...
</OPTION>

参数

参数 | 类型 | 详述
ngSelected | expression | 如果表达式为真， 指定的属性"selected" 会被设到元素上。

示例

index.html
Check me to select: <input type="checkbox" ng-model="selected"><br/><select>
  <option>Hello!</option>
  <option id="greet" ng-selected="selected">Greetings!</option></select>
protractor.js
it('should select Greetings!', Function() {
  expect(element(by.id('greet')).getAttribute('selected')).toBeFalsy();
  element(by.model('selected')).click();
  expect(element(by.id('greet')).getAttribute('selected')).toBeTruthy();});


AngularJS: API: ng/directive/ngShow

ngShow

  1. - directive in module ng

ngShow指令根据ngShow属性上表达式来显示或隐藏给定的HTML元素。元素的显示或隐藏是通过删除或添加ng-hide CSS 类到元素上来实现的。.ng-hide CSS 类是在AngularJS预定义的，并且设置显示样式为空(使用!important标记)。 对于CSP 模式请添加 angular-csp.css 到你的html文件(参见ngCsp)。

<!-- when $scope.myValue is truthy (element is visible) -->
<div ng-show="myValue"></div>

<!-- when $scope.myValue is falsy (element is hidden) -->
<div ng-show="myValue" class="ng-hide"></div>

当ngShow表达式计算结果为假时，ng-hide CSS 类会被加到元素的class属性中，从而让它变为隐藏。当为真时，ng-hide CSS 类会从元素移除，这样元素就不会被隐藏。

为什么使用!important?

你可能想知道为什么要在ng-hide CSS类上使用!important。这是因为 .ng-hide选择器很容易被级别更高的选择器覆盖。例如，一些简单的改变HTML列表条目的显示样式会让隐藏的元素显示。这成为了处理CSS框架时最大的问题。

通过使用!important，显示和隐藏行为会按预期工作，而不管CSS选择器间的任何冲突(当!important没用在任何相矛盾的样式上时)。如果开发者决定覆盖样式来改变如何隐藏元素，那只需要在自己的CSS代码中配合使!important即可。

覆盖 .ng-hide

默认情况下，.ng-hide类使用 display:none!important格式化元素。如果你希望改变ngShow/ngHide的隐藏行为，可通过在CSS中重新定义 .ng-hide类来实现：

.ng-hide {
  /* this is just another form of hiding an element */
  display:block!important;
  position:absolute;
  top:-9999px;
  left:-9999px;}

默认情况下你不需要覆盖CSS中任何东西，动画就会针对显示样式生效。

ngShow动画的一些注意点

ngShow/ngHide中动画的显示和隐藏事件会在指令表达式为真或假时触发。 这个系统工作方式像ngClass的动画系统，除了你必须也包含!important标记到覆盖的显示属性中，这样就可以在元素隐藏动画期间正确执行。

////a working example can be found at the bottom of this page
//.my-element.ng-hide-add, .my-element.ng-hide-remove {
  /* this is required as of 1.3x to properly
     apply all styling in a show/hide animation */
  transition:0s linear all;}

.my-element.ng-hide-add-active,.my-element.ng-hide-remove-active {
  /* the transition is defined in the active class */
  transition:1s linear all;}

.my-element.ng-hide-add { ... }.my-element.ng-hide-add.ng-hide-add-active { ... }.my-element.ng-hide-remove { ... }.my-element.ng-hide-remove.ng-hide-remove-active { ... }

记住，AngularJS的1.3.0-beta.11版本里， 不需要通过阻塞动画过程来改变显示属性，ngAnimate会为你自动处理样式的切换。

指令信息

  • 这个指令执行优先级为0.

用法

  • 作为属性使用:
    <ANY
  ng-show="">
...
</ANY>

动画

addClass: .ng-hide - 在ngShow表达式计算结果为非真时生效，并且是在内容被显示前。

removeClass: .ng-hide - 在ngShow表达式计算结果为真时生效，并且是在内容被隐藏前。

点击这里 了解更多关于涉及动画的步骤。

参数

参数 | 类型 | 详述
ngShow | expression | 如果表达式为真则显示元素，否则隐藏。

示例

index.html
Click me: <input type="checkbox" ng-model="checked"><br/><div>
  Show:
  <div class="check-element animate-show" ng-show="checked">
    <span class="glyphicon glyphicon-thumbs-up"></span> I show up when your checkbox is checked.
  </div>
</div><div>
  Hide:
  <div class="check-element animate-show" ng-hide="checked">
    <span class="glyphicon glyphicon-thumbs-down"></span> I hide when your checkbox is checked.
  </div>
</div>
glyphicons.css
@import url(//netdna.bootstrapcdn.com/bootstrap/3.0.0/css/bootstrap-glyphicons.css);
animations.css
.animate-show {
  line-height:20px;
  opacity:1;
  padding:10px;
  border:1px solid black;
  background:white;}

.animate-show.ng-hide-add.ng-hide-add-active,.animate-show.ng-hide-remove.ng-hide-remove-active {
  -webkit-transition:all linear 0.5s;
  transition:all linear 0.5s;}

.animate-show.ng-hide {
  line-height:0;
  opacity:0;
  padding:0 10px;}

.check-element {
  padding:10px;
  border:1px solid black;
  background:white;}
protractor.js
var thumbsUp = element(by.css('span.glyphicon-thumbs-up'));var thumbsDown = element(by.css('span.glyphicon-thumbs-down'));

it('should check ng-show / ng-hide', Function() {
  expect(thumbsUp.isDisplayed()).toBeFalsy();
  expect(thumbsDown.isDisplayed()).toBeTruthy();

  element(by.model('checked')).click();

  expect(thumbsUp.isDisplayed()).toBeTruthy();
  expect(thumbsDown.isDisplayed()).toBeFalsy();});


AngularJS: API: ng/directive/ngSrc

ngSrc

  1. - directive in module ng

Angular的{{hash}}等标记在src属性中不能正确工作：浏览器会使用包含{{hash}} 的原始文本的URL，在Angular更新{{hash}}内的表达式之前。 ngSrc 指令解决了这个问题。

有问题的写法：

<img src="http://www.gravatar.com/avatar/{{hash}}"/>

正确的写法：

<img ng-src="http://www.gravatar.com/avatar/{{hash}}"/>

指令信息

  • 这个指令执行优先级为99.

用法

  • 作为属性使用:
    <IMG
  ng-src="">
...
</IMG>

参数

参数 | 类型 | 详述
ngSrc | template | 可以包含{{}}标记的任意字符串。


AngularJS: API: ng/directive/ngSrcset

ngSrcset

  1. - directive in module ng

Angular的{{hash}}等标记在srcset属性中不能正确工作：浏览器会使用包含{{hash}} 的原始文本的URL，在Angular更新{{hash}}内的表达式之前。 ngSrcset 指令解决了这个问题。

有问题的写法：

<img srcset="http://www.gravatar.com/avatar/{{hash}} 2x"/>

正确的写法：

<img ng-srcset="http://www.gravatar.com/avatar/{{hash}} 2x"/>

指令信息

  • 这个指令执行优先级为99.

用法

  • 作为属性使用:
    <IMG
  ng-srcset="">
...
</IMG>

参数

参数 | 类型 | 详述
ngSrcset | template | 可以包含{{}}标记的任意字符串。


AngularJS: API: ng/directive/ngStyle

ngStyle

  1. - directive in module ng

ngStyle指令允许你在HTML元素上条件化设置CSS样式。

指令信息

  • 这个指令执行优先级为0.

用法

  • 作为属性使用:
    <ANY
  ng-style="">
...
</ANY>
  • 作为CSS类使用:
    <ANY class="ng-style: ;"> ... </ANY>

参数

参数 | 类型 | 详述
ngStyle | expression | 结果为对象的表达式，对象的键名为CSS样式名，对象的键值为CSS名对应的值。 有些CSS样式名不能直接作为对象的键名，它们必须用引号括起来。参见下面例子中的 'background-color'样式。

示例

index.html
<input Type="button" value="set color" ng-click="myStyle={color:'red'}">
<input Type="button" value="set background" ng-click="myStyle={'background-color':'blue'}">
<input Type="button" value="clear" ng-click="myStyle={}"><br/>
<span ng-style="myStyle">Sample Text</span>
<pre>myStyle={{myStyle}}</pre>
style.css
span {
  color: black;}
protractor.js
var colorSpan = element(by.css('span'));

it('should check ng-style', Function() {
  expect(colorSpan.getCssValue('color')).toBe('rgba(0, 0, 0, 1)');
  element(by.css('input[value=\'set color\']')).click();
  expect(colorSpan.getCssValue('color')).toBe('rgba(255, 0, 0, 1)');
  element(by.css('input[value=clear]')).click();
  expect(colorSpan.getCssValue('color')).toBe('rgba(0, 0, 0, 1)');});


AngularJS: API: ng/directive/ngSubmit

ngSubmit

  1. - directive in module ng

让Angular表达式可以绑定到onsubmit事件上。

此外，它可以防止默认动作(这对表单意味着向服务器发送请求和重新加载当前页)，但只在表单没包含action, data-action或x-action属性时。

指令信息

  • 这个指令执行优先级为0.

用法

  • 作为属性使用:
    <form
  ng-submit="">
...
</form>

参数

参数 | 类型 | 详述
ngSubmit | expression | 用于计算的表达式。 (事件对象存放于$event)

示例

index.html
<script>
  angular.module('submitExample', [])
    .controller('ExampleController', ['$scope', Function($scope) {
      $scope.list = [];
      $scope.text = 'hello';
      $scope.submit = Function() {
        if ($scope.text) {
          $scope.list.push(this.text);
          $scope.text = '';
        }
      };
    }]);
</script>
<form ng-submit="submit()" ng-controller="ExampleController">
  Enter text and hit enter:
  <input Type="text" ng-model="text" name="text" />
  <input Type="submit" id="submit" value="Submit" />
  <pre>list={{list}}</pre>
</form>
protractor.js
it('should check ng-submit', Function() {
  expect(element(by.binding('list')).getText()).toBe('list=[]');
  element(by.css('#submit')).click();
  expect(element(by.binding('list')).getText()).toContain('hello');
  expect(element(by.model('text')).getAttribute('value')).toBe('');});
it('should ignore empty strings', Function() {
  expect(element(by.binding('list')).getText()).toBe('list=[]');
  element(by.css('#submit')).click();
  element(by.css('#submit')).click();
  expect(element(by.binding('list')).getText()).toContain('hello');
 });


AngularJS: API: ng/directive/ngSwitch

ngSwitch

  1. - directive in module ng

ngSwitch指令用于根据域表达式在你的模板上按条件切换DOM结构。元素内使用ngSwitch而非ngSwitchWhen或ngSwitchDefault指令的地方会保留在模板中的位置。

这个指令的工作方法类似于ngInclude，然而，使用下载的模板代码替换(或从模板缓冲中载入)，ngSwitch只从嵌套元素中简单选择一个，并让根据将匹配表达式值的元素显示出来。换句话说，你定义一个包含元素 (在你放置指令的地方),放置一个表达式在 on="..." 属性 (或 ng-switch="..." 属性)上，然后在指令内定义任何内部元素，并放置when属性到每个元素上。when属性用于告诉ngSwitch当表达式计算时显示哪个元素。如果匹配的表达式没在when属性中找到，会显示default属性对应的元素。

注意用于匹配的属性值不能是表达式。他们被解释为字符串值进行匹配。例如，ng-switch-when="someVal" 将匹配字符串 "someVal" ，而不会对应为表达式$scope.someVal的值。

指令信息

  • 这个指令会创建新的作用域(scope)。
  • 这个指令执行优先级为800.

用法

<ANY ng-switch="expression">
  <ANY ng-switch-when="matchValue1">...</ANY>
  <ANY ng-switch-when="matchValue2">...</ANY>
  <ANY ng-switch-default>...</ANY>
</ANY>

动画

enter - 在ngSwitch的内容改变并匹配到内部子元素后发生。

leave - 只在ngSwitch内容改变后并在原内容从DOM移除前发生。

点击这里 了解更多关于涉及动画的步骤。

参数

参数 类型 详述
ngSwitch | on *

用于匹配 ng-switch-when的表达式。在子元素可添加：

  • ngSwitchWhen: 状况匹配语句。如果匹配到这个状况就显示。如果一次匹配到多个，那所有匹配到的元素都会显示。
  • ngSwitchDefault: 当没有状况匹配到时的默认状况。如果有多个默认状况，所有都会显示。

示例

index.html
<div ng-controller="ExampleController">
  <select ng-model="selection" ng-options="item for item in items">
  </select>
  <tt>selection={{selection}}</tt>
  <hr/>
  <div class="animate-switch-container"
    ng-switch on="selection">
      <div class="animate-switch" ng-switch-when="settings">Settings Div</div>
      <div class="animate-switch" ng-switch-when="home">Home Span</div>
      <div class="animate-switch" ng-switch-default>default</div>
  </div>
</div>
script.js
angular.module('switchExample', ['ngAnimate'])
  .controller('ExampleController', ['$scope', Function($scope) {
    $scope.items = ['settings', 'home', 'other'];
    $scope.selection = $scope.items[0];
  }]);
animations.css
.animate-switch-container {
  position:relative;
  background:white;
  border:1px solid black;
  height:40px;
  overflow:hidden;}

.animate-switch {
  padding:10px;}

.animate-switch.ng-animate {
  -webkit-transition:all cubic-bezier(0.250, 0.460, 0.450, 0.940) 0.5s;
  transition:all cubic-bezier(0.250, 0.460, 0.450, 0.940) 0.5s;

  position:absolute;
  top:0;
  left:0;
  right:0;
  bottom:0;}

.animate-switch.ng-leave.ng-leave-active,.animate-switch.ng-enter {
  top:-50px;}.animate-switch.ng-leave,.animate-switch.ng-enter.ng-enter-active {
  top:0;}
protractor.js
var switchElem = element(by.css('[ng-switch]'));
var select = element(by.model('selection'));

it('should start in settings', Function() {
  expect(switchElem.getText()).toMatch(/Settings Div/);});
it('should change to home', Function() {
  select.all(by.css('option')).get(1).click();
  expect(switchElem.getText()).toMatch(/Home Span/);});
it('should select default', Function() {
  select.all(by.css('option')).get(2).click();
  expect(switchElem.getText()).toMatch(/default/);});


AngularJS: API: ng/directive/ngTransclude

ngTransclude

  1. - directive in module ng

指令用于标记紧挨着的使用嵌入式的父指令中包含的DOM的插入点。

在内容插入前，这个指令所在元素的任何已存在内容会被清除。

指令信息

  • 这个指令执行优先级为0.

用法

  • 作为元素使用: (这个指令能用于自定义元素，但要注意IE限制)。
    <ng-transclude>
...
</ng-transclude>
  • 作为属性使用:
    <ANY>
...
</ANY>
  • 作为CSS类使用:
    <ANY class=""> ... </ANY>

示例

index.html
<script>
  angular.module('transcludeExample', [])
   .Directive('pane', Function(){
      return {
        restrict: 'E',
        transclude: true,
        scope: { title:'@' },
        template: '<div style="border: 1px solid black;">' +
                    '<div style="background-color: gray">{{title}}</div>' +
                    '<ng-transclude></ng-transclude>' +
                  '</div>'
      };
  })
  .controller('ExampleController', ['$scope', Function($scope) {
    $scope.title = 'Lorem Ipsum';
    $scope.text = 'Neque porro quisquam est qui dolorem ipsum quia dolor...';
  }]);
</script>
<div ng-controller="ExampleController">
  <input ng-model="title"><br>
  <textarea ng-model="text"></textarea> <br/>
  <pane title="{{title}}">{{text}}</pane>
</div>
protractor.js
it('should have transcluded', Function() {
  var titleElement = element(by.model('title'));
  titleElement.clear();
  titleElement.sendKeys('TITLE');
  var textElement = element(by.model('text'));
  textElement.clear();
  textElement.sendKeys('TEXT');
  expect(element(by.binding('title')).getText()).toEqual('TITLE');
  expect(element(by.binding('text')).getText()).toEqual('TEXT');});


AngularJS: API: ng/directive/ngValue

ngValue

  1. - directive in module ng

绑定给定的表达式到input[select]或 input[radio]的值上，这样当元素被选中时， 元素的ngModel 会被设为当前绑定的值。

ngValue 经常用于使用ng-repeat动态生成单选按钮列表，如下面所示。

指令信息

  • 这个指令执行优先级为0.

用法

  • 作为属性使用:
    <input
  [ng-value=""]>
...
</input>

参数

Param | 类型 | 详述
ngValue (可选) | string | Angular表达式，绑定到input 元素的value 属性的值。

示例

index.html
<script>
   angular.module('valueExample', [])
     .controller('ExampleController', ['$scope', Function($scope) {
       $scope.names = ['pizza', 'unicorns', 'robots'];
       $scope.my = { favorite: 'unicorns' };
     }]);
</script>
 <form ng-controller="ExampleController">
   <h2>Which is your favorite?</h2>
     <label ng-repeat="name in names" for="{{name}}">
       {{name}}
       <input Type="radio"
              ng-model="my.favorite"
              ng-value="name"
              id="{{name}}"
              name="favorite">
     </label>
   <div>You chose {{my.favorite}}</div>
 </form>
protractor.js
var favorite = element(by.binding('my.favorite'));

it('should initialize to model', Function() {
  expect(favorite.getText()).toContain('unicorns');});
it('should bind the values to the inputs', Function() {
  element.all(by.model('my.favorite')).get(0).click();
  expect(favorite.getText()).toContain('pizza');});


AngularJS: API: ng/directive/script

script

  1. - directive in module ng

载入<script>元素内容到$templateCache，这样模板就能通过ngInclude和 ngView，或directives来使用。 <script>元素的类型必须设定为text/ng-template，并且必须通过元素的id来给出模板的缓冲名称，这样就能用于指令的templateUrl了。

指令信息

  • 这个指令执行优先级为0.

用法

  • 作为元素使用:
    <script
  Type=""
  id="">...</script>

参数

参数 | 类型 | 详述
Type | string | 必须设为'text/ng-template'.
id | string | 模板的缓冲名称。

示例

index.html
<script Type="text/ng-template" id="/tpl.html">
  Content of the template.
</script>

<a ng-click="currentTpl='/tpl.html'" id="tpl-link">Load inlined template</a>
<div id="tpl-content" ng-include src="currentTpl"></div>
protractor.js
it('should load template defined inside script tag', Function() {
  element(by.css('#tpl-link')).click();
  expect(element(by.css('#tpl-content')).getText()).toMatch(/Content of the template/);});


AngularJS: API: ng/directive/select

select

  1. - directive in module ng

带有angular数据绑定功能的HTML SELECT 元素。

ngOptions

ngOptions 属性可用于动态生成<option>元素列表，当对<select>元素使用数组，或者是 ngOptions可解析的表达式计算得到的对象。

当<select>菜单中的一项被选中时，数组元素或对象属性作为被选中的选项绑定到模型的 ngModel指令。

注意： ngModel通过引用比较，而非值比较。这在使用对象数组 绑定时很重要。参见示例in this jsfiddle.

此外，设置为空字符串值的单个硬编码的<option>元素可以嵌套到 <select>元素中。这个元素将表现为null或 "not selected"选项。参见下面的示例演示。

注意： ngOptions 为<option>提供了一个迭代器工厂用于替代 ngRepeat，在你想让 select模型绑定到非字符串值时。这是因为一个选项元素只能被绑定到一个字符串值上。

指令信息

  • 这个指令执行优先级为0.

用法

  • 作为元素使用:
    <select
  ng-model=""
  [name=""]
  [required=""]
  [ng-required=""]
  [ng-options=""]>
...
</select>

参数

参数 类型 详述
ngModel string

声明用于数据绑定的Angular表达式。

name
(可选)
string

发布到表单下的控件的属性名称。

required
(可选)
string

控件只有输入值才被认为有效。

ngRequired
(可选)
string

当ngRequired表达式等于true时，添加required属性和required验证约束到元素上。 使用ngRequired替换required，当你想数据绑定到required属性上时。

ngOptions
(可选)
comprehension_expression

下列形式之一：

  • 当数据源为数组：
    • label for value in array
    • select as label for value in array
    • label group by group for value in array
    • select as label group by group for value in array track by trackexpr
  • 当数据源为对象：
    • label for (key , value) in Object
    • select as label for (key , value) in Object
    • label group by group for (key, value) in Object
    • select as label group by group for (key, value) in Object

这里:

  • array / Object:用于进行迭代的结果为一个数组或对象的表达式。
  • value: 局部变量，迭代期间指向array中的每个条目，或Object的每个属性值。
  • key: 局部变量，迭代期间指向Object的属性名称。
  • label: 这个表达式的结果作为<option>元素的标签。表达式通常指向value 变量 (如 value.propertyName)。
  • select:这个表达式的结果会绑定到父<select>元素的模型上。如果未指定，select表达式默认为value。
  • group: 这个表达式的结果会被用于使用<optgroup> DOM 元素分组选项。
  • trackexpr: 应用于对象数组。表达式的结果被用唯一标识数组中的对象。 trackexpr通常指向value变量(如value.propertyName)。

示例

index.html
<script>
angular.module('selectExample', [])
  .controller('ExampleController', ['$scope', Function($scope) {
    $scope.colors = [
      {name:'black', shade:'dark'},
      {name:'white', shade:'light'},
      {name:'red', shade:'dark'},
      {name:'blue', shade:'dark'},
      {name:'yellow', shade:'light'}
    ];
    $scope.myColor = $scope.colors[2]; // red
  }]);
</script>
<div ng-controller="ExampleController">
  <ul>
    <li ng-repeat="color in colors">
      Name: <input ng-model="color.name">
      [<a href ng-click="colors.splice($index, 1)">X</a>]
    </li>
    <li>
      [<a href ng-click="colors.push({})">add</a>]
    </li>
  </ul>
  <hr/>
  Color (null not allowed):
  <select ng-model="myColor" ng-options="color.name for color in colors"></select><br>

  Color (null allowed):
  <span  class="nullable">
    <select ng-model="myColor" ng-options="color.name for color in colors">
      <option value="">-- choose color --</option>
    </select>
  </span><br/>

  Color grouped by shade:
  <select ng-model="myColor" ng-options="color.name group by color.shade for color in colors">
  </select><br/>

  Select <a href ng-click="myColor = { name:'not in list', shade: 'other' }">bogus</a>.<br>
  <hr/>
  Currently selected: {{ {selected_color:myColor}  }}
  <div style="border:solid 1px black; height:20px"
       ng-style="{'background-color':myColor.name}">
  </div>
</div>
protractor.js
it('should check ng-options', Function() {
  expect(element(by.binding('{selected_color:myColor}')).getText()).toMatch('red');
  element.all(by.model('myColor')).first().click();
  element.all(by.css('select[ng-model="myColor"] option')).first().click();
  expect(element(by.binding('{selected_color:myColor}')).getText()).toMatch('black');
  element(by.css('.nullable select[ng-model="myColor"]')).click();
  element.all(by.css('.nullable select[ng-model="myColor"] option')).first().click();
  expect(element(by.binding('{selected_color:myColor}')).getText()).toMatch('null');});


AngularJS: API: ng/directive/textarea

textarea

  1. - directive in module ng

可进行angular数据绑定的HTML textarea 元素。数据绑定和验证元素属性完全与input 元素相同。

指令信息

  • 这个指令执行优先级为0.

用法

  • 作为元素使用:
    <textarea
  ng-model=""
  [name=""]
  [required=""]
  [ng-required=""]
  [ng-minlength=""]
  [ng-maxlength=""]
  [ng-pattern=""]
  [ng-change=""]
  [ng-trim=""]>
...
</textarea>

参数

参数 | 类型 | 详述
ngModel | string | 声明用于数据绑定的Angular表达式。
name (可选) | string | 发布到表单下的控件的属性名称。
required (可选) | string | 如果未输入值就设置 required验证错误键。
ngRequired (可选) | string | 如果值为true则置为 required 属性和 required验证约束。当你想数据绑定到 required属性时使用ngRequired替代required。
ngMinlength (可选) | number | 如果值短于minlength则设置minlength验证错误键。
ngMaxlength (可选) | number | 如果值长于maxlength则设置maxlength验证错误键。
ngPattern (可选) | string | 如果值不匹配正则表达式则设置pattern验证错误键。 值可以是/regexp/形式的内嵌正则表达式，或者是用regexp定义在scope中的表达式。
ngChange (可选) | string | Angular表达式，当输入元素通过用户交互方式发生输入变化时会执行这个表达式。
ngTrim (可选) | boolean | 如果设置为false，Angular将不自动去除输入内容的空格。


AngularJS: API: ng/filter

Filter components in ng

名称 | 描述
Filter | Selects a subset of items from array and returns it as a new array.
currency | Formats a number as a currency (ie $1,234.56). When no currency symbol is provided, default symbol for current locale is used.
number | Formats a number as text.
date | Formats date to a string based on the requested format.
json | Allows you to convert a JavaScript object into JSON string.
lowercase | Converts string to lowercase.
uppercase | Converts string to uppercase.
limitTo | Creates a new array or string containing only a specified number of elements. The elements are taken from either the beginning or the end of the source array or string, as specified by the value and sign (positive or negative) of limit.
orderBy | Orders a specified array by the expression predicate. It is ordered alphabetically for strings and numerically for numbers. 注意： if you notice numbers are not being sorted correctly, make sure they are actually being saved as numbers and not strings.


AngularJS: API: ng/filter/currency

currency

  1. - filter in module ng

格式化数字为货币形式 (如 $1,234.56)。当提供的不是货币形式时，会使用本地化默认形式。

用法

用于HTML模板绑定

{{ currency_expression | currency : symbol}}

用于JavaScript

$filter('currency')(amount, symbol)

参数

参数 | 类型 | 详述
amount | number | 用于过滤器的输入。
symbol (可选) | string | 用于显示的货币形式或标识。

返回值

string

格式化的数值。

示例

index.html
<script>
  angular.module('currencyExample', [])
    .controller('ExampleController', ['$scope', Function($scope) {
      $scope.amount = 1234.56;
    }]);
</script>
<div ng-controller="ExampleController">
  <input Type="number" ng-model="amount"> <br>
  default currency symbol ($): <span id="currency-default">{{amount | currency}}</span><br>
  custom currency identifier (USD$): <span>{{amount | currency:"USD$"}}</span>
</div>
protractor.js
it('should init with 1234.56', Function() {
  expect(element(by.id('currency-default')).getText()).toBe('$1,234.56');
  expect(element(by.binding('amount | currency:"USD$"')).getText()).toBe('USD$1,234.56');});
it('should update', Function() {
  if (browser.params.browser == 'safari') {
    // Safari does not understand the minus key. See
    // https://github.com/angular/protractor/issues/481
    return;
  }
  element(by.model('amount')).clear();
  element(by.model('amount')).sendKeys('-1234');
  expect(element(by.id('currency-default')).getText()).toBe('($1,234.00)');
  expect(element(by.binding('amount | currency:"USD$"')).getText()).toBe('(USD$1,234.00)');});


AngularJS: API: ng/filter/date

date

  1. - filter in module ng

格式化date到字符串，基于format的要求。

format 字符串由以下元素组合而成：

  • 'yyyy': 4位数字的年份(如AD 1 => 0001, AD 2010 => 2010)
  • 'yy': 2位数字的年份，范围为(00-99)。(如AD 2001 => 01, AD 2010 => 10)
  • 'y': 1位数字的年份，例如 (AD 1 => 1, AD 199 => 199)
  • 'MMMM': 月份 (January-December)
  • 'MMM': 月份 (Jan-Dec)
  • 'MM': 月份, padded (01-12)
  • 'M': 月份 (1-12)
  • 'dd': 日，范围为(01-31)
  • 'd': 日 (1-31)
  • 'EEEE': 星期,(Sunday-Saturday)
  • 'EEE': 星期, (Sun-Sat)
  • 'HH': 小时, 范围为(00-23)
  • 'H': 小时 (0-23)
  • 'hh': am/pm形式的小时, 范围为(01-12)
  • 'h': am/pm形式的小时, (1-12)
  • 'mm': 分钟,范围为 (00-59)
  • 'm': 分钟 (0-59)
  • 'ss': 秒, 范围为 (00-59)
  • 's': 秒 (0-59)
  • '.sss' or ',sss': 毫秒,范围为 (000-999)
  • 'a': am/pm 标记
  • 'Z': 4 位数字的时区偏移(+符号)(-1200-+1200)
  • 'ww': ISO-8601 年内的周数 (00-53)

  • 'w': ISO-8601 年内的周数 (0-53)

    format 字符串也可以是以下预定义的本地化格式之一:

  • 'medium': 等于en_US本地化后的 'MMM d, y h:mm:ss a' (如：Sep 3, 2010 12:05:08 pm)

  • 'short': 等于en_US本地化后的 'M/d/yy h:mm a' (如： 9/3/10 12:05 pm)
  • 'fullDate': 等于en_US本地化后的 'EEEE, MMMM d, y' (如： Friday, September 3, 2010)
  • 'longDate': 等于en_US本地化后的 'MMMM d, y' (如： September 3, 2010)
  • 'mediumDate': 等于en_US本地化后的 'MMM d, y' (如： Sep 3, 2010)
  • 'shortDate': 等于en_US本地化后的 'M/d/yy' (如： 9/3/10)
  • 'mediumTime': 等于en_US本地化后的 'h:mm:ss a' (如： 12:05:08 pm)

  • 'shortTime': 等于en_US本地化后的 'h:mm a' (如： 12:05 pm)

    format 字符串可以包含固定值。这需要用单引号括起来 (如： "h 'in the morning'")。如果要输出单引号，使序列中使用两个单引号(如： "h 'o''clock'")。

用法

用于HTML模板绑定

{{ date_expression | date : format}}

用于JavaScript

$filter('date')(date, format)

参数

参数 | 类型 | 详述
date | Date number string | 进行日期格式化的日期对象、毫秒(字符串或数字)或符合ISO 8601的日期时间字符串格式(如： yyyy-MM-ddTHH:mm:ss.SSSZ 和它的简短版本，如yyyy-MM-ddTHH:mmZ, yyyy-MM-dd 或 yyyyMMddTHHmmssZ)。如果在字符串中没有指定时区，会使用本地时区的时间。
format (可选) | string | 格式化规则(见描述)。如果没指定，使用mediumDate 。

返回值

string

格式化后的字符串，或输入验证不是日期/毫秒的原始输入内容。

示例

index.html
<span ng-non-bindable>{{1288323623006 | date:'medium'}}</span>:
    <span>{{1288323623006 | date:'medium'}}</span><br>
<span ng-non-bindable>{{1288323623006 | date:'yyyy-MM-dd HH:mm:ss Z'}}</span>:
   <span>{{1288323623006 | date:'yyyy-MM-dd HH:mm:ss Z'}}</span><br>
<span ng-non-bindable>{{1288323623006 | date:'MM/dd/yyyy @ h:mma'}}</span>:
   <span>{{'1288323623006' | date:'MM/dd/yyyy @ h:mma'}}</span><br>
protractor.js
it('should format date', Function() {
  expect(element(by.binding("1288323623006 | date:'medium'")).getText()).
     toMatch(/Oct 2\d, 2010 \d{1,2}:\d{2}:\d{2} (AM|PM)/);
  expect(element(by.binding("1288323623006 | date:'yyyy-MM-dd HH:mm:ss Z'")).getText()).
     toMatch(/2010\-10\-2\d \d{2}:\d{2}:\d{2} (\-|\+)?\d{4}/);
  expect(element(by.binding("'1288323623006' | date:'MM/dd/yyyy @ h:mma'")).getText()).
     toMatch(/10\/2\d\/2010 @ \d{1,2}:\d{2}(AM|PM)/);});


AngularJS: API: ng/filter/filter

Filter

  1. - filter in module ng

从array中选择一个条目子集，并作为一个新数组返回。

用法

用于HTML模板绑定

{{ filter_expression | filter : expression : comparator}}

用于JavaScript

$filter('filter')(array, expression, comparator)

参数

参数 类型 详述
array Array

源数组。

expression string Object function()

从array选择条目时的条件。

可以为以下之一：

  • string:作为表达式计算的字符串，计算结果作为子串匹配array中的内容。array中包含这个字符串的所有字符串或字符串属性对象会返回。字符串前可以放置!表示相反条件。

  • Object: 一个模式对象，用于过滤array中对象的指定属性。例如{name:"M", phone:"1"} 表示返回数据组中属性name 包含 "M" 和属性 phone 包含 "1"的条目。可以使用特殊属性名 $ (as in {$:"text"}) 来匹配对象中的所有属性。这相当于上面描述的使用string进行的子串简单匹配。

  • Function(value): 一个自定义过滤方法的函数。这个函数被每个array中的元素调用。最终结果为返回true的元素的数组。

comparator function(actual, expected) true undefined

用于检测期望值(来自过滤表达式)和实际值(来自数组中的实际对象)是否匹配的比较器。

可以为以下之一：

  • Function(actual, expected): 这个函数会传入对象值和期望值来比较，如果条目返回true就会被包含在过滤结果中。

  • true: Function(actual, expected) { return angular.equals(expected, actual)}的便捷写法。它对期望值和实际值进行强比较。

  • false|undefined: 一个不区分大小写的子串匹配函数的便捷写法。

示例

index.html
<div ng-init="friends = [{name:'John', phone:'555-1276'},
                         {name:'Mary', phone:'800-BIG-MARY'},
                         {name:'Mike', phone:'555-4321'},
                         {name:'Adam', phone:'555-5678'},
                         {name:'Julie', phone:'555-8765'},
                         {name:'Juliette', phone:'555-5678'}]"></div>

Search: <input ng-model="searchText">
<table id="searchTextResults">
  <tr><th>名称</th><th>Phone</th></tr>
  <tr ng-repeat="friend in friends | filter:searchText">
    <td>{{friend.name}}</td>
    <td>{{friend.phone}}</td>
  </tr>
</table><hr>
Any: <input ng-model="search.$"> <br>
Name only <input ng-model="search.name"><br>
Phone only <input ng-model="search.phone"><br>
Equality <input Type="checkbox" ng-model="strict"><br>
<table id="searchObjResults">
  <tr><th>名称</th><th>Phone</th></tr>
  <tr ng-repeat="friendObj in friends | filter:search:strict">
    <td>{{friendObj.name}}</td>
    <td>{{friendObj.phone}}</td>
  </tr>
</table>
protractor.js
var expectFriendNames = Function(expectedNames, key) {
  element.all(by.repeater(key + ' in friends').column(key + '.name')).then(Function(arr) {
    arr.forEach(Function(wd, i) {
      expect(wd.getText()).toMatch(expectedNames[i]);
    });
  });};

it('should search across all fields when filtering with a string', Function() {
  var searchText = element(by.model('searchText'));
  searchText.clear();
  searchText.sendKeys('m');
  expectFriendNames(['Mary', 'Mike', 'Adam'], 'friend');

  searchText.clear();
  searchText.sendKeys('76');
  expectFriendNames(['John', 'Julie'], 'friend');});

it('should search in specific fields when filtering with a predicate object', Function() {
  var searchAny = element(by.model('search.$'));
  searchAny.clear();
  searchAny.sendKeys('i');
  expectFriendNames(['Mary', 'Mike', 'Julie', 'Juliette'], 'friendObj');});
it('should use a equal comparison when comparator is true', Function() {
  var searchName = element(by.model('search.name'));
  var strict = element(by.model('strict'));
  searchName.clear();
  searchName.sendKeys('Julie');
  strict.click();
  expectFriendNames(['Julie'], 'friendObj');});


AngularJS: API: ng/filter/json

json

  1. - filter in module ng

允许你转换一个JavaScript对象到JSON字符串。

这个过滤器常用于调试。使用双花括号的绑定会自动转换成JSON。

用法

用于HTML模板绑定

{{ json_expression | json}}

用于JavaScript

$filter('json')(Object)

参数

参数 | 类型 | 详述
Object | * | 用于过滤的任何JavaScript对象 (包括数组和原始类型)。

返回值

string

JSON字符串。

示例

index.html
<pre>{{ {'name':'value'} | json }}</pre>
protractor.js
it('should jsonify filtered objects', Function() {
  expect(element(by.binding("{'name':'value'}")).getText()).toMatch(/\{\n  "name": ?"value"\n}/);});


AngularJS: API: ng/filter/limitTo

limitTo

  1. - filter in module ng

创建只包含指定数量元素的新数组或字符串。元素可从源数组或字符串的起点或终点开始取，通过limit来指定值和符号(正或负)。

用法

用于HTML模板绑定

{{ limitTo_expression | limitTo : limit}}

用于JavaScript

$filter('limitTo')(input, limit)

参数

参数 | 类型 | 详述
input | Array string | 用于限定的源数组或字符串。
limit | string number | 返回的数组或字符串的长度。如果limit数字为正数，从源数组/字符串开始的limit数量的条目会被复制。如果数字为负数，从源数组/字符串结尾的limit 数量的条目会被复制。如果limit超过array.length会被裁剪。

返回值

Array string

长度为limit的新子数组或子串，如果输入数组小于limit，返回长度会小于limit。

示例

index.html
<script>
  angular.module('limitToExample', [])
    .controller('ExampleController', ['$scope', Function($scope) {
      $scope.numbers = [1,2,3,4,5,6,7,8,9];
      $scope.letters = "abcdefghi";
      $scope.numLimit = 3;
      $scope.letterLimit = 3;
    }]);
</script>
<div ng-controller="ExampleController">
  Limit {{numbers}} to: <input Type="integer" ng-model="numLimit">
  <p>Output numbers: {{ numbers | limitTo:numLimit }}</p>
  Limit {{letters}} to: <input Type="integer" ng-model="letterLimit">
  <p>Output letters: {{ letters | limitTo:letterLimit }}</p>
</div>
protractor.js
var numLimitInput = element(by.model('numLimit'));
var letterLimitInput = element(by.model('letterLimit'));
var limitedNumbers = element(by.binding('numbers | limitTo:numLimit'));
var limitedLetters = element(by.binding('letters | limitTo:letterLimit'));

it('should limit the number array to first three items', Function() {
  expect(numLimitInput.getAttribute('value')).toBe('3');
  expect(letterLimitInput.getAttribute('value')).toBe('3');
  expect(limitedNumbers.getText()).toEqual('Output numbers: [1,2,3]');
  expect(limitedLetters.getText()).toEqual('Output letters: abc');});

it('should update the output when -3 is entered', Function() {
  numLimitInput.clear();
  numLimitInput.sendKeys('-3');
  letterLimitInput.clear();
  letterLimitInput.sendKeys('-3');
  expect(limitedNumbers.getText()).toEqual('Output numbers: [7,8,9]');
  expect(limitedLetters.getText()).toEqual('Output letters: ghi');});

it('should not exceed the maximum size of input array', Function() {
  numLimitInput.clear();
  numLimitInput.sendKeys('100');
  letterLimitInput.clear();
  letterLimitInput.sendKeys('100');
  expect(limitedNumbers.getText()).toEqual('Output numbers: [1,2,3,4,5,6,7,8,9]');
  expect(limitedLetters.getText()).toEqual('Output letters: abcdefghi');});


AngularJS: API: ng/filter/lowercase

lowercase

  1. - filter in module ng

转换字符串为小写形式。

用法

用于HTML模板绑定

{{ lowercase_expression | lowercase}}

用于JavaScript

$filter('lowercase')()


AngularJS: API: ng/filter/number

number

  1. - filter in module ng

格式化数字到文本。

如果输入不是一个数字，返回空字符串。

用法

用于HTML模板绑定

{{ number_expression | number : fractionSize}}

用于JavaScript

$filter('number')(number, fractionSize)

参数

参数 | 类型 | 详述
number | number string | 用于格式化的数字。
fractionSize (可选) | number string | 带小数点的十进制数字。如果未提供，小数的大小取决于当前本地化数字格式。默认本地化值为3。

返回值

string

小数位取整后的数字，每三位使用“,”分隔。

示例

index.html
<script>
  angular.module('numberFilterExample', [])
    .controller('ExampleController', ['$scope', Function($scope) {
      $scope.val = 1234.56789;
    }]);
</script>
<div ng-controller="ExampleController">
  Enter number: <input ng-model='val'><br>
  Default formatting: <span id='number-default'>{{val | number}}</span><br>
  No fractions: <span>{{val | number:0}}</span><br>
  Negative number: <span>{{-val | number:4}}</span>
</div>
protractor.js
 it('should format numbers', Function() {
   expect(element(by.id('number-default')).getText()).toBe('1,234.568');
   expect(element(by.binding('val | number:0')).getText()).toBe('1,235');
   expect(element(by.binding('-val | number:4')).getText()).toBe('-1,234.5679');
 });

 it('should update', Function() {
   element(by.model('val')).clear();
   element(by.model('val')).sendKeys('3374.333');
   expect(element(by.id('number-default')).getText()).toBe('3,374.333');
   expect(element(by.binding('val | number:0')).getText()).toBe('3,374');
   expect(element(by.binding('-val | number:4')).getText()).toBe('-3,374.3330');});


AngularJS: API: ng/filter/orderBy

orderBy

  1. - filter in module ng

通过expression来排序指定的array 。 字符串按字母顺序排序，数字按大小排序。注意：如果你发现数字没被正确排序，请确认它们保存的是数字而不是字符串。

用法

用于HTML模板绑定

{{ orderBy_expression | orderBy : expression : reverse}}

用于JavaScript

$filter('orderBy')(array, expression, reverse)

参数

参数 类型 详述
array Array

用于排序的数组。

expression function(*) string Array.<(function(*)|string)>

一个用于通过比较来决定元素顺序的声明。

可为下列之一：

  • Function: Getter函数。这个函数的结果可使用 <, =, >操作符进行排序。
  • string: 一个Angular表达式，对一个对象求值来排序，如用'name'来对属性名为'name'排序。用可选前缀 + 或 -来确定是正序或倒序 (例如，+name or -name)。
  • Array: 一个函数或字符串声明数组。数组中的第一个声明用于排序，但是当两个条目相等时，会用下一个声明。
reverse
(可选)
boolean

对数组进行反向排序。

返回值

Array

源数组排序后的副本。

示例

index.html
<script>
  angular.module('orderByExample', [])
    .controller('ExampleController', ['$scope', Function($scope) {
      $scope.friends =
          [{name:'John', phone:'555-1212', age:10},
           {name:'Mary', phone:'555-9876', age:19},
           {name:'Mike', phone:'555-4321', age:21},
           {name:'Adam', phone:'555-5678', age:35},
           {name:'Julie', phone:'555-8765', age:29}];
      $scope.predicate = '-age';
    }]);
</script>
<div ng-controller="ExampleController">
  <pre>Sorting predicate = {{predicate}}; reverse = {{reverse}}</pre>
  <hr/>
  [ <a href="" ng-click="predicate=''">unsorted</a> ]
  <table class="friend">
    <tr>
      <th><a href="" ng-click="predicate = 'name'; reverse=false">名称</a>
          (<a href="" ng-click="predicate = '-name'; reverse=false">^</a>)</th>
      <th><a href="" ng-click="predicate = 'phone'; reverse=!reverse">Phone Number</a></th>
      <th><a href="" ng-click="predicate = 'age'; reverse=!reverse">Age</a></th>
    </tr>
    <tr ng-repeat="friend in friends | orderBy:predicate:reverse">
      <td>{{friend.name}}</td>
      <td>{{friend.phone}}</td>
      <td>{{friend.age}}</td>
    </tr>
  </table>
</div>

也可以手工调用orderBy过滤器，通过注入$filter，使用$filter('orderBy')获取过滤器实例，然后使用所需参数调用过滤器实例。

示例:

index.html
<div ng-controller="Ctrl">
  <table class="friend">
    <tr>
      <th><a href="" ng-click="reverse=false;order('name', false)">名称</a>
        (<a href="" ng-click="order('-name',false)">^</a>)</th>
      <th><a href="" ng-click="reverse=!reverse;order('phone', reverse)">Phone Number</a></th>
      <th><a href="" ng-click="reverse=!reverse;order('age',reverse)">Age</a></th>
    </tr>
    <tr ng-repeat="friend in friends">
      <td>{{friend.name}}</td>
      <td>{{friend.phone}}</td>
      <td>{{friend.age}}</td>
    </tr>
  </table>
</div>
script.js
angular.module('orderByExample', [])
  .controller('ExampleController', ['$scope', '$filter', Function($scope, $filter) {
    var orderBy = $filter('orderBy');
    $scope.friends = [
      { name: 'John',    phone: '555-1212',    age: 10 },
      { name: 'Mary',    phone: '555-9876',    age: 19 },
      { name: 'Mike',    phone: '555-4321',    age: 21 },
      { name: 'Adam',    phone: '555-5678',    age: 35 },
      { name: 'Julie',   phone: '555-8765',    age: 29 }
    ];
    $scope.order = Function(predicate, reverse) {
      $scope.friends = orderBy($scope.friends, predicate, reverse);
    };
    $scope.order('-age',false);
  }]);


AngularJS: API: ng/filter/uppercase

uppercase

  1. - filter in module ng

转换字符串到大写形式。

用法

用于HTML模板绑定

{{ uppercase_expression | uppercase}}

用于JavaScript

$filter('uppercase')()


AngularJS: API: ng/function

Function components in ng

名称 描述
angular.lowercase

转换指定的字符串到小写。
angular.uppercase

Converts the specified string to uppercase.
angular.forEach

Invokes the iterator function once for each item in obj collection, which can be either an object or an array. The iterator function is invoked with iterator(value, key), where value is the value of an object property or an array element and key is the object property key or array element index. Specifying a context for the function is optional.
angular.extend

Extends the destination object dst by copying all of the properties from the src object(s) to dst. You can specify multiple src objects.
angular.noop

A function that performs no operations. 这个函数在使用函数风格写代码时很有用。

     Function foo(callback) {
       var result = calculateResult();
       (callback || angular.noop)(result);
     }
angular.identity

A function that returns its first argument. This function is useful when writing code in the functional style.
angular.isUndefined

检测引用是否未定义。
angular.isDefined

检测引用是否已定义。
angular.isObject

检测引用是否为一个Object. Unlike typeof in JavaScript, nulls are not considered to be objects. Note that JavaScript arrays are objects.
angular.isString

检测引用是否是一个 String.
angular.isNumber

检测引用是否是一个 Number.
angular.isDate

检测值是否为日期。
angular.isArray

检测引用是否为一个Array.
angular.isFunction

检测引用是否是一个 Function.
angular.isElement

检测引用是否为一个DOM元素（或是封装的jQuery元素）。
angular.copy

Creates a deep copy of source, which should be an object or an array.
angular.equals

Determines if two objects or two values are equivalent. Supports value types, regular expressions, arrays and objects.
angular.bind

Returns a function which calls function fn bound to self (self becomes the this for fn). You can supply optional args that are prebound to the function. This feature is also known as partial application, as distinguished from function currying.
angular.toJson

Serializes input into a JSON-formatted string. Properties with leading $$ characters will be stripped since angular uses this notation internally.
angular.fromJson

反序列化JSON字符串。
angular.bootstrap

Use this function to manually start up angular application.
angular.injector

Creates an injector function that can be used for retrieving services as well as for 依赖注入 (see 依赖注入).
angular.element

Wraps a raw DOM element or HTML string as a jQuery element.
angular.module

The angular.module is a global place for creating, registering and retrieving Angular modules. All modules (angular core or 3rd party) that should be available to an application must be registered using this mechanism.


AngularJS: API: ng/function/angular.bind

angular.bind

  1. - function in module ng

返回将调用函数fn绑定到self的函数 (self成为fn的this )。你可以提供可选的 args预绑定到函数。此功能也被称为 partial application(偏函数应用)，区别于 function currying(函数加里化)。
译者注：概念请参见函数Currying和Partial Application的比较

用法

angular.bind(self, fn, args);

参数

参数 | 类型 | 详述
self | Object | fn运算环境的上下文。
fn | function() | 被绑定的函数。
args | * | 预绑定到fn函数调用的可选参数。

返回值

function()

用所有指定绑定信息封装fn的函数。


AngularJS: API: ng/function/angular.bootstrap

angular.bootstrap

  1. - function in module ng

使用这个函数手工启动angular应用。

参见: Bootstrap

注意基于端到端测试的Protractor不能使用这个函数手工启动。它必须使用 ngApp。

Angular会检测是否它被多次载入到浏览器，并且只允许第一次载入的脚本被启动，且会对之后的每次脚本报出一个WARNING到浏览器控制台。这防止了应用中奇怪的结果，在多个Angular实例试图处理DOM时。

<!doctype html>
<html>
<body>
<div ng-controller="WelcomeController">
  {{greeting}}
</div>

<script src="angular.js"></script>
<script>
  var app = angular.module('demo', [])
  .controller('WelcomeController', Function($scope) {
      $scope.greeting = 'Welcome!';
  });
  angular.bootstrap(document, ['demo']);
</script>
</body>
</html>

用法

angular.bootstrap(element, [modules], [config]);

参数

参数 类型 详述
element DOMElement

angular应用的根DOM元素。
modules
(可选)
 Array<String|Function|Array>=

要载入到应用的模块数组。数组中的每个条目为预定义的模块名称，或一个 (依赖注入标注的)函数，作为运行块被注入调用。参见: modules
config
(可选)
 Object

定义应用配置选项的对象。支持以下的键：

- `strictDi`: 禁用应用的自动Function标注。这是为了帮助寻找会破坏压缩代码的错误。

返回值

auto.$injector

返回这个应用新创建的注入器。


AngularJS: API: ng/function/angular.copy

angular.copy

  1. - function in module ng

创建source的深度复制，可以为一个对象或一个数组。

  • 如果destination没指定，会创建对象或数组的一个复本。
  • 如果提供一个destination，它的所有元素(对于数组)或属性(对于对象)会被删除，然后会把源的所有元素/属性复制过去。
  • 如果source不是一个对象或数组(包括null和undefined)，返回source。
  • 如果source等于'destination'，将抛出一个错误。

用法

angular.copy(source, [destination]);

参数

参数 | 类型 | 详述
source | * | 用于复制的源。可以为任何类型，包括基础类型、 null和 undefined。
destination (可选) | Object Array | 存储复制后的目标。如果提供，必须和source是相同类型。

返回值

*

副本或更新后的destination，如果destination指定的话。

示例

index.html
<div ng-controller="ExampleController">
<form novalidate class="simple-form">
Name: <input Type="text" ng-model="user.name" /><br />
E-mail: <input Type="email" ng-model="user.email" /><br />
Gender: <input Type="radio" ng-model="user.gender" value="male" />male
<input Type="radio" ng-model="user.gender" value="female" />female<br />
<button ng-click="reset()">RESET</button>
<button ng-click="update(user)">SAVE</button>
</form>
<pre>form = {{user | json}}</pre>
<pre>master = {{master | json}}</pre>
</div>

<script>
 angular.module('copyExample')
   .controller('ExampleController', ['$scope', Function($scope) {
     $scope.master= {};

     $scope.update = Function(user) {
       // Example with 1 argument
       $scope.master= angular.copy(user);
     };

     $scope.reset = Function() {
       // Example with 2 arguments
       angular.copy($scope.master, $scope.user);
     };

     $scope.reset();
   }]);
</script>


AngularJS: API: ng/function/angular.element

angular.element

  1. - function in module ng

封装一个原始DOM元素或HTML字符串为一个 jQuery 元素。

如果存在jQuery， angular.element 作为jQuery 函数的别名。如果不存在jQuery，angular.element委托到Angular内建的jQuery子集，称为"jQuery lite" 或 "jqLite."

jqLite是一个微型的、API兼容的jQuery子集，允许Angular在跨浏览器兼容的方式下操纵DOM。jqLite只实现了所需的最常用功能。

要使用jQuery，只要简单的在DOMContentLoaded事件触发前载入即可。

注意： Angular中所有元素引用都用jQuery或jqLite进行了封装，从不会直接引用原始DOM。

Angular的jqLite

jqLite只提供了以下jQuery方法：

  • addClass()
  • after()
  • append()
  • attr()
  • bind() - 不支持namespaces、selectors或eventData
  • children() - 不支持selectors
  • clone()
  • contents()
  • css()
  • data()
  • empty()
  • eq()
  • find() - 只限于根据标签名查找
  • hasClass()
  • html()
  • next() - 不支持selectors
  • on() - 不支持namespaces、selectors或eventData
  • off() - 不支持namespaces、selectors
  • one() - 不支持namespaces、selectors
  • parent() - 不支持selectors
  • prepend()
  • prop()
  • ready()
  • remove()
  • removeAttr()
  • removeClass()
  • removeData()
  • replaceWith()
  • text()
  • toggleClass()
  • triggerHandler() - 传递一个虚拟的事件对象到handlers
  • unbind() - 不支持namespaces
  • val()
  • wrap()

jQuery/jqLite 扩展

Angular同时提供了以下额外的方法和事件到jQuery和jqLite:

事件

  • $destroy - AngularJS拦截所有jqLite/jQuery的DOM销毁api，并在所有DOM 节点被移除时触发这个事件。这可以在它被移除前用于清除任何绑定到DOM元素的第三方内容。

方法

  • controller(name) -获取当前元素或它父亲的控制器。默认获取的控制器与ngController指令相关。如果name 是驼峰式的指令名，这个指令的控制器会被获取到(如： 'ngModel')。
  • injector() - 获取当前元素或它父亲的注入。
  • scope() - 获取当前元素或它父亲的 scope 。
  • isolateScope() - 获取直接附加到当前元素的独立 scope。这个获取器只能用于包含开始一个新的独立域的指令的元素上。在这个元素上调用scope()永远返回原始的非独立域。
  • inheritedData() - 等同于 data(), 但是会遍历DOM直到找到一个值或到达最顶部父元素。

用法

angular.element(element);

参数

参数 | 类型 | 详述
element | string DOMElement | 要被封装到jQuery的HTML字符串或DOM元素。

返回值

Object

jQuery对象。


AngularJS: API: ng/function/angular.equals

angular.equals

  1. - function in module ng

判断两个对象或两个值是否相等。支持值类型、正则表达式、数组和对象。

如果两个对象或值满足下列任一种情况就认为是相等的：

  • 两个对象或值通过了===比较。
  • 两个对象或值是相同类型，并且它们所有属性都用angular.equals比较后相等。
  • 两个值为NaN (在JavaScript中, NaN == NaN结果为false。但是我们这里认定两个NaN是相等的)。
  • 两个值为相同的正则表达式(在JavaScript中, /abc/ == /abc/结果为false。但是我们这里认定两个正则表达式的文本形式相同时为相等)。

在属性比较时，Function类型的属性和名称以$开始的属性会被忽略。

Scope和DOMWindow对象只能使用===比较。

用法

angular.equals(o1, o2);

参数

参数 | 类型 | 详述
o1 | * | 要比较的对象或值。
o2 | * | 要比较的对象或值。

返回值

boolean

如果两个参数相等为True。


AngularJS: API: ng/function/angular.extend

angular.extend

  1. - function in module ng

通过从src对象复制所有属性到dst来扩展目标对象dst。你可以指定多个src对象。

用法

angular.extend(dst, src);

参数

参数 | 类型 | 详述
dst | Object | 目标对象。
src | Object | 源对象。

返回值

Object

dst的引用。


AngularJS: API: ng/function/angular.forEach

angular.forEach

  1. - function in module ng

对obj集合中的每个条目调用一次iterator函数，集合可以是一个对象或数组。 iterator函数通过iterator(value, key)形式调用，其中value是对象属性值或数组元素，key是对象属性键或数组元素索引。函数的context是可选参数。

值得注意的是.forEach不会遍历继承的属性，因为它使用hasOwnProperty方法进行过滤。

     var values = {name: 'misko', gender: 'male'};
     var log = [];
     angular.forEach(values, Function(value, key) {
       this.push(key + ': ' + value);
     }, log);
     expect(log).toEqual(['name: misko', 'gender: male']);

用法

angular.forEach(obj, iterator, [context]);

参数

参数 | 类型 | 详述
obj | Object Array | 要遍历的对象。
iterator | Function | 迭代函数。
context (可选) | Object | 要作为迭代函数上下文(this)的对象。

返回值

Object Array

obj的引用。


AngularJS: API: ng/function/angular.fromJson

angular.fromJson

  1. - function in module ng

反序列化JSON字符串。

用法

angular.fromJson(json);

参数

参数 | 类型 | 详述
json | string | 进行反序列化的JSON字符串。

返回值

Object Array string number

反序列化后得到的对象。


AngularJS: API: ng/function/angular.identity

angular.identity

  1. - function in module ng

一个函数返回它的第一个参数。这个函数在使用函数风格写代码时很有用。

     Function transformer(transformationFn, value) {
       return (transformationFn || angular.identity)(value);
     };

用法

angular.identity();


AngularJS: API: ng/function/angular.injector

angular.injector

  1. - function in module ng

创建一个注入函数，用于通过依赖注入的方式获取服务(参见 依赖注入)。

用法

angular.injector(modules);

参数

参数 | 类型 | 详述
modules | Array.<string|Function> | 模块函数或它们的别名的列表。参见angular.module。 ng模块必须提供。

返回值

function()

注入函数。参见 $injector.

示例

典型用法

  // create an injector
  var $injector = angular.injector(['ng']);

  // use the injector to kick off your application
  // use the type inference to auto inject arguments, or use implicit injection
  $injector.invoke(Function($rootScope, $compile, $document){
    $compile($document)($rootScope);
    $rootScope.$digest();
  });

有时你要从Angular外部访问当前运行的Angular应用程序的注入器。也许，你想在应用启动后注入和编译一些标记，你可以使用独立的injector()添加到JQuery/jqLite元素。参见 angular.element.

这是相当少见的，可能的情况是第三方库作为注入标记。

在下面的例子中，一个包含ng-controller指令的HTML新区块通过JQuery添加到文档末尾。我们随后编译并链接它到当前AngularJS域中。

var $div = $('<div ng-controller="MyCtrl">{{content.label}}</div>');
$(document.body).append($div);

angular.element(document).injector().invoke(Function($compile) {
  var scope = angular.element($div).scope();
  $compile($div)(scope);
});


AngularJS: API: ng/function/angular.isArray

angular.isArray

  1. - function in module ng

检测引用是否为一个Array。

用法

angular.isArray(value);

参数

参数 | 类型 | 详述
value | * | 用于检测的引用。

返回值

boolean

如果value是Array返回True。


AngularJS: API: ng/function/angular.isDate

angular.isDate

  1. - function in module ng

检测值是否为日期。

用法

angular.isDate(value);

参数

参数 | 类型 | 详述
value | * | 用于检测的引用。

返回值

boolean

如果value是Date返回True。


AngularJS: API: ng/function/angular.isDefined

angular.isDefined

  1. - function in module ng

检测引用是否已定义。

用法

angular.isDefined(value);

参数

参数 | 类型 | 详述
value | * | 用于检测的引用。

返回值

boolean

如果value已定义返回True。


AngularJS: API: ng/function/angular.isElement

angular.isElement

  1. - function in module ng

检测引用是否为一个DOM元素（或是封装的jQuery元素）。

用法

angular.isElement(value);

参数

参数 | 类型 | 详述
value | * | 用于检测的引用。

返回值

boolean

如果value是DOM元素（或封装的jQuery元素）返回True。


AngularJS: API: ng/function/angular.isFunction

angular.isFunction

  1. - function in module ng

检测引用是否是一个 Function。

用法

angular.isFunction(value);

参数

参数 | 类型 | 详述
value | * | 用于检测的引用。

返回值

boolean

如果value是一个Function返回True。


AngularJS: API: ng/function/angular.isNumber

angular.isNumber

  1. - function in module ng

检测引用是否是一个 Number。

用法

angular.isNumber(value);

参数

参数 | 类型 | 详述
value | * | 用于检测的引用。

返回值

boolean

如果value是一个Number返回True。


AngularJS: API: ng/function/angular.isObject

angular.isObject

  1. - function in module ng

检测引用是否为一个Object。不同于JavaScript的typeof，null不被认为是对象。注意JavaScript数组是对象。

用法

angular.isObject(value);

参数

参数 | 类型 | 详述
value | * | 用于检测的引用。

返回值

boolean

如果value是一个Object但不是null返回True。


AngularJS: API: ng/function/angular.isString

angular.isString

  1. - function in module ng

检测引用是否是一个 String。

用法

angular.isString(value);

参数

参数 | 类型 | 详述
value | * | 用于检测的引用。

返回值

boolean

如果value是一个String返回True。


AngularJS: API: ng/function/angular.isUndefined

angular.isUndefined

  1. - function in module ng

检测引用是否未定义。

用法

angular.isUndefined(value);

参数

参数 | 类型 | 详述
value | * | 用于检测的引用。

返回值

boolean

如果value未定义返回True。


AngularJS: API: ng/function/angular.lowercase

angular.lowercase

  1. - function in module ng

转换指定的字符串到小写。

用法

angular.lowercase(string);

参数

参数 | 类型 | 详述
string | string | 要转换为小写的字符串。

返回值

string

已变成小写的字符串。


AngularJS: API: ng/function/angular.module

angular.module

  1. - function in module ng

angular.module可在全局位置创建、注册、获取Angular模块。所有模块（angular核心或第三方）都必须使用这个机制注册才能在应用中生效。

当传递两个或多个参数时，会创建一个新模块。如果只传递一个参数，则是获取一个存在的模块（第一个参数指向module）。

模块

一个模块是服务、指令、控制器、过滤器和配置信息的集合。 angular.module用于配置$injector。

// Create a new module
var myModule = angular.module('myModule', []);

// register a new service
myModule.value('appName', 'MyCoolApp');

// configure existing services inside initialization blocks.
myModule.config(['$locationProvider', Function($locationProvider) {
  // Configure existing providers
  $locationProvider.hashPrefix('!');
}]);

然后你可以创建一个注入器，并像这样载入你的模块：

var injector = angular.injector(['ng', 'myModule'])

然而，更可能的是，你可以用ngApp 或angular.bootstrap简化这个过程。

用法

angular.module(name, [requires], [configFn]);

参数

参数 | 类型 | 详述
name | string | 要创建或获取的模块名称。
requires (可选) | !Array.<string>= | 如果指定，会创建一个新模块。如果未指定，会通过进一步配置获取模块。
configFn (可选) | Function= | 模块的可选配置函数。同Module#config().

返回值

module

类型为angular.Module的新模块。


AngularJS: API: ng/function/angular.noop

angular.noop

  1. - function in module ng

一个执行空操作的函数。这个函数在使用函数风格写代码时很有用。

     Function foo(callback) {
       var result = calculateResult();
       (callback || angular.noop)(result);
     }

用法

angular.noop();


AngularJS: API: ng/function/angular.toJson

angular.toJson

  1. - function in module ng

序列化输入到JSON格式字符串。$$字符开始的属性会从angular使用这个符号的内部被剔除。

用法

angular.toJson(obj, [pretty]);

参数

参数 | 类型 | 详述
obj | Object Array Date string number | 要序列化为JSON的输入。
pretty (可选) | boolean | 如果设为true，JSON输出会包含换行和空格。

返回值

string undefined

obj的JSON格式字符串。


AngularJS: API: ng/function/angular.uppercase

angular.uppercase

  1. - function in module ng

将指定字符串转换为大写。

用法

angular.uppercase(string);

参数

参数 | 类型 | 详述
string | string | 要转换为大写的字符串。

返回值

string

转换为大写后的字符串。


AngularJS: API: ng/object

Object components in ng

名称 | 描述
angular.version | An object that contains information about the current AngularJS version. This object has the following properties:


AngularJS: API: ng/object/angular.version

angular.version

  1. - object in module ng

包含当前AngularJS版本信息的对象。这个对象有以下属性：

  • full – {string} – 完整的版本字符串，如"0.9.18"。
  • major – {number} – 主版本号，如"0"。
  • minor – {number} – 次版本号，如"9"。
  • dot – {number} – 小版本号，如"18".
  • codeName – {string} – 发行的代码名称，如"jiggling-armfat"。


AngularJS: API: ng/provider

Provider components in ng

名称 描述
$animateProvider

Default implementation of $animate that doesn't perform any animations, instead just synchronously performs DOM updates and calls done() callbacks.
$compileProvider
$controllerProvider

The $controller service is used by Angular to create new controllers.
$filterProvider

Filters are just functions which transform input to an output. However filters need to be Dependency Injected. To achieve this a filter definition consists of a factory function which is annotated with dependencies and is responsible for creating a filter function.
$httpProvider

Use $httpProvider to change the default behavior of the $http service.
$interpolateProvider

Used for configuring the interpolation markup. Defaults to {{ and }}.
$locationProvider

Use the $locationProvider to configure how the application deep linking paths are stored.
$logProvider

Use the $logProvider to configure how the application logs messages
$parseProvider

$parseProvider can be used for configuring the default behavior of the $parse service.
$rootScopeProvider

Provider for the $rootScope service.
$sceDelegateProvider

The $sceDelegateProvider provider allows developers to configure the $sceDelegate service. This allows one to get/set the whitelists and blacklists used to ensure that the URLs used for sourcing Angular templates are safe. Refer $sceDelegateProvider.resourceUrlWhitelist and $sceDelegateProvider.resourceUrlBlacklist
$sceProvider

The $sceProvider provider allows developers to configure the $sce service.

  • enable/disable Strict Contextual Escaping (SCE) in a module
  • override the default implementation with a custom delegate


AngularJS: API: ng/provider/$animateProvider

$animateProvider

  1. - $animate
  2. - provider in module ng

$animate的默认实现，但不执行任何动画，而只是同步进行执行DOM更新和done()回调调用。

为了使用动画请加载ngAnimate模块。

要看功能实现请参见src/ngAnimate/animate.js。

方法

  • register(name, factory);

    注册一个新的可注入动画工厂函数。工厂函数生成动画对象，它包含实现动画的每个事件的回调函数。

    • eventFn: Function(Element, doneFunction) Element为要进行动画的元素，doneFunction在元素动画完成后被调用。如果返回函数，动画服务会使用这个函数取消动画，在取消事件被触发时。
      return {
    eventFn : Function(element, done) {
      //code to run the animation
      //once complete, then run done()
      return Function cancellationFunction() {
        //code to cancel the animation
      }
    }
  }

    参数

    参数 类型 详述
    name string

    动画名称。
    factory Function

    执行后返回动画对象的工厂函数。

  • classNameFilter([expression]);

    设置和（或）返回用于执行动画时检查的CSS类正则表达式。在启动时classNameFilter值没有设置，因此启用$animate将会在所有元素上尝试执行一个动画。当设置了classNameFilter值后，动画只会在成功匹配过滤表达式的元素上执行。这反过来又可以提高低功率设备以及含有大量的结构操作的应用的表现。

    参数

    参数 类型 详述
    expression
    (可选)
             RegExp

    防止全部动画的用于检查的className表达式。

    返回值

    RegExp

    当前CSS className表达式值。如果为空表示没有表达式值。


AngularJS: API: ng/provider/$compileProvider

$compileProvider

  1. - $compile
  2. - provider in module ng

用法

$compileProvider();

方法

  • Directive(name, directiveFactory);

    注册一个用于编译的新指令。

    参数

    参数 类型 详述
    name string Object

    驼峰格式的指令名称 (如 ngBind会匹配ng-bind)，或是一个指令集的对象映射表，键是名称，值是工厂。
    directiveFactory function() Array

    一个可注入的指令工厂函数。参见Directive 获取更多信息。

    返回值

    ng.$compileProvider

    用于链式操作的自身。

  • aHrefSanitizationWhitelist([regexp]);

    获取或覆盖默认的正则表达式，用于a[href]消毒过程中的安全urls白名单。

    消毒是一种安全措施旨在防止通过HTML链接进行XSS攻击。

    通过数据绑定指定到a[href]的任何URL将先被归一化，再变成一个绝对URL。之后，URL与 aHrefSanitizationWhitelist正则表达式匹配。如果发现匹配，原始url写入DOM。否则，绝对url加上'unsafe:'前缀字符串后才写入DOM。

    参数

    参数 类型 详述
    regexp
    (可选)
             RegExp

    新的白名单网址正则表达式。

    返回值

    RegExp ng.$compileProvider

    如果无参调用返回当前正则表达式，否则返回用于链式操作的自身。

  • imgSrcSanitizationWhitelist([regexp]);

    获取或覆盖默认的正则表达式，用于img[href]消毒过程中的安全urls白名单。

    消毒是一种安全措施旨在防止通过HTML链接进行XSS攻击。

    通过数据绑定指定到img[href]的任何URL将先被归一化，再变成一个绝对URL。之后，URL与 aHrefSanitizationWhitelist正则表达式匹配。如果发现匹配，原始url写入DOM。否则，绝对url加上'unsafe:'前缀字符串后才写入DOM。

    参数

    参数 类型 详述
    regexp
    (可选)
             RegExp

    新的白名单网址正则表达式。

    返回值

    RegExp ng.$compileProvider

    如果无参调用返回当前正则表达式，否则返回用于链式操作的自身。


AngularJS: API: ng/provider/$controllerProvider

$controllerProvider

  1. - $controller
  2. - provider in module ng

$controller service 用于Angular创建新的控制器。

这个provider允许控制器通过register方法进行注册。

方法

  • register(name, constructor);

    参数

    参数 类型 详述
    name string Object

    控制器名称，或多个控制器的映射表，其中键是名称，值是构造器。
    constructor function() Array

    控制器构造器fn (可通过数组形式来附加依赖注入标记)。

  • allowGlobals();

    如果调用，允许$controller在window上寻找控制器构造器。

  • register(name);

    参数

    参数 类型 详述
    name string Object

    过滤器函数名，或多个过滤器函数的映射表，其中键是过滤器名称，值是过滤器工厂。

    返回值

    Object

    注册的过滤器实例，或使用映射表方法注册的过滤器映射表。


AngularJS: API: ng/provider/$filterProvider

$filterProvider

  1. - $filter
  2. - provider in module ng

过滤器是只将输入转换到一个输出的函数。然而过滤器需要被依赖注入。要实现的这个过滤器的定义包括一个标注依赖和负责创建一个过滤器函数的工厂函数。

  // Filter registration
  Function MyModule($provide, $filterProvider) {
    // create a service to demonstrate injection (not always needed)
    $provide.value('greet', Function(name){
      return 'Hello ' + name + '!';
    });

    // register a filter factory which uses the
    // greet service to demonstrate DI.
    $filterProvider.register('greet', Function(greet){
      // return the filter function which uses the greet service
      // to generate salutation
      return Function(text) {
        // filters need to be forgiving so check input validity
        return text && greet(text) || text;
      };
    });
  }

过滤器函数在Filter后缀的过滤器名称下用$injector 注册。

  it('should be the same instance', inject(
    Function($filterProvider) {
      $filterProvider.register('reverse', Function(){
        return ...;
      });
    },
    Function($filter, reverseFilter) {
      expect($filter('reverse')).toBe(reverseFilter);
    });

关于angular过滤器如何工作的更多信息，以及如何创建自己的过滤器，参见Angular开发者指南中的Filters 。

方法

  • register(name, fn);

    注册过滤器工厂函数。

    参数

    参数 类型 详述
    name String

    过滤器名称。
    fn Function

    可注入的过滤器工厂函数。


AngularJS: API: ng/provider/$httpProvider

$httpProvider

  1. - $http
  2. - provider in module ng

使用$httpProvider改变$http服务的默认行为。

属性

  • defaults

    包含所有$http请示默认值的对象。

    • defaults.xsrfCookieName - {string} - 包含XSRF令牌的cookie名称。默认值为'XSRF-TOKEN'。

    • defaults.xsrfHeaderName - {string} - 使用XSRF填充的HTTP头名称。默认值为'X-XSRF-TOKEN'。

    • defaults.headers - {Object} - 所有$http请求的默认头。参考$http的设置默认头文档。

      • defaults.headers.common
      • defaults.headers.post
      • defaults.headers.put
      • defaults.headers.patch


AngularJS: API: ng/provider/$interpolateProvider

$interpolateProvider

  1. - $interpolate
  2. - provider in module ng

用于配置插值标记。默认为{{和}}。

用法

$interpolateProvider();

方法

  • startSymbol([value]);

    表示字符串中的插值表达式开始的符号。默认为{{。

    参数

    参数 类型 详述
    value
    (可选)
            string

    用于设置开始符号的新值。

    返回值

    string self

    getter访问时返回当前符号，setter时返回自身。

  • endSymbol([value]);

    表示字符串中的插值表达式结束的符号。默认为}}。

    参数

    参数 类型 详述
    value
    (可选)
            string

    用于设置结束符号的新值。

    返回值

    string self

    getter访问时返回当前符号，setter时返回自身。

示例

index.html
<script>
var customInterpolationApp = angular.module('customInterpolationApp', []);

customInterpolationApp.config(Function($interpolateProvider) {
  $interpolateProvider.startSymbol('//');
  $interpolateProvider.endSymbol('//');});

customInterpolationApp.controller('DemoController', Function() {
    this.label = "This binding is brought you by // interpolation symbols.";});
</script>
<div ng-app="App" ng-controller="DemoController as demo">
  //demo.label//
</div>
protractor.js
it('should interpolate binding with custom symbols', Function() {
expect(element(by.binding('demo.label')).getText()).toBe('This binding is brought you by // interpolation symbols.');});


AngularJS: API: ng/provider/$locationProvider

$locationProvider

  1. - $location
  2. - provider in module ng

使用$locationProvider配置如何存储应用深度链接路径。

方法

  • hashPrefix([prefix]);

    参数

    参数 类型 详述
    prefix
    (可选)
             string

    哈希部分的前缀（含路径和搜索）

    返回值

    *

    如果作为getter使用返回当前值，如果作为setter使用返回自身（用于链式操作）。

  • html5Mode([mode]);

    参数

    参数 类型 详述
    mode
    (可选)
             boolean

    如果有效则使用HTML5的策略。

    返回值

    *

    如果作为getter使用返回当前值，如果作为setter使用返回自身（用于链式操作）。


AngularJS: API: ng/provider/$logProvider

$logProvider

  1. - $log
  2. - provider in module ng

使用$logProvider配置应用如果记录日志信息。

方法

  • debugEnabled([flag]);

    参数

    参数 类型 详述
    flag
    (可选)
             boolean

    允许或禁止调试级别的信息。

    返回值

    *

    如果作为getter使用返回当前值，如果作为setter使用返回自身（用于链式操作）。


AngularJS: API: ng/provider/$parseProvider

$parseProvider

  1. - $parse
  2. - provider in module ng

$parseProvider 能用于配置$parse 服务的默认行为。

用法

$parseProvider();


AngularJS: API: ng/provider/$rootScopeProvider

$rootScopeProvider

  1. - $rootScope
  2. - provider in module ng

$rootScope服务的提供者。

方法

  • digestTtl(limit);

    设置$digest的数字来指出迭代域尝试执行的次数，在放弃和假设模型是不稳定的之前。

    当前默认为10次迭代。

    在复杂的应用程序中可能$watch之间的依赖将导致一些digest迭代。然而，如果应用程序需要比默认10次更多的digest迭代来稳定模型，你应该查清是什么导致模型在digest时不断改变。

    增加TTL会带来性能的影响，所以你不应该在无正当理由下改变它。

    参数

    参数 类型 详述
    limit number

    digest迭代次数。


AngularJS: API: ng/provider/$sceDelegateProvider

$sceDelegateProvider

  1. - $sceDelegate
  2. - provider in module ng

$sceDelegateProvider提供者允许开发者配置$sceDelegate服务。它允许一个get/set 白名单和黑名单用于确保使用的获取Angular模板的URL是安全的。参见$sceDelegateProvider.resourceUrlWhitelist 和 $sceDelegateProvider.resourceUrlBlacklist

对于这个服务在Angular中的一些细节，请阅读Strict Contextual Escaping (SCE)。

示例: 考虑以下情况

  • 你的应用的url主机地址为http://myapp.example.com/
  • 但是你的一些模板存在其它域上，如http://srv01.assets.example.com/, http://srv02.assets.example.com/等。
  • 并且你有一个开放的重定向http://myapp.example.com/clickThru?...。

这种情况下的安全配置可能看起来像：

 angular.module('myApp', []).config(Function($sceDelegateProvider) {
   $sceDelegateProvider.resourceUrlWhitelist([
     // 允许相同来源资源载入。
     'self',
     // 允许从我们的assets域加载。注意 * 和 **之间的不同。
     'http://srv*.assets.example.com/**'
   ]);

   // 黑名单覆盖白名单，这样开放重定向在这会被阻止。
   $sceDelegateProvider.resourceUrlBlacklist([
     'http://myapp.example.com/clickThru**'
   ]);
 });

方法

  • resourceUrlWhitelist([whitelist]);

    Sets/Gets 信任资源URL们的白名单。

    参数

    参数 类型 详述
    whitelist
    (可选)
             Array

    当提供时，使用给出的值替换resourceUrlWhitelist。它必须是一个数组或null。这里会使用该数组的快照，所以数组未来的变化被忽略。

    注意: 一个空的白名单数组会阻止所有URL!

    返回值

    Array

    当前设置的白名单数组。

    没有白名单时的默认值被简单设为['self']，只允许相同来源的资源请求。

  • resourceUrlBlacklist([blacklist]);

    Sets/Gets 信任资源URL们的黑名单。

    参数

    参数 类型 详述
    blacklist
    (可选)
             Array

    当提供时，使用给出的值替换resourceUrlBlacklist。它必须是一个数组或null。这里会使用该数组的快照，所以数组未来的变化被忽略。

    黑名单典型的用法是用**阻止开放重定向(http://cwe.mitre.org/data/definitions/601.html)。
使用**处理您域中这些原本被信任的但实际上返回重定向域的内容。
最后，正如我们之前所说的黑名单会覆盖白名单。

    返回值

    Array

    当前设置的黑名单数组。

    没有白名单时的默认值被简单设为空数组(表示这里没有黑名单)。


AngularJS: API: ng/provider/$sceProvider

$sceProvider

  1. - $sce
  2. - provider in module ng

$sceProvider提供者允许开发者配置$sce服务。

  • 启用/禁止一个模块中的Strict Contextual Escaping (SCE)
  • 使用自定义委托重写默认实现

更多信息参见 Strict Contextual Escaping (SCE)。

方法

  • enabled([value]);

    启用/禁止SCE，并返回当前值。

    参数

    参数 类型 详述
    value
    (可选)
             boolean

    如果提供，将启用/禁止SCE。

    返回值

    boolean

    如果SCE启用返回true，否则为false。


AngularJS: API: ng/service

Service components in ng

名称 | 描述
$anchorScroll | When called, it checks current value of $location.hash() and scrolls to the related element, according to rules specified in Html5 spec.
$animate | The $animate service provides rudimentary DOM manipulation functions to insert, remove and move elements within the DOM, as well as adding and removing classes. This service is the core service used by the ngAnimate $animator service which provides high-level animation hooks for CSS and JavaScript.
$cacheFactory | Factory that constructs Cache objects and gives access to them.
$templateCache | The first time a template is used, it is loaded in the template cache for quick retrieval. You can load templates directly into the cache in a script tag, or by consuming the $templateCache service directly.
$compile | Compiles an HTML string or DOM into a template and produces a template function, which can then be used to link scope and the template together.
$controller | $controller service is responsible for instantiating controllers.
$document | A jQuery or jqLite wrapper for the browser's window.document object.
$exceptionHandler | Any uncaught exception in Angular表达式s is delegated to this service. The default implementation simply delegates to $log.error which logs it into the browser console.
$filter | Filters are used for formatting data displayed to the user.
$http | The $http service is a core Angular service that facilitates communication with the remote HTTP servers via the browser's XMLHttpRequest object or via JSONP.
$httpBackend | HTTP backend used by the Service that delegates to XMLHttpRequest object or JSONP and deals with browser incompatibilities.
$interpolate | Compiles a string with markup into an interpolation function. This service is used by the HTML $compile service for data binding. See $interpolateProvider for configuring the interpolation markup.
$interval | Angular's wrapper for window.setInterval. The fn function is executed every delay milliseconds.
$locale | $locale service provides localization rules for various Angular components. As of right now the only public api is:
$location | The $location service parses the URL in the browser address bar (based on the window.location) and makes the URL available to your application. Changes to the URL in the address bar are reflected into $location service and changes to $location are reflected into the browser address bar.
$log | Simple service for logging. Default implementation safely writes the message into the browser's console (if present).
$parse | Converts Angular expression into a function.
$q | A promise/deferred implementation inspired by Kris Kowal's Q.
$rootElement | The root element of Angular application. This is either the element where ngApp was declared or the element passed into angular.bootstrap. The element represent the root element of application. It is also the location where the applications $injector service gets published, it can be retrieved using $rootElement.injector().
$rootScope | Every application has a single root scope. All other scopes are descendant scopes of the root scope. Scopes provide separation between the model and the view, via a mechanism for watching the model for changes. They also provide an event emission/broadcast and subscription facility. See the developer guide on scopes.
$sceDelegate | $sceDelegate is a service that is used by the $sce service to provide Strict Contextual Escaping (SCE) services to AngularJS.
$sce | $sce is a service that provides Strict Contextual Escaping services to AngularJS.
$timeout | Angular's wrapper for window.setTimeout. The fn function is wrapped into a try/catch block and delegates any exceptions to $exceptionHandler service.
$window | A reference to the browser's window object. While window is globally available in JavaScript, it causes testability problems, because it is a global variable. In angular we always refer to it through the $window service, so it may be overridden, removed or mocked for testing.


AngularJS: API: ng/service/$anchorScroll

$anchorScroll

  1. - service in module ng

When called, it checks current value of $location.hash() and scrolls to the related element, according to rules specified in Html5 spec.

It also watches the $location.hash() and scrolls whenever it changes to match any anchor. This can be disabled by calling $anchorScrollProvider.disableAutoScrolling().

依赖

  • $window
  • $location
  • $rootScope

用法

$anchorScroll();

示例

index.html
<div id="scrollArea" ng-controller="ScrollController">
  <a ng-click="gotoBottom()">Go to bottom</a>
  <a id="bottom"></a> You're at the bottom!
</div>
script.js
angular.module('anchorScrollExample', [])
  .controller('ScrollController', ['$scope', '$location', '$anchorScroll',
    Function ($scope, $location, $anchorScroll) {
      $scope.gotoBottom = Function() {
        // set the location.hash to the id of
        // the element you wish to scroll to.
        $location.hash('bottom');

        // call $anchorScroll()
        $anchorScroll();
      };
    }]);
style.css
#scrollArea {
  height: 350px;
  overflow: auto;}

#bottom {
  display: block;
  margin-top: 2000px;}


AngularJS: API: ng/service/$animate

$animate

  1. - $animateProvider
  2. - service in module ng

The $animate service provides rudimentary DOM manipulation functions to insert, remove and move elements within the DOM, as well as adding and removing classes. This service is the core service used by the ngAnimate $animator service which provides high-level animation hooks for CSS and JavaScript.

$animate is available in the AngularJS core, however, the ngAnimate module must be included to enable full out animation support. Otherwise, $animate will only perform simple DOM manipulation operations.

To learn more about enabling animation support, click here to visit the ngAnimate module page as well as the ngAnimate $animate service page.

方法

  • enter(element, parent, after, [done]);

    Inserts the element into the DOM either after the after element or as the first child within the parent element. Once complete, the done() callback will be fired (if provided).

    参数

    参数 类型 详述
    element DOMElement

    the element which will be inserted into the DOM
    parent DOMElement

    the parent element which will append the element as a child (if the after element is not present)
    after DOMElement

    the sibling element which will append the element after itself
    done
    (可选)
             Function=

    callback function that will be called after the element has been inserted into the DOM

  • leave(element, [done]);

    Removes the element from the DOM. Once complete, the done() callback will be fired (if provided).

    参数

    参数 类型 详述
    element DOMElement

    the element which will be removed from the DOM
    done
    (可选)
             Function=

    callback function that will be called after the element has been removed from the DOM

  • move(element, parent, after, [done]);

    Moves the position of the provided element within the DOM to be placed either after the after element or inside of the parent element. Once complete, the done() callback will be fired (if provided).

    参数

    参数 类型 详述
    element DOMElement

    the element which will be moved around within the DOM
    parent DOMElement

    the parent element where the element will be inserted into (if the after element is not present)
    after DOMElement

    the sibling element where the element will be positioned next to
    done
    (可选)
             Function=

    the callback function (if provided) that will be fired after the element has been moved to its new position

  • addClass(element, className, [done]);

    Adds the provided className CSS class value to the provided element. Once complete, the done() callback will be fired (if provided).

    参数

    参数 类型 详述
    element DOMElement

    the element which will have the className value added to it
    className string

    the CSS class which will be added to the element
    done
    (可选)
             Function=

    the callback function (if provided) that will be fired after the className value has been added to the element

  • removeClass(element, className, [done]);

    Removes the provided className CSS class value from the provided element. Once complete, the done() callback will be fired (if provided).

    参数

    参数 类型 详述
    element DOMElement

    the element which will have the className value removed from it
    className string

    the CSS class which will be removed from the element
    done
    (可选)
             Function=

    the callback function (if provided) that will be fired after the className value has been removed from the element

  • setClass(element, add, remove, [done]);

    Adds and/or removes the given CSS classes to and from the element. Once complete, the done() callback will be fired (if provided).

    参数

    参数 类型 详述
    element DOMElement

    the element which will have its CSS classes changed removed from it
    add string

    the CSS classes which will be added to the element
    remove string

    the CSS class which will be removed from the element
    done
    (可选)
             Function=

    the callback function (if provided) that will be fired after the CSS classes have been set on the element


AngularJS: API: ng/service/$cacheFactory

$cacheFactory

  1. - service in module ng

Factory that constructs Cache objects and gives access to them.

 var cache = $cacheFactory('cacheId');
 expect($cacheFactory.get('cacheId')).toBe(cache);
 expect($cacheFactory.get('noSuchCacheId')).not.toBeDefined();

 cache.put("key", "value");
 cache.put("another key", "another value");

 // We've specified no options on creation
 expect(cache.info()).toEqual({id: 'cacheId', size: 2});

用法

$cacheFactory(cacheId, [options]);

参数

参数 类型 详述
cacheId string

Name or id of the newly created cache.

options
(可选)
Object

Options object that specifies the cache behavior. Properties:

  • {number=} capacity — turns the cache into LRU cache.

返回值

Object

Newly created cache object with the following set of methods:

  • {Object} info() — Returns id, size, and options of cache.
  • {{*}} put({string} key, {*} value) — Puts a new key-value pair into the cache and returns it.
  • {{*}} get({string} key) — Returns cached value for key or undefined for cache miss.
  • {void} remove({string} key) — Removes a key-value pair from the cache.
  • {void} removeAll() — Removes all cached values.
  • {void} destroy() — Removes references to this cache from $cacheFactory.

方法

  • info();

    Get information about all the caches that have been created

    返回值

    Object
    • key-value map of cacheId to the result of calling cache#info

  • get(cacheId);

    Get access to a cache object by the cacheId used when it was created.

    参数

    参数 类型 详述
    cacheId string

    Name or id of a cache to access.

    返回值

    Object

    Cache object identified by the cacheId or undefined if no such cache.

示例

index.html
<div ng-controller="CacheController">
  <input ng-model="newCacheKey" placeholder="Key">
  <input ng-model="newCacheValue" placeholder="Value">
  <button ng-click="put(newCacheKey, newCacheValue)">Cache</button>

  <p ng-if="keys.length">Cached Values</p>
  <div ng-repeat="key in keys">
    <span ng-bind="key"></span>
    <span>: </span>
    <b ng-bind="cache.get(key)"></b>
  </div>

  <p>Cache Info</p>
  <div ng-repeat="(key, value) in cache.info()">
    <span ng-bind="key"></span>
    <span>: </span>
    <b ng-bind="value"></b>
  </div></div>
script.js
angular.module('cacheExampleApp', []).
  controller('CacheController', ['$scope', '$cacheFactory', Function($scope, $cacheFactory) {
    $scope.keys = [];
    $scope.cache = $cacheFactory('cacheId');
    $scope.put = Function(key, value) {
      $scope.cache.put(key, value);
      $scope.keys.push(key);
    };
  }]);
style.css
p {
  margin: 10px 0 3px;}


AngularJS: API: ng/service/$compile

$compile

  1. - $compileProvider
  2. - service in module ng

Compiles an HTML string or DOM into a template and produces a template function, which can then be used to link scope and the template together.

The compilation is a process of walking the DOM tree and matching DOM elements to directives.

注意： This document is an in-depth reference of all directive options. For a gentle introduction to directives with examples of common use cases, see the directive guide.

Comprehensive Directive API

There are many different options for a directive.

The difference resides in the return value of the factory function. You can either return a "Directive Definition Object" (see below) that defines the directive properties, or just the postLink function (all other properties will have the default values).

最佳实践： It's recommended to use the "directive definition object" form.

Here's an example directive declared with a Directive Definition Object:

  var myModule = angular.module(...);

  myModule.Directive('directiveName', Function factory(injectables) {
    var directiveDefinitionObject = {
      priority: 0,
      template: '<div></div>', // or // function(tElement, tAttrs) { ... },
      // or
      // templateUrl: 'directive.html', // or // function(tElement, tAttrs) { ... },
      transclude: false,
      restrict: 'A',
      scope: false,
      controller: Function($scope, $element, $attrs, $transclude, otherInjectables) { ... },
      controllerAs: 'stringAlias',
      require: 'siblingDirectiveName', // or // ['^parentDirectiveName', '?optionalDirectiveName', '?^optionalParent'],
      compile: Function compile(tElement, tAttrs, transclude) {
        return {
          pre: Function preLink(scope, iElement, iAttrs, controller) { ... },
          post: Function postLink(scope, iElement, iAttrs, controller) { ... }
        }
        // or
        // return function postLink( ... ) { ... }
      },
      // or
      // link: {
      //  pre: function preLink(scope, iElement, iAttrs, controller) { ... },
      //  post: function postLink(scope, iElement, iAttrs, controller) { ... }
      // }
      // or
      // link: function postLink( ... ) { ... }
    };
    return directiveDefinitionObject;
  });
注意： Any unspecified options will use the default value. You can see the default values below.

Therefore the above can be simplified as:

  var myModule = angular.module(...);

  myModule.Directive('directiveName', Function factory(injectables) {
    var directiveDefinitionObject = {
      link: Function postLink(scope, iElement, iAttrs) { ... }
    };
    return directiveDefinitionObject;
    // or
    // return function postLink(scope, iElement, iAttrs) { ... }
  });

Directive Definition Object

The directive definition object provides instructions to the compiler. The attributes are:

priority

When there are multiple directives defined on a single DOM element, sometimes it is necessary to specify the order in which the directives are applied. The priority is used to sort the directives before their compile functions get called. Priority is defined as a number. Directives with greater numerical priority are compiled first. Pre-link functions are also run in priority order, but post-link functions are run in reverse order. The order of directives with the same priority is undefined. The default priority is 0.

terminal

If set to true then the current priority will be the last set of directives which will execute (any directives at the current priority will still execute as the order of execution on same priority is undefined).

scope

If set to true, then a new scope will be created for this directive. If multiple directives on the same element request a new scope, only one new scope is created. The new scope rule does not apply for the root of the template since the root of the template always gets a new scope.

If set to {} (object hash), then a new "isolate" scope is created. The 'isolate' scope differs from normal scope in that it does not prototypically inherit from the parent scope. This is useful when creating reusable components, which should not accidentally read or modify data in the parent scope.

The 'isolate' scope takes an object hash which defines a set of local scope properties derived from the parent scope. These local properties are useful for aliasing values for templates. Locals definition is a hash of local scope property to its source:

  • @ or @attr - bind a local scope property to the value of DOM attribute. The result is always a string since DOM attributes are strings. If no attr name is specified then the attribute name is assumed to be the same as the local name. Given <widget my-attr="hello {{name}}"> and widget definition of scope: { localName:'@myAttr' }, then widget scope property localName will reflect the interpolated value of hello {{名称}}. As the 名称 attribute changes so will the localName property on the widget scope. The 名称 is read from the parent scope (not component scope).

  • = or =attr - set up bi-directional binding between a local scope property and the parent scope property of name defined via the value of the attr attribute. If no attr name is specified then the attribute name is assumed to be the same as the local name. Given <widget my-attr="parentModel"> and widget definition of scope: { localModel:'=myAttr' }, then widget scope property localModel will reflect the value of parentModel on the parent scope. Any changes to parentModel will be reflected in localModel and any changes in localModel will reflect in parentModel. If the parent scope property doesn't exist, it will throw a NON_ASSIGNABLE_MODEL_EXPRESSION exception. You can avoid this behavior using =? or =?attr in order to flag the property as optional.

  • & or &attr - provides a way to execute an expression in the context of the parent scope. If no attr name is specified then the attribute name is assumed to be the same as the local name. Given <widget my-attr="count = count + value"> and widget definition of scope: { localFn:'&myAttr' }, then isolate scope property localFn will point to a function wrapper for the count = count + value expression. Often it's desirable to pass data from the isolated scope via an expression to the parent scope, this can be done by passing a map of local variable names and values into the expression wrapper fn. 例如，if the expression is increment(amount) then we can specify the amount value by calling the localFn as localFn({amount: 22}).

controller

Controller constructor function. The controller is instantiated before the pre-linking phase and it is shared with other directives (see require attribute). This allows the directives to communicate with each other and augment each other's behavior. The controller is injectable (and supports bracket notation) with the following locals:

  • $scope - Current scope associated with the element
  • $element - Current element
  • $attrs - Current attributes object for the element
  • $transclude - A transclude linking function pre-bound to the correct transclusion scope. The scope can be overridden by an optional first argument. Function([scope], cloneLinkingFn).

require

Require another directive and inject its controller as the fourth argument to the linking function. The require takes a string name (or array of strings) of the directive(s) to pass in. If an array is used, the injected argument will be an array in corresponding order. If no such directive can be found, or if the directive does not have a controller, then an error is raised. The name can be prefixed with:

  • (no prefix) - Locate the required controller on the current element. Throw an error if not found.
  • ? - Attempt to locate the required controller or pass null to the link fn if not found.
  • ^ - Locate the required controller by searching the element's parents. Throw an error if not found.
  • ?^ - Attempt to locate the required controller by searching the element's parents or pass null to the link fn if not found.

controllerAs

Controller alias at the directive scope. An alias for the controller so it can be referenced at the directive template. The directive needs to define a scope for this configuration to be used. Useful in the case when directive is used as component.

restrict

String of subset of EACM which restricts the directive to a specific directive declaration style. If omitted, the default (attributes only) is used.

  • E - Element name: <my-directive></my-directive>
  • A - Attribute (default): <div my-directive="exp"></div>
  • C - Class: <div class="my-directive: exp;"></div>
  • M - Comment: <!-- directive: my-directive exp -->

Type

String representing the document type used by the markup. This is useful for templates where the root node is non-HTML content (such as SVG or MathML). The default value is "html".

  • html - All root template nodes are HTML, and don't need to be wrapped. Root nodes may also be top-level elements such as <svg> or <math>.
  • svg - The template contains only SVG content, and must be wrapped in an <svg> node prior to processing.
  • math - The template contains only MathML content, and must be wrapped in an <math> node prior to processing.

If no Type is specified, then the type is considered to be html.

template

replace the current element with the contents of the HTML. The replacement process migrates all of the attributes / classes from the old element to the new one. See the Directives Guide for an example.

You can specify template as a string representing the template or as a function which takes two arguments tElement and tAttrs (described in the compile function api below) and returns a string value representing the template.

templateUrl

Same as template but the template is loaded from the specified URL. Because the template loading is asynchronous the compilation/linking is suspended until the template is loaded.

You can specify templateUrl as a string representing the URL or as a function which takes two arguments tElement and tAttrs (described in the compile function api below) and returns a string value representing the url. In either case, the template URL is passed through $sce.getTrustedResourceUrl.

replace ([DEPRECATED!], will be removed in next major release)

specify where the template should be inserted. Defaults to false.

  • true - the template will replace the current element.
  • false - the template will replace the contents of the current element.

transclude

compile the content of the element and make it available to the directive. Typically used with ngTransclude. The advantage of transclusion is that the linking function receives a transclusion function which is pre-bound to the correct scope. In a typical setup the widget creates an isolate scope, but the transclusion is not a child, but a sibling of the isolate scope. This makes it possible for the widget to have private state, and the transclusion to be bound to the parent (pre-isolate) scope.

  • true - transclude the content of the directive.
  • 'element' - transclude the whole element including any directives defined at lower priority.

compile

  Function compile(tElement, tAttrs, transclude) { ... }

The compile function deals with transforming the template DOM. Since most directives do not do template transformation, it is not used often. The compile function takes the following arguments:

  • tElement - template element - The element where the directive has been declared. It is safe to do template transformation on the element and child elements only.

  • tAttrs - template attributes - Normalized list of attributes declared on this element shared between all directive compile functions.

  • transclude - [DEPRECATED!] A transclude linking function: Function(scope, cloneLinkingFn)

注意： The template instance and the link instance may be different objects if the template has been cloned. For this reason it is not safe to do anything other than DOM transformations that apply to all cloned DOM nodes within the compile function. Specifically, DOM listener registration should be done in a linking function rather than in a compile function.
注意： The compile function cannot handle directives that recursively use themselves in their own templates or compile functions. Compiling these directives results in an infinite loop and a stack overflow errors. This can be avoided by manually using $compile in the postLink function to imperatively compile a directive's template instead of relying on automatic template compilation via template or templateUrl declaration or manual compilation inside the compile function.
注意： The transclude function that is passed to the compile function is deprecated, as it例如 does not know about the right outer scope. Please use the transclude function that is passed to the link function instead.

A compile function can have a return value which can be either a function or an object.

  • returning a (post-link) function - is equivalent to registering the linking function via the link property of the config object when the compile function is empty.

  • returning an object with function(s) registered via pre and post properties - allows you to control when a linking function should be called during the linking phase. See info about pre-linking and post-linking functions below.

link

This property is used only if the compile property is not defined.

  Function link(scope, iElement, iAttrs, controller, transcludeFn) { ... }

The link function is responsible for registering DOM listeners as well as updating the DOM. It is executed after the template has been cloned. This is where most of the directive logic will be put.

  • scope - Scope - The scope to be used by the directive for registering watches.

  • iElement - instance element - The element where the directive is to be used. It is safe to manipulate the children of the element only in postLink function since the children have already been linked.

  • iAttrs - instance attributes - Normalized list of attributes declared on this element shared between all directive linking functions.

  • controller - a controller instance - A controller instance if at least one directive on the element defines a controller. The controller is shared among all the directives, which allows the directives to use the controllers as a communication channel.

  • transcludeFn - A transclude linking function pre-bound to the correct transclusion scope. The scope can be overridden by an optional first argument. This is the same as the $transclude parameter of directive controllers. Function([scope], cloneLinkingFn).

Pre-linking function

Executed before the child elements are linked. Not safe to do DOM transformation since the compiler linking function will fail to locate the correct elements for linking.

Post-linking function

Executed after the child elements are linked. It is safe to do DOM transformation in the post-linking function.

Attributes

The Attributes object - passed as a parameter in the link() or compile() functions. It has a variety of uses.

accessing Normalized attribute names: Directives like 'ngBind' can be expressed in many ways: 'ng:bind', data-ng-bind, or 'x-ng-bind'. the attributes object allows for normalized access to the attributes.

  • Directive inter-communication: All directives share the same instance of the attributes object which allows the directives to use the attributes object as inter directive communication.

  • Supports interpolation: Interpolation attributes are assigned to the attribute object allowing other directives to read the interpolated value.

  • Observing interpolated attributes: Use $observe to observe the value changes of attributes that contain interpolation (如： src="{{bar}}"). Not only is this very efficient but it's also the only way to easily get the actual value because during the linking phase the interpolation hasn't been evaluated yet and so the value is at this time set to undefined.

Function linkingFn(scope, elm, attrs, ctrl) {
  // get the attribute value
  console.log(attrs.ngModel);

  // change the attribute
  attrs.$set('ngModel', 'new value');

  // observe changes to interpolated attribute
  attrs.$observe('ngModel', Function(value) {
    console.log('ngModel has changed value to ' + value);
  });}

Below is an example using $compileProvider.

注意: Typically directives are registered with module.Directive. The example below is to illustrate how $compile works.

index.html
<script>
  angular.module('compileExample', [], Function($compileProvider) {
    // configure new 'compile' directive by passing a directive
    // factory function. The factory function injects the '$compile'
    $compileProvider.Directive('compile', Function($compile) {
      // directive factory creates a link function
      return Function(scope, element, attrs) {
        scope.$watch(
          Function(scope) {
             // watch the 'compile' expression for changes
            return scope.$eval(attrs.compile);
          },
          Function(value) {
            // when the 'compile' expression changes
            // assign it into the current DOM
            element.html(value);

            // compile the new DOM and link it to the current
            // scope.
            // 注意： we only compile .childNodes so that
            // we don't get into infinite loop compiling ourselves
            $compile(element.contents())(scope);
          }
        );
      };
    });
  })
  .controller('GreeterController', ['$scope', Function($scope) {
    $scope.name= 'Angular';
    $scope.html = 'Hello {{name}}';
  }]);</script><div ng-controller="GreeterController">
  <input ng-model="name"> <br>
  <textarea ng-model="html"></textarea> <br>
  <div compile="html"></div></div>
protractor.js
it('should auto compile', Function() {
  var textarea = $('textarea');
  var output = $('div[compile]');
  // The initial state reads 'Hello Angular'.
  expect(output.getText()).toBe('Hello Angular');
  textarea.clear();
  textarea.sendKeys('{{name}}!');
  expect(output.getText()).toBe('Angular!');});

用法

$compile(element, transclude, maxPriority);

参数

参数 | 类型 | 详述
element | string DOMElement | Element or HTML string to compile into a template function.
transclude | function(angular.Scope, cloneAttachFn=) | function available to directives.
maxPriority | number | only apply directives lower than given priority (Only effects the root element(s), not their children)

返回值

function(scope, cloneAttachFn=)

a link function which is used to bind template (a DOM element/tree) to a scope. Where:

  • scope - A Scope to bind to.

  • cloneAttachFn - If cloneAttachFn is provided, then the link function will clone the template and call the cloneAttachFn function allowing the caller to attach the cloned elements to the DOM document at the appropriate place. The cloneAttachFn is called as:
    cloneAttachFn(clonedElement, scope) where:

    • clonedElement - is a clone of the original element passed into the compiler.
    • scope - is the current scope with which the linking function is working with.

Calling the linking function returns the element of the template. It is either the original element passed in, or the clone of the element if the cloneAttachFn is provided.

After linking the view is not updated until after a call to $digest which typically is done by Angular automatically.

If you need access to the bound view, there are two ways to do it:

  • If you are not asking the linking function to clone the template, create the DOM element(s) before you send them to the compiler and keep this reference around.

      var element = $compile('<p>{{total}}</p>')(scope);

  • if on the other hand, you need the element to be cloned, the view reference from the original example would not point to the clone, but rather to the original template that was cloned. In this case, you can access the clone via the cloneAttachFn:

      var templateElement = angular.element('<p>{{total}}</p>'),
      scope = ....;

  var clonedElement = $compile(templateElement)(scope, Function(clonedElement, scope) {
    //attach the clone to DOM document at the right place
  });

  //now we have reference to the cloned DOM via `clonedElement`

For information on how the compiler works, see the Angular HTML Compiler section of the Developer Guide.


AngularJS: API: ng/service/$controller

$controller

  1. - $controllerProvider
  2. - service in module ng

$controller service is responsible for instantiating controllers.

It's just a simple call to $injector, but extracted into a service, so that one can override this service with BC version.

依赖

  • $injector

用法

$controller(constructor, locals);

参数

参数 类型 详述
constructor function() string

If called with a function then it's considered to be the controller constructor function. Otherwise it's considered to be a string which is used to retrieve the controller constructor using the following steps:

  • check if a controller with given name is registered via $controllerProvider
  • check if evaluating the string on the current scope returns a constructor
  • if $controllerProvider#allowGlobals, check window[constructor] on the global window object (not recommended)
locals Object

Injection locals for Controller.

返回值

Object

Instance of given controller.


AngularJS: API: ng/service/$document

$document

  1. - service in module ng

A jQuery or jqLite wrapper for the browser's window.document object.

依赖

  • $window

示例

index.html
<div ng-controller="ExampleController">
  <p>$document title: <b ng-bind="title"></b></p>
  <p>window.document title: <b ng-bind="windowTitle"></b></p></div>
script.js
angular.module('documentExample', [])
  .controller('ExampleController', ['$scope', '$document', Function($scope, $document) {
    $scope.title = $document[0].title;
    $scope.windowTitle = angular.element(window.document)[0].title;
  }]);


AngularJS: API: ng/service/$exceptionHandler

$exceptionHandler

  1. - service in module ng

Any uncaught exception in Angular表达式s is delegated to this service. The default implementation simply delegates to $log.error which logs it into the browser console.

In unit tests, if angular-mocks.js is loaded, this service is overridden by mock $exceptionHandler which aids in testing.

示例:

  angular.module('exceptionOverride', []).factory('$exceptionHandler', Function () {
    return Function (exception, cause) {
      exception.message += ' (caused by "' + cause + '")';
      throw exception;
    };
  });

This example will override the normal action of $exceptionHandler, to make angular exceptions fail hard when they happen, instead of just logging to the console.

依赖

  • $log

用法

$exceptionHandler(exception, [cause]);

参数

参数 | 类型 | 详述
exception | Error | Exception associated with the error.
cause (可选) | string | optional information about the context in which the error was thrown.


AngularJS: API: ng/service/$filter

$filter

  1. - $filterProvider
  2. - service in module ng

Filters are used for formatting data displayed to the user.

The general syntax in templates is as follows:

    {{ expression [| filter_name[:parameter_value] ... ] }}

用法

$filter(名称);

参数

参数 | 类型 | 详述
名称 | String | Name of the filter function to retrieve

返回值

Function

the filter function

示例

index.html
<div ng-controller="MainCtrl">
 <h3>{{ originalText }}</h3>
 <h3>{{ filteredText }}</h3></div>
script.js
angular.module('filterExample', []).controller('MainCtrl', Function($scope, $filter) {
  $scope.originalText = 'hello';
  $scope.filteredText = $filter('uppercase')($scope.originalText);});


AngularJS: API: ng/service/$http

$http

  1. - $httpProvider
  2. - service in module ng

The $http service is a core Angular service that facilitates communication with the remote HTTP servers via the browser's XMLHttpRequest object or via JSONP.

For unit testing applications that use $http service, see $httpBackend mock.

For a higher level of abstraction, please check out the $resource service.

The $http API is based on the deferred/promise APIs exposed by the $q service. While for simple usage patterns this doesn't matter much, for advanced usage it is important to familiarize yourself with these APIs and the guarantees they provide.

General usage

The $http service is a function which takes a single argument — a configuration object — that is used to generate an HTTP request and returns a promise with two $http specific methods: success and error.

  $http({method: 'GET', url: '/someUrl'}).
    success(Function(data, status, headers, config) {
      // this callback will be called asynchronously
      // when the response is available
    }).
    error(Function(data, status, headers, config) {
      // called asynchronously if an error occurs
      // or server returns response with an error status.
    });

Since the returned value of calling the $http function is a promise, you can also use the then method to register callbacks, and these callbacks will receive a single argument – an object representing the response. See the API signature and type info below for more details.

A response status code between 200 and 299 is considered a success status and will result in the success callback being called. Note that if the response is a redirect, XMLHttpRequest will transparently follow it, meaning that the error callback will not be called for such responses.

Writing Unit Tests that use $http

When unit testing (using ngMock), it is necessary to call $httpBackend.flush() to flush each pending request using trained responses.

$httpBackend.expectGET(...);
$http.get(...);
$httpBackend.flush();

Shortcut methods

Shortcut methods are also available. All shortcut methods require passing in the URL, and request data must be passed in for POST/PUT requests.

  $http.get('/someUrl').success(successCallback);
  $http.post('/someUrl', data).success(successCallback);

Complete list of shortcut methods:

  • $http.get
  • $http.head
  • $http.post
  • $http.put
  • $http.delete
  • $http.jsonp

Setting HTTP Headers

The $http service will automatically add certain HTTP headers to all requests. These defaults can be fully configured by accessing the $httpProvider.defaults.headers configuration object, which currently contains this default configuration:

  • $httpProvider.defaults.headers.common (headers that are common for all requests):
    • Accept: application/json, text/plain, * / *
  • $httpProvider.defaults.headers.post: (header defaults for POST requests)
    • Content-Type: application/json
  • $httpProvider.defaults.headers.put (header defaults for PUT requests)
    • Content-Type: application/json

To add or overwrite these defaults, simply add or remove a property from these configuration objects. To add headers for an HTTP method other than POST or PUT, simply add a new object with the lowercased HTTP method name as the key,例如 `$httpProvider.defaults.headers.get = { 'My-Header' : 'value' }.

The defaults can also be set at runtime via the $http.defaults object in the same fashion. 例如:

module.run(Function($http) {
  $http.defaults.headers.common.Authorization = 'Basic YmVlcDpib29w'});

此外， you can supply a headers property in the config object passed when calling $http(config), which overrides the defaults without changing them globally.

Transforming Requests and Responses

Both requests and responses can be transformed using transform functions. 默认情况下， Angular applies these transformations:

Request transformations:

  • If the data property of the request configuration object contains an object, serialize it into JSON format.

Response transformations:

  • If XSRF prefix is detected, strip it (see Security Considerations section below).
  • If JSON response is detected, deserialize it using a JSON parser.

To globally augment or override the default transforms, modify the $httpProvider.defaults.transformRequest and $httpProvider.defaults.transformResponse properties. These properties are by default an array of transform functions, which allows you to push or unshift a new transformation function into the transformation chain. You can also decide to completely override any default transformations by assigning your transformation functions to these properties directly without the array wrapper. These defaults are again available on the $http factory at run-time, which may be useful if you have run-time services you wish to be involved in your transformations.

Similarly, to locally override the request/response transforms, augment the transformRequest and/or transformResponse properties of the configuration object passed into $http.

Caching

To enable caching, set the request configuration cache property to true (to use default cache) or to a custom cache object (built with $cacheFactory). When the cache is enabled, $http stores the response from the server in the specified cache. The next time the same request is made, the response is served from the cache without sending a request to the server.

Note that even if the response is served from cache, delivery of the data is asynchronous in the same way that real requests are.

If there are multiple GET requests for the same URL that should be cached using the same cache, but the cache is not populated yet, only one request to the server will be made and the remaining requests will be fulfilled using the response from the first request.

You can change the default cache to a new object (built with $cacheFactory) by updating the $http.defaults.cache property. All requests who set their cache property to true will now use this cache object.

If you set the default cache to false then only requests that specify their own custom cache object will be cached.

Interceptors

Before you start creating interceptors, be sure to understand the $q and deferred/promise APIs.

For purposes of global error handling, authentication, or any kind of synchronous or asynchronous pre-processing of request or postprocessing of responses, it is desirable to be able to intercept requests before they are handed to the server and responses before they are handed over to the application code that initiated these requests. The interceptors leverage the promise APIs to fulfill this need for both synchronous and asynchronous pre-processing.

The interceptors are service factories that are registered with the $httpProvider by adding them to the $httpProvider.interceptors array. The factory is called and injected with dependencies (if specified) and returns the interceptor.

There are two kinds of interceptors (and two kinds of rejection interceptors):

  • request: interceptors get called with a http config object. The function is free to modify the config object or create a new one. The function needs to return the config object directly, or a promise containing the config or a new config object.
  • requestError: interceptor gets called when a previous interceptor threw an error or resolved with a rejection.
  • response: interceptors get called with http response object. The function is free to modify the response object or create a new one. The function needs to return the response object directly, or as a promise containing the response or a new response object.
  • responseError: interceptor gets called when a previous interceptor threw an error or resolved with a rejection.
  // register the interceptor as a service
  $provide.factory('myHttpInterceptor', Function($q, dependency1, dependency2) {
    return {
      // optional method
      'request': Function(config) {
        // do something on success
        return config;
      },

      // optional method
     'requestError': Function(rejection) {
        // do something on error
        if (canRecover(rejection)) {
          return responseOrNewPromise
        }
        return $q.reject(rejection);
      },

      // optional method
      'response': Function(response) {
        // do something on success
        return response;
      },

      // optional method
     'responseError': Function(rejection) {
        // do something on error
        if (canRecover(rejection)) {
          return responseOrNewPromise
        }
        return $q.reject(rejection);
      }
    };
  });

  $httpProvider.interceptors.push('myHttpInterceptor');

  // alternatively, register the interceptor via an anonymous factory
  $httpProvider.interceptors.push(Function($q, dependency1, dependency2) {
    return {
     'request': Function(config) {
         // same as above
      },

      'response': Function(response) {
         // same as above
      }
    };
  });

Security Considerations

When designing web applications, consider security threats from:

  • JSON vulnerability
  • XSRF

Both server and the client must cooperate in order to eliminate these threats. Angular comes pre-configured with strategies that address these issues, but for this to work backend server cooperation is required.

JSON Vulnerability Protection

A JSON vulnerability allows third party website to turn your JSON resource URL into JSONP request under some conditions. To counter this your server can prefix all JSON requests with following string ")]}',\n". Angular will automatically strip the prefix before processing it as JSON.

For example if your server needs to return:

['one','two']

which is vulnerable to attack, your server can return:

)]}',['one','two']

Angular will strip the prefix, before processing the JSON.

Cross Site Request Forgery (XSRF) Protection

XSRF is a technique by which an unauthorized site can gain your user's private data. Angular provides a mechanism to counter XSRF. When performing XHR requests, the $http service reads a token from a cookie (默认情况下， XSRF-TOKEN) and sets it as an HTTP header (X-XSRF-TOKEN). Since only JavaScript that runs on your domain could read the cookie, your server can be assured that the XHR came from JavaScript running on your domain. The header will not be set for cross-domain requests.

To take advantage of this, your server needs to set a token in a JavaScript readable session cookie called XSRF-TOKEN on the first HTTP GET request. On subsequent XHR requests the server can verify that the cookie matches X-XSRF-TOKEN HTTP header, and therefore be sure that only JavaScript running on your domain could have sent the request. The token must be unique for each user and must be verifiable by the server (to prevent the JavaScript from making up its own tokens). We recommend that the token is a digest of your site's authentication cookie with a salt) for added security.

The name of the headers can be specified using the xsrfHeaderName and xsrfCookieName properties of either $httpProvider.defaults at config-time, $http.defaults at run-time, or the per-request config object.

依赖

  • $httpBackend
  • $cacheFactory
  • $rootScope
  • $q
  • $injector

用法

$http(config);

参数

参数 类型 详述
config Object

Object describing the request to be made and how it should be processed. The object has following properties:

  • method – {string} – HTTP method (如： 'GET', 'POST', etc)
  • url – {string} – Absolute or relative URL of the resource that is being requested.
  • params – {Object.<string|Object>} – Map of strings or objects which will be turned to ?key1=value1&key2=value2 after the url. If the value is not a string, it will be JSONified.
  • data – {string|Object} – Data to be sent as the request message data.
  • headers – {Object} – Map of strings or functions which return strings representing HTTP headers to send to the server. If the return value of a function is null, the header will not be sent.
  • xsrfHeaderName – {string} – Name of HTTP header to populate with the XSRF token.
  • xsrfCookieName – {string} – Name of cookie containing the XSRF token.
  • transformRequest – {Function(data, headersGetter)|Array.<Function(data, headersGetter)>} – transform function or an array of such functions. The transform function takes the http request body and headers and returns its transformed (typically serialized) version.
  • transformResponse – {Function(data, headersGetter)|Array.<Function(data, headersGetter)>} – transform function or an array of such functions. The transform function takes the http response body and headers and returns its transformed (typically deserialized) version.
  • cache – {boolean|Cache} – If true, a default $http cache will be used to cache the GET request, otherwise if a cache instance built with $cacheFactory, this cache will be used for caching.
  • timeout – {number|Promise} – timeout in milliseconds, or promise that should abort the request when resolved.
  • withCredentials - {boolean} - whether to set the withCredentials flag on the XHR object. See [requests with credentials]https://developer.mozilla.org/en/http_access_control#section_5 for more information.
  • responseType - {string} - see requestType.

返回值

HttpPromise

Returns a promise object with the standard then method and two http specific methods: success and error. The then method takes two arguments a success and an error callback which will be called with a response object. The success and error methods take a single argument - a function that will be called when the request succeeds or fails respectively. The arguments passed into these functions are destructured representation of the response object passed into the then method. The response object has these properties:

  • data – {string|Object} – The response body transformed with the transform functions.
  • status – {number} – HTTP status code of the response.
  • headers – {Function([headerName])} – Header getter function.
  • config – {Object} – The configuration object that was used to generate the request.
  • statusText – {string} – HTTP status text of the response.

方法

  • get(url, [config]);

    Shortcut method to perform GET request.

    参数

    参数 类型 详述
    url string

    Relative or absolute URL specifying the destination of the request

    config
    (可选)
            Object

    Optional configuration object

    返回值

    HttpPromise

    Future object

  • delete(url, [config]);

    Shortcut method to perform DELETE request.

    参数

    参数 类型 详述
    url string

    Relative or absolute URL specifying the destination of the request

    config
    (可选)
            Object

    Optional configuration object

    返回值

    HttpPromise

    Future object

  • head(url, [config]);

    Shortcut method to perform HEAD request.

    参数

    参数 类型 详述
    url string

    Relative or absolute URL specifying the destination of the request

    config
    (可选)
            Object

    Optional configuration object

    返回值

    HttpPromise

    Future object

  • jsonp(url, [config]);

    Shortcut method to perform JSONP request.

    参数

    参数 类型 详述
    url string

    Relative or absolute URL specifying the destination of the request. Should contain JSON_CALLBACK string.

    config
    (可选)
            Object

    Optional configuration object

    返回值

    HttpPromise

    Future object

  • post(url, data, [config]);

    Shortcut method to perform POST request.

    参数

    参数 类型 详述
    url string

    Relative or absolute URL specifying the destination of the request

    data *

    Request content

    config
    (可选)
            Object

    Optional configuration object

    返回值

    HttpPromise

    Future object

  • put(url, data, [config]);

    Shortcut method to perform PUT request.

    参数

    参数 类型 详述
    url string

    Relative or absolute URL specifying the destination of the request

    data *

    Request content

    config
    (可选)
            Object

    Optional configuration object

    返回值

    HttpPromise

    Future object

  • patch(url, data, [config]);

    Shortcut method to perform PATCH request.

    参数

    参数 类型 详述
    url string

    Relative or absolute URL specifying the destination of the request

    data *

    Request content

    config
    (可选)
            Object

    Optional configuration object

    返回值

    HttpPromise

    Future object

属性

  • pendingRequests

    Array.<Object>

    Array of config objects for currently pending requests. This is primarily meant to be used for debugging purposes.

  • defaults

    Runtime equivalent of the $httpProvider.defaults property. Allows configuration of default headers, withCredentials as well as request and response transformations.

    See "Setting HTTP Headers" and "Transforming Requests and Responses" sections above.

示例

index.html
<div ng-controller="FetchController"><select ng-model="method">
  <option>GET</option>
  <option>JSONP</option></select><input Type="text" ng-model="url" size="80"/><button id="fetchbtn" ng-click="fetch()">fetch</button><br><button id="samplegetbtn" ng-click="updateModel('GET', 'http-hello.html')">Sample GET</button><button id="samplejsonpbtn"
  ng-click="updateModel('JSONP',
                'https://angularjs.org/greet.php?callback=JSON_CALLBACK&name=Super%20Hero')">
  Sample JSONP
</button><button id="invalidjsonpbtn"
  ng-click="updateModel('JSONP', 'https://angularjs.org/doesntexist&callback=JSON_CALLBACK')">
    Invalid JSONP
  </button><pre>http status code: {{status}}</pre><pre>http response data: {{data}}</pre></div>
script.js
angular.module('httpExample', []).controller('FetchController', ['$scope', '$http', '$templateCache',
  Function($scope, $http, $templateCache) {
    $scope.method = 'GET';
    $scope.url = 'http-hello.html';

    $scope.fetch = Function() {
      $scope.code = null;
      $scope.response = null;

      $http({method: $scope.method, url: $scope.url, cache: $templateCache}).
        success(Function(data, status) {
          $scope.status = status;
          $scope.data = data;
        }).
        error(Function(data, status) {
          $scope.data = data || "Request failed";
          $scope.status = status;
      });
    };

    $scope.updateModel = Function(method, url) {
      $scope.method = method;
      $scope.url = url;
    };
  }]);
http-hello.html
Hello, $http!
protractor.js
var status = element(by.binding('status'));var data = element(by.binding('data'));var fetchBtn = element(by.id('fetchbtn'));var sampleGetBtn = element(by.id('samplegetbtn'));var sampleJsonpBtn = element(by.id('samplejsonpbtn'));var invalidJsonpBtn = element(by.id('invalidjsonpbtn'));

it('should make an xhr GET request', Function() {
  sampleGetBtn.click();
  fetchBtn.click();
  expect(status.getText()).toMatch('200');
  expect(data.getText()).toMatch(/Hello, \$http!/);});

it('should make a JSONP request to angularjs.org', Function() {
  sampleJsonpBtn.click();
  fetchBtn.click();
  expect(status.getText()).toMatch('200');
  expect(data.getText()).toMatch(/Super Hero!/);});

it('should make JSONP request to invalid URL and invoke the error handler',
    Function() {
  invalidJsonpBtn.click();
  fetchBtn.click();
  expect(status.getText()).toMatch('0');
  expect(data.getText()).toMatch('Request failed');});


AngularJS: API: ng/service/$httpBackend

$httpBackend

  1. - service in module ng

HTTP backend used by the Service that delegates to XMLHttpRequest object or JSONP and deals with browser incompatibilities.

You should never need to use this service directly, instead use the higher-level abstractions: $http or $resource.

During testing this implementation is swapped with mock $httpBackend which can be trained with responses.

依赖

  • $window
  • $document


AngularJS: API: ng/service/$interpolate

$interpolate

  1. - $interpolateProvider
  2. - service in module ng

Compiles a string with markup into an interpolation function. This service is used by the HTML $compile service for data binding. See $interpolateProvider for configuring the interpolation markup.

  var $interpolate = ...; // injected
  var exp = $interpolate('Hello {{name | uppercase}}!');
  expect(exp({name:'Angular'}).toEqual('Hello ANGULAR!');

$interpolate takes an optional fourth argument, allOrNothing. If allOrNothing is true, the interpolation function will return undefined unless all embedded expressions evaluate to a value other than undefined.

  var $interpolate = ...; // injected
  var context = {greeting: 'Hello', name: undefined };

  // default "forgiving" mode
  var exp = $interpolate('{{greeting}} {{name}}!');
  expect(exp(context)).toEqual('Hello !');

  // "allOrNothing" mode
  exp = $interpolate('{{greeting}} {{name}}!', false, null, true);
  expect(exp(context, true)).toBeUndefined();
  context.name= 'Angular';
  expect(exp(context, true)).toEqual('Hello Angular!');

allOrNothing is useful for interpolating URLs. ngSrc and ngSrcset use this behavior.

Escaped Interpolation

$interpolate provides a mechanism for escaping interpolation markers. Start and end markers can be escaped by preceding each of their characters with a REVERSE SOLIDUS U+005C (backslash). It will be rendered as a regular start/end marker, and will not be interpreted as an expression or binding.

This enables web-servers to prevent script injection attacks and defacing attacks, to some degree, while also enabling code examples to work without relying on the ngNonBindable directive.

For security purposes, it is strongly encouraged that web servers escape user-supplied data, replacing angle brackets (<, >) with &lt; and &gt; respectively, and replacing all interpolation start/end markers with their escaped counterparts.

Escaped interpolation markers are only replaced with the actual interpolation markers in rendered output when the $interpolate service processes the text. So, for HTML elements interpolated by $compile, or otherwise interpolated with the mustHaveExpression parameter set to true, the interpolated text must contain an unescaped interpolation expression. As such, this is typically useful only when user-data is used in rendering a template from the server, or when otherwise untrusted data is used by a directive.

index.html
<div ng-init="username='A user'">
  <p ng-init="apptitle='Escaping demo'">{{apptitle}}: \{\{ username = "defaced value"; \}\}
    </p>
  <p><strong>{{username}}</strong> attempts to inject code which will deface the
    application, but fails to accomplish their task, because the server has correctly
    escaped the interpolation start/end markers with REVERSE SOLIDUS U+005C (backslash)
    characters.</p>
  <p>Instead, the result of the attempted script injection is visible, and can be removed
    from the database by an administrator.</p></div>

依赖

  • $parse
  • $sce

用法

$interpolate(text, [mustHaveExpression], [trustedContext], [allOrNothing]);

参数

参数 | 类型 | 详述
text | string | The text with markup to interpolate.
mustHaveExpression (可选) | boolean | if set to true then the interpolation string must have embedded expression in order to return an interpolation function. Strings with no embedded expression will return null for the interpolation function.
trustedContext (可选) | string | when provided, the returned function passes the interpolated result through $sce.getTrusted(interpolatedResult, trustedContext) before returning it. Refer to the $sce service that provides Strict Contextual Escaping for details.
allOrNothing (可选) | boolean | if true, then the returned function returns undefined unless all embedded expressions evaluate to a value other than undefined.

返回值

function(context)

an interpolation function which is used to compute the interpolated string. The function has these parameters:

  • context: evaluation context for all expressions embedded in the interpolated text

方法

  • startSymbol();

    Symbol to denote the start of expression in the interpolated string. Defaults to {{.

    Use $interpolateProvider#startSymbol to change the symbol.

    返回值

    string

    start symbol.

  • endSymbol();

    Symbol to denote the end of expression in the interpolated string. Defaults to }}.

    Use $interpolateProvider#endSymbol to change the symbol.

    返回值

    string

    end symbol.


AngularJS: API: ng/service/$interval

$interval

  1. - service in module ng

Angular's wrapper for window.setInterval. The fn function is executed every delay milliseconds.

The return value of registering an interval function is a promise. This promise will be notified upon each tick of the interval, and will be resolved after count iterations, or run indefinitely if count is not defined. The value of the notification will be the number of iterations that have run. To cancel an interval, call $interval.cancel(promise).

In tests you can use $interval.flush(millis) to move forward by millis milliseconds and trigger any functions scheduled to run in that time.

注意: Intervals created by this service must be explicitly destroyed when you are finished with them. In particular they are not automatically destroyed when a controller's scope or a directive's element are destroyed. You should take this into consideration and make sure to always cancel the interval at the appropriate moment. See the example below for more details on how and when to do this.

用法

$interval(fn, delay, [count], [invokeApply]);

参数

参数 | 类型 | 详述
fn | function() | A function that should be called repeatedly.
delay | number | Number of milliseconds between each function call.
count (可选) | number | Number of times to repeat. If not set, or 0, will repeat indefinitely.
invokeApply (可选) | boolean | If set to false skips model dirty checking, otherwise will invoke fn within the $apply block.

返回值

promise

A promise which will be notified on each iteration.

方法

  • cancel(promise);

    Cancels a task associated with the promise.

    参数

    参数 类型 详述
    promise promise

    returned by the $interval function.

    返回值

    boolean

    返回值true if the task was successfully canceled.

示例

index.html
<script>
angular.module('intervalExample', [])
  .controller('ExampleController', ['$scope', '$interval',
    Function($scope, $interval) {
      $scope.format = 'M/d/yy h:mm:ss a';
      $scope.blood_1 = 100;
      $scope.blood_2 = 120;

      var stop;
      $scope.fight = Function() {
        // Don't start a new fight if we are already fighting
        if ( angular.isDefined(stop) ) return;

      stop = $interval(Function() {
        if ($scope.blood_1 > 0 && $scope.blood_2 > 0) {
          $scope.blood_1 = $scope.blood_1 - 3;
          $scope.blood_2 = $scope.blood_2 - 4;
        } else {
          $scope.stopFight();
        }
      }, 100);
    };

    $scope.stopFight = Function() {
      if (angular.isDefined(stop)) {
        $interval.cancel(stop);
        stop = undefined;
      }
    };

    $scope.resetFight = Function() {
      $scope.blood_1 = 100;
      $scope.blood_2 = 120;
    };

    $scope.$on('$destroy', Function() {
      // Make sure that the interval nis destroyed too
      $scope.stopFight();
    });
  })
  // Register the 'myCurrentTime' directive factory method.
  // We inject $interval and dateFilter service since the factory method is DI.
  .Directive('myCurrentTime', ['$interval', 'dateFilter',
    Function($interval, dateFilter) {
      // return the directive link function. (compile function not needed)
      return Function(scope, element, attrs) {
        var format,  // date format
            stopTime; // so that we can cancel the time updates

        // used to update the UI
        Function updateTime() {
          element.text(dateFilter(new Date(), format));
        }

        // watch the expression, and update the UI on change.
        scope.$watch(attrs.myCurrentTime, Function(value) {
          format = value;
          updateTime();
        });

        stopTime = $interval(updateTime, 1000);

        // listen on DOM destroy (removal) event, and cancel the next UI update
        // to prevent updating time after the DOM element was removed.
        element.on('$destroy', Function() {
          $interval.cancel(stopTime);
        });
      }
    });</script>

<div><div ng-controller="ExampleController">
  Date format: <input ng-model="format"> <hr/>
  Current time is: <span my-current-time="format"></span>
  <hr/>
  Blood 1 : <font color='red'>{{blood_1}}</font>
  Blood 2 : <font color='red'>{{blood_2}}</font>
  <button Type="button" data-ng-click="fight()">Fight</button>
  <button Type="button" data-ng-click="stopFight()">StopFight</button>
  <button Type="button" data-ng-click="resetFight()">resetFight</button></div></div>


AngularJS: API: ng/service/$locale

$locale

  1. - service in module ng

$locale service provides localization rules for various Angular components. As of right now the only public api is:

  • id – {string} – locale id formatted as languageId-countryId (如： en-us)


AngularJS: API: ng/service/$location

$location

  1. - $locationProvider
  2. - service in module ng

The $location service parses the URL in the browser address bar (based on the window.location) and makes the URL available to your application. Changes to the URL in the address bar are reflected into $location service and changes to $location are reflected into the browser address bar.

The $location service:

  • Exposes the current URL in the browser address bar, so you can
    • Watch and observe the URL.
    • Change the URL.
  • Synchronizes the URL with the browser when the user
    • Changes the address bar.
    • Clicks the back or forward button (or clicks a History link).
    • Clicks on a link.
  • Represents the URL object as a set of methods (protocol, host, port, path, search, hash).

For more information see Developer Guide: Using $location

依赖

  • $rootElement

方法

  • absUrl();

    This method is getter only.

    Return full url representation with all segments encoded according to rules specified in RFC 3986.

    返回值

    string

    full url

  • url([url], [replace]);

    This method is getter / setter.

    Return url (如： /path?a=b#hash) when called without any parameter.

    Change path, search and hash, when called with parameter and return $location.

    参数

    参数 类型 详述
    url
    (可选)
             string

    New url without base prefix (如： /path?a=b#hash)
    replace
    (可选)
             string

    The path that will be changed

    返回值

    string

    url

  • protocol();

    This method is getter only.

    Return protocol of current url.

    返回值

    string

    protocol of current url

  • host();

    This method is getter only.

    Return host of current url.

    返回值

    string

    host of current url.

  • port();

    This method is getter only.

    Return port of current url.

    返回值

    Number

    port

  • path([path]);

    This method is getter / setter.

    Return path of current url when called without any parameter.

    Change path when called with parameter and return $location.

    注意： Path should always begin with forward slash (/), this method will add the forward slash if it is missing.

    参数

    参数 类型 详述
    path
    (可选)
             string

    New path

    返回值

    string

    path

  • search(search, [paramValue]);

    This method is getter / setter.

    Return search part (as object) of current url when called without any parameter.

    Change search part when called with parameter and return $location.

    // given url http://example.com/#/some/path?foo=bar&baz=xoxo
var searchObject = $location.search();
// => {foo: 'bar', baz: 'xoxo'}

// set foo to 'yipee'
$location.search('foo', 'yipee');
// => $location

    参数

    参数 类型 详述
    search string Object.<string> Object.<Array.<string>>

    New search params - string or hash object.

    When called with a single argument the method acts as a setter, setting the search component of $location to the specified value.

    If the argument is a hash object containing an array of values, these values will be encoded as duplicate search parameters in the url.
    paramValue
    (可选)
             string Array.<string> boolean

    If search is a string, then paramValue will override only a single search property.

    If paramValue is an array, it will override the property of the search component of $location specified via the first argument.

    If paramValue is null, the property specified via the first argument will be deleted.

    If paramValue is true, the property specified via the first argument will be added with no value nor trailing equal sign.

    返回值

    Object

    If called with no arguments returns the parsed search object. If called with one or more arguments returns $location object itself.

  • hash([hash]);

    This method is getter / setter.

    Return hash fragment when called without any parameter.

    Change hash fragment when called with parameter and return $location.

    参数

    参数 类型 详述
    hash
    (可选)
             string

    New hash fragment

    返回值

    string

    hash

  • replace();

    If called, all changes to $location during current $digest will be replacing current history record, instead of adding new one.

事件

  • $locationChangeStart

    Broadcasted before a URL will change. This change can be prevented by calling preventDefault method of the event. See $rootScope.Scope for more details about event object. Upon successful change $locationChangeSuccess is fired.

    类型:

    broadcast

    目标:

    root scope

  • $locationChangeSuccess

    Broadcasted after a URL was changed.

    类型:

    broadcast

    目标:

    root scope


AngularJS: API: ng/service/$log

$log

  1. - $logProvider
  2. - service in module ng

Simple service for logging. Default implementation safely writes the message into the browser's console (if present).

The main purpose of this service is to simplify debugging and troubleshooting.

The default is to log debug messages. You can use ng.$logProvider#debugEnabled to change this.

依赖

  • $window

方法

  • log();

    输出一条日志信息

  • info();

    输出一条提示信息

  • warn();

    输出一条警告信息

  • error();

    输出一条错误信息

  • debug();

    输出一条调试信息

示例

script.js
angular.module('logExample', [])
  .controller('LogController', ['$scope', '$log', Function($scope, $log) {
    $scope.$log = $log;
    $scope.message = 'Hello World!';
  }]);
index.html
<div ng-controller="LogController">
  <p>Reload this page with open console, enter text and hit the log button...</p>
  Message:
  <input Type="text" ng-model="message"/>
  <button ng-click="$log.log(message)">log</button>
  <button ng-click="$log.warn(message)">warn</button>
  <button ng-click="$log.info(message)">info</button>
  <button ng-click="$log.error(message)">error</button></div>


AngularJS: API: ng/service/$parse

$parse

  1. - $parseProvider
  2. - service in module ng

Converts Angular expression into a function.

  var getter = $parse('user.name');
  var setter = getter.assign;
  var context = {user:{name:'angular'}};
  var locals = {user:{name:'local'}};

  expect(getter(context)).toEqual('angular');
  setter(context, 'newValue');
  expect(context.user.名称).toEqual('newValue');
  expect(getter(context, locals)).toEqual('local');

用法

$parse(expression);

参数

参数 | 类型 | 详述
expression | string | String expression to compile.

返回值

function(context, locals)

a function which represents the compiled expression:

  • context – {Object} – an object against which any expressions embedded in the strings are evaluated against (typically a scope object).

  • locals – {Object=} – local variables context object, useful for overriding values in context.

    The returned function also has the following properties:

    • literal – {boolean} – whether the expression's top-level node is a JavaScript literal.
    • constant – {boolean} – whether the expression is made entirely of JavaScript constant literals.
    • assign – {?Function(context, value)} – if the expression is assignable, this will be set to a function to change its value on the given context.


AngularJS: API: ng/service/$q

$q

  1. - service in module ng

A promise/deferred implementation inspired by Kris Kowal's Q.

The CommonJS Promise proposal describes a promise as an interface for interacting with an object that represents the result of an action that is performed asynchronously, and may or may not be finished at any given point in time.

From the perspective of dealing with error handling, deferred and promise APIs are to asynchronous programming what try, catch and throw keywords are to synchronous programming.

  // for the purpose of this example let's assume that variables `$q`, `scope` and `okToGreet`
  // are available in the current lexical scope (they could have been injected or passed in).

  Function asyncGreet(名称) {
    var deferred = $q.defer();

    setTimeout(Function() {
      deferred.notify('About to greet ' + name + '.');

      if (okToGreet(名称)) {
        deferred.resolve('Hello, ' + name + '!');
      } else {
        deferred.reject('Greeting ' + name + ' is not allowed.');
      }
    }, 1000);

    return deferred.promise;
  }

  var promise = asyncGreet('Robin Hood');
  promise.then(Function(greeting) {
    alert('Success: ' + greeting);
  }, Function(reason) {
    alert('Failed: ' + reason);
  }, Function(update) {
    alert('Got notification: ' + update);
  });

At first it might not be obvious why this extra complexity is worth the trouble. The payoff comes in the way of guarantees that promise and deferred APIs make, see https://github.com/kriskowal/uncommonjs/blob/master/promises/specification.md.

Additionally the promise api allows for composition that is very hard to do with the traditional callback (CPS) approach. For more on this please see the Q documentation especially the section on serial or parallel joining of promises.

The Deferred API

A new instance of deferred is constructed by calling $q.defer().

The purpose of the deferred object is to expose the associated Promise instance as well as APIs that can be used for signaling the successful or unsuccessful completion, as well as the status of the task.

方法

  • resolve(value) – resolves the derived promise with the value. If the value is a rejection constructed via $q.reject, the promise will be rejected instead.
  • reject(reason) – rejects the derived promise with the reason. This is equivalent to resolving it with a rejection constructed via $q.reject.
  • notify(value) - provides updates on the status of the promise's execution. This may be called multiple times before the promise is either resolved or rejected.

属性

  • promise – {Promise} – promise object associated with this deferred.

The Promise API

A new promise instance is created when a deferred instance is created and can be retrieved by calling deferred.promise.

The purpose of the promise object is to allow for interested parties to get access to the result of the deferred task when it completes.

方法

  • then(successCallback, errorCallback, notifyCallback) – regardless of when the promise was or will be resolved or rejected, then calls one of the success or error callbacks asynchronously as soon as the result is available. The callbacks are called with a single argument: the result or rejection reason. 此外， the notify callback may be called zero or more times to provide a progress indication, before the promise is resolved or rejected.

    This method returns a new promise which is resolved or rejected via the return value of the successCallback, errorCallback. It also notifies via the return value of the notifyCallback method. The promise can not be resolved or rejected from the notifyCallback method.

  • catch(errorCallback) – shorthand for promise.then(null, errorCallback)

  • finally(callback) – allows you to observe either the fulfillment or rejection of a promise, but to do so without modifying the final value. This is useful to release resources or do some clean-up that needs to be done whether the promise was rejected or resolved. See the full specification for more information.

    Because finally is a reserved word in JavaScript and reserved keywords are not supported as property names by ES3, you'll need to invoke the method like promise['finally'](callback) to make your code IE8 and Android 2.x compatible.

Chaining promises

Because calling the then method of a promise returns a new derived promise, it is easily possible to create a chain of promises:

  promiseB = promiseA.then(Function(result) {
    return result + 1;
  });

  // promiseB will be resolved immediately after promiseA is resolved and its value
  // will be the result of promiseA incremented by 1

It is possible to create chains of any length and since a promise can be resolved with another promise (which will defer its resolution further), it is possible to pause/defer resolution of the promises at any point in the chain. This makes it possible to implement powerful APIs like $http's response interceptors.

Differences between Kris Kowal's Q and $q

There are two main differences:

  • $q is integrated with the $rootScope.Scope Scope model observation mechanism in angular, which means faster propagation of resolution or rejection into your models and avoiding unnecessary browser repaints, which would result in flickering UI.

  • Q has many more features than $q, but that comes at a cost of bytes. $q is tiny, but contains all the important functionality needed for common async tasks.

    Testing

     it('should simulate promise', inject(Function($q, $rootScope) {
   var deferred = $q.defer();
   var promise = deferred.promise;
   var resolvedValue;

   promise.then(Function(value) { resolvedValue = value; });
   expect(resolvedValue).toBeUndefined();

   // Simulate resolving of promise
   deferred.resolve(123);
   // Note that the 'then' function does not get called synchronously.
   // This is because we want the promise API to always be async, whether or not
   // it got called synchronously or asynchronously.
   expect(resolvedValue).toBeUndefined();

   // Propagate promise resolution to 'then' functions using $apply().
   $rootScope.$apply();
   expect(resolvedValue).toEqual(123);
 }));

依赖

  • $rootScope

方法

  • defer();

    Creates a Deferred object which represents a task which will finish in the future.

    返回值

    Deferred

    Returns a new instance of deferred.

  • reject(reason);

    Creates a promise that is resolved as rejected with the specified reason. This api should be used to forward rejection in a chain of promises. If you are dealing with the last promise in a promise chain, you don't need to worry about it.

    When comparing deferreds/promises to the familiar behavior of try/catch/throw, think of reject as the throw keyword in JavaScript. This also means that if you "catch" an error via a promise error callback and you want to forward the error to the promise derived from the current promise, you have to "rethrow" the error by returning a rejection constructed via reject.

      promiseB = promiseA.then(Function(result) {
    // success: do something and resolve promiseB
    //          with the old or a new result
    return result;
  }, Function(reason) {
    // error: handle the error if possible and
    //        resolve promiseB with newPromiseOrValue,
    //        otherwise forward the rejection to promiseB
    if (canHandle(reason)) {
     // handle the error and recover
     return newPromiseOrValue;
    }
    return $q.reject(reason);
  });

    参数

    参数 类型 详述
    reason *

    Constant, message, exception or an object representing the rejection reason.

    返回值

    Promise

    Returns a promise that was already resolved as rejected with the reason.

  • when(value);

    Wraps an object that might be a value or a (3rd party) then-able promise into a $q promise. This is useful when you are dealing with an object that might or might not be a promise, or if the promise comes from a source that can't be trusted.

    参数

    参数 类型 详述
    value *

    Value or a promise

    返回值

    Promise

    Returns a promise of the passed value or promise

  • all(promises);

    Combines multiple promises into a single promise that is resolved when all of the input promises are resolved.

    参数

    参数 类型 详述
    promises Array.<Promise> Object.<Promise>

    An array or hash of promises.

    返回值

    Promise

    Returns a single promise that will be resolved with an array/hash of values, each value corresponding to the promise at the same index/key in the promises array/hash. If any of the promises is resolved with a rejection, this resulting promise will be rejected with the same rejection value.


AngularJS: API: ng/service/$rootElement

$rootElement

  1. - service in module ng

The root element of Angular application. This is either the element where ngApp was declared or the element passed into angular.bootstrap. The element represent the root element of application. It is also the location where the applications $injector service gets published, it can be retrieved using $rootElement.injector().


AngularJS: API: ng/service/$rootScope

$rootScope

  1. - $rootScopeProvider
  2. - service in module ng

Every application has a single root scope. All other scopes are descendant scopes of the root scope. Scopes provide separation between the model and the view, via a mechanism for watching the model for changes. They also provide an event emission/broadcast and subscription facility. See the developer guide on scopes.


AngularJS: API: ng/service/$sce

$sce

  1. - $sceProvider
  2. - service in module ng

$sce is a service that provides Strict Contextual Escaping services to AngularJS.

强上下文转义

Strict Contextual Escaping (SCE) is a mode in which AngularJS requires bindings in certain contexts to result in a value that is marked as safe to use for that context. One example of such a context is binding arbitrary html controlled by the user via ng-bind-html. We refer to these contexts as privileged or SCE contexts.

As of version 1.2, Angular ships with SCE enabled by default.

注意： When enabled (the default), IE8 in quirks mode is not supported. In this mode, IE8 allows one to execute arbitrary javascript by the use of the expression() syntax. Refer http://blogs.msdn.com/b/ie/archive/2008/10/16/ending-expressions.aspx to learn more about them. You can ensure your document is in standards mode and not quirks mode by adding <!doctype html> to the top of your HTML document.

SCE assists in writing code in way that (a) is secure by default and (b) makes auditing for security vulnerabilities such as XSS, clickjacking, etc. a lot easier.

Here's an example of a binding in a privileged context:

<input ng-model="userHtml"><div ng-bind-html="userHtml"></div>

Notice that ng-bind-html is bound to userHtml controlled by the user. With SCE disabled, this application allows the user to render arbitrary HTML into the DIV. In a more realistic example, one may be rendering user comments, blog articles, etc. via bindings. (HTML is just one example of a context where rendering user controlled input creates security vulnerabilities.)

For the case of HTML, you might use a library, either on the client side, or on the server side, to sanitize unsafe HTML before binding to the value and rendering it in the document.

How would you ensure that every place that used these types of bindings was bound to a value that was sanitized by your library (or returned as safe for rendering by your server?) How can you ensure that you didn't accidentally delete the line that sanitized the value, or renamed some properties/fields and forgot to update the binding to the sanitized value?

To be secure 默认情况下， you want to ensure that any such bindings are disallowed unless you can determine that something explicitly says it's safe to use a value for binding in that context. You can then audit your code (a simple grep would do) to ensure that this is only done for those values that you can easily tell are safe - because they were received from your server, sanitized by your library, etc. You can organize your codebase to help with this - perhaps allowing only the files in a specific directory to do this. Ensuring that the internal API exposed by that code doesn't markup arbitrary values as safe then becomes a more manageable task.

In the case of AngularJS' SCE service, one uses $sce.trustAs (and shorthand methods such as $sce.trustAsHtml, etc.) to obtain values that will be accepted by SCE / privileged contexts.

How does it work?

In privileged contexts, directives and code will bind to the result of $sce.getTrusted(context, value) rather than to the value directly. Directives use $sce.parseAs rather than $parse to watch attribute bindings, which performs the $sce.getTrusted behind the scenes on non-constant literals.

As an example, ngBindHtml uses $sce.parseAsHtml(binding expression). Here's the actual code (slightly simplified):

var ngBindHtmlDirective = ['$sce', Function($sce) {
  return Function(scope, element, attr) {
    scope.$watch($sce.parseAsHtml(attr.ngBindHtml), Function(value) {
      element.html(value || '');
    });
  };}];

Impact on loading templates

This applies both to the ng-include directive as well as templateUrl's specified by directives.

默认情况下， Angular only loads templates from the same domain and protocol as the application document. This is done by calling $sce.getTrustedResourceUrl on the template URL. To load templates from other domains and/or protocols, you may either either 白名单化 or wrap it into a trusted value.

Please 注意： The browser's 同源策略 and 交叉源资源共享(CORS) policy apply in addition to this and may further restrict whether the template is successfully loaded. This means that without the right CORS policy, loading templates from a different domain won't work on all browsers. Also, loading templates from file:// URL does not work on some browsers.

This feels like too much overhead

It's important to remember that SCE only applies to interpolation expressions.

If your expressions are constant literals, they're automatically trusted and you don't need to call $sce.trustAs on them (remember to include the ngSanitize module) (如： <div ng-bind-html="'<b>implicitly trusted</b>'"></div>) just works.

此外， a[href] and img[src] automatically sanitize their URLs and do not pass them through $sce.getTrusted. SCE doesn't play a role here.

The included $sceDelegate comes with sane defaults to allow you to load templates in ng-include from your application's domain without having to even know about SCE. It blocks loading templates from other domains or loading templates over http from an https served document. You can change these by setting your own custom whitelists and blacklists for matching such URLs.

This significantly reduces the overhead. It is far easier to pay the small overhead and have an application that's secure and can be audited to verify that with much more ease than bolting security onto an application later.

What trusted context types are supported?

Context | Notes
$sce.HTML | For HTML that's safe to source into the application. The ngBindHtml directive uses this context for bindings. If an unsafe value is encountered and the $sanitize module is present this will sanitize the value instead of throwing an error.
$sce.CSS | For CSS that's safe to source into the application. Currently unused. Feel free to use it in your own directives.
$sce.URL | For URLs that are safe to follow as links. Currently unused (<a href= and <img src= sanitize their urls and don't constitute an SCE context.
$sce.RESOURCE_URL | For URLs that are not only safe to follow as links, but whose contents are also safe to include in your application. Examples include ng-include, src / ngSrc bindings for tags other than IMG (如： IFRAME, Object, etc.) Note that $sce.RESOURCE_URL makes a stronger statement about the URL than $sce.URL does and therefore contexts requiring values trusted for $sce.RESOURCE_URL can be used anywhere that values trusted for $sce.URL are required.
$sce.JS | For JavaScript that is safe to execute in your application's context. Currently unused. Feel free to use it in your own directives.

Format of items in resourceUrlWhitelist/Blacklist

Each element in these arrays must be one of the following:

  • 'self'
    • The special string, 'self', can be used to match against all URLs of the same domain as the application document using the same protocol.
  • String (except the special value 'self')
    • The string is matched against the full normalized / absolute URL of the resource being tested (substring matches are not good enough.)
    • There are exactly two wildcard sequences - * and **. All other characters match themselves.
    • *: matches zero or more occurrences of any character other than one of the following 6 characters: ':', '/', '.', '?', '&' and ';'. It's a useful wildcard for use in a whitelist.
    • **: matches zero or more occurrences of any character. As such, it's not not appropriate to use in for a scheme, domain, etc. as it would match too much. (如： http://**.example.com/ would match http://evil.com/?ignore=.example.com/ and that might not have been the intention.) Its usage at the very end of the path is ok. (如： http://foo.example.com/templates/**).
  • RegExp (see caveat below)
    • Caveat: While regular expressions are powerful and offer great flexibility, their syntax (and all the inevitable escaping) makes them harder to maintain. It's easy to accidentally introduce a bug when one updates a complex expression (imho, all regexes should have good test coverage.). For instance, the use of . in the regex is correct only in a small number of cases. A . character in the regex used when matching the scheme or a subdomain could be matched against a : or literal . that was likely not intended. It is highly recommended to use the string patterns and only fall back to regular expressions if they as a last resort.
    • The regular expression must be an instance of RegExp (i.e. not a string.) It is matched against the entire normalized / absolute URL of the resource being tested (even when the RegExp did not have the ^ and $ codes.) 此外， any flags present on the RegExp (such as multiline, global, ignoreCase) are ignored.
    • If you are generating your JavaScript from some other templating engine (not recommended,例如 in issue #4006), remember to escape your regular expression (and be aware that you might need more than one level of escaping depending on your templating engine and the way you interpolated the value.) Do make use of your platform's escaping mechanism as it might be good enough before coding your own.例如 Ruby has Regexp.escape(str) and Python has re.escape. Javascript lacks a similar built in function for escaping. Take a look at Google Closure library's goog.string.regExpEscape(s).

Refer $sceDelegateProvider for an example.

Show me an example using SCE.

index.html
<div ng-controller="AppController as myCtrl"><i ng-bind-html="myCtrl.explicitlyTrustedHtml" id="explicitlyTrustedHtml"></i><br><br><b>User comments</b><br>
默认情况下， HTML that isn't explicitly trusted (如： Alice's comment) is sanitized when
$sanitize is available.  If $sanitize isn't available, this results in an error instead of an
exploit.
<div class="well">
  <div ng-repeat="userComment in myCtrl.userComments">
    <b>{{userComment.name}}</b>:
    <span ng-bind-html="userComment.htmlComment" class="htmlComment"></span>
    <br>
  </div></div></div>
script.js
angular.module('mySceApp', ['ngSanitize']).controller('AppController', ['$http', '$templateCache', '$sce',
  Function($http, $templateCache, $sce) {
    var self = this;
    $http.get("test_data.json", {cache: $templateCache}).success(Function(userComments) {
      self.userComments = userComments;
    });
    self.explicitlyTrustedHtml = $sce.trustAsHtml(
        '<span onmouseover="this.textContent="Explicitly trusted HTML bypasses ' +
        'sanitization."">Hover over this text.</span>');
  }]);
test_data.json
[{ "name": "Alice",
  "htmlComment":
      "<span onmouseover='this.textContent=\"PWN3D!\"'>Is <i>anyone</i> reading this?</span>"},{ "name": "Bob",
  "htmlComment": "<i>Yes!</i>  Am I the only other one?"}]
protractor.js
describe('SCE doc demo', Function() {
it('should sanitize untrusted values', Function() {
  expect(element.all(by.css('.htmlComment')).first().getInnerHtml())
      .toBe('<span>Is <i>anyone</i> reading this?</span>');});

it('should NOT sanitize explicitly trusted values', Function() {
  expect(element(by.id('explicitlyTrustedHtml')).getInnerHtml()).toBe(
      '<span onmouseover="this.textContent="Explicitly trusted HTML bypasses ' +
      'sanitization."">Hover over this text.</span>');});});

Can I disable SCE completely?

Yes, you can. However, this is strongly discouraged. SCE gives you a lot of security benefits for little coding overhead. It will be much harder to take an SCE disabled application and either secure it on your own or enable SCE at a later stage. It might make sense to disable SCE for cases where you have a lot of existing code that was written before SCE was introduced and you're migrating them a module at a time.

That said, here's how you can completely disable SCE:

angular.module('myAppWithSceDisabledmyApp', []).config(Function($sceProvider) {
  // Completely disable SCE.  For demonstration purposes only!
  // Do not use in new projects.
  $sceProvider.enabled(false);});

用法

$sce();

方法

  • isEnabled();

    Returns a boolean indicating if SCE is enabled.

    返回值

    Boolean

    true if SCE is enabled, false otherwise. If you want to set the value, you have to do it at module config time on $sceProvider.

  • parseAs(Type, expression);

    Converts Angular expression into a function. This is like $parse and is identical when the expression is a literal constant. Otherwise, it wraps the expression in a call to $sce.getTrusted(Type, result)

    参数

    参数 类型 详述
    Type string

    The kind of SCE context in which this result will be used.

    expression string

    String expression to compile.

    返回值

    function(context, locals)

    a function which represents the compiled expression:

    • context – {Object} – an object against which any expressions embedded in the strings are evaluated against (typically a scope object).
    • locals – {Object=} – local variables context object, useful for overriding values in context.

  • trustAs(Type, value);

    Delegates to $sceDelegate.trustAs. As such, returns an object that is trusted by angular for use in specified strict contextual escaping contexts (such as ng-bind-html, ng-include, any src attribute interpolation, any dom event binding attribute interpolation such as for onclick, etc.) that uses the provided value. See * $sce for enabling strict contextual escaping.

    参数

    参数 类型 详述
    Type string

    The kind of context in which this value is safe for use.例如 url, resource_url, html, js and css.

    value *

    The value that that should be considered trusted/safe.

    返回值

    *

    A value that can be used to stand in for the provided value in places where Angular expects a $sce.trustAs() return value.

  • trustAsHtml(value);

    Shorthand method. $sce.trustAsHtml(value) → $sceDelegate.trustAs($sce.HTML, value)

    参数

    参数 类型 详述
    value *

    The value to trustAs.

    返回值

    *

    An object that can be passed to $sce.getTrustedHtml(value) to obtain the original value. (privileged directives only accept expressions that are either literal constants or are the return value of $sce.trustAs.)

  • trustAsUrl(value);

    Shorthand method. $sce.trustAsUrl(value) → $sceDelegate.trustAs($sce.URL, value)

    参数

    参数 类型 详述
    value *

    The value to trustAs.

    返回值

    *

    An object that can be passed to $sce.getTrustedUrl(value) to obtain the original value. (privileged directives only accept expressions that are either literal constants or are the return value of $sce.trustAs.)

  • trustAsResourceUrl(value);

    Shorthand method. $sce.trustAsResourceUrl(value) → $sceDelegate.trustAs($sce.RESOURCE_URL, value)

    参数

    参数 类型 详述
    value *

    The value to trustAs.

    返回值

    *

    An object that can be passed to $sce.getTrustedResourceUrl(value) to obtain the original value. (privileged directives only accept expressions that are either literal constants or are the return value of $sce.trustAs.)

  • trustAsJs(value);

    Shorthand method. $sce.trustAsJs(value) → $sceDelegate.trustAs($sce.JS, value)

    参数

    参数 类型 详述
    value *

    The value to trustAs.

    返回值

    *

    An object that can be passed to $sce.getTrustedJs(value) to obtain the original value. (privileged directives only accept expressions that are either literal constants or are the return value of $sce.trustAs.)

  • getTrusted(Type, maybeTrusted);

    Delegates to $sceDelegate.getTrusted. As such, takes the result of a $sce.trustAs() call and returns the originally supplied value if the queried context type is a supertype of the created type. If this condition isn't satisfied, throws an exception.

    参数

    参数 类型 详述
    Type string

    The kind of context in which this value is to be used.

    maybeTrusted *

    The result of a prior $sce.trustAs call.

    返回值

    *

    The value the was originally provided to $sce.trustAs if valid in this context. Otherwise, throws an exception.

  • getTrustedHtml(value);

    Shorthand method. $sce.getTrustedHtml(value) → $sceDelegate.getTrusted($sce.HTML, value)

    参数

    参数 类型 详述
    value *

    The value to pass to $sce.getTrusted.

    返回值

    *

    The return value of $sce.getTrusted($sce.HTML, value)

  • getTrustedCss(value);

    Shorthand method. $sce.getTrustedCss(value) → $sceDelegate.getTrusted($sce.CSS, value)

    参数

    参数 类型 详述
    value *

    The value to pass to $sce.getTrusted.

    返回值

    *

    The return value of $sce.getTrusted($sce.CSS, value)

  • getTrustedUrl(value);

    Shorthand method. $sce.getTrustedUrl(value) → $sceDelegate.getTrusted($sce.URL, value)

    参数

    参数 类型 详述
    value *

    The value to pass to $sce.getTrusted.

    返回值

    *

    The return value of $sce.getTrusted($sce.URL, value)

  • getTrustedResourceUrl(value);

    Shorthand method. $sce.getTrustedResourceUrl(value) → $sceDelegate.getTrusted($sce.RESOURCE_URL, value)

    参数

    参数 类型 详述
    value *

    The value to pass to $sceDelegate.getTrusted.

    返回值

    *

    The return value of $sce.getTrusted($sce.RESOURCE_URL, value)

  • getTrustedJs(value);

    Shorthand method. $sce.getTrustedJs(value) → $sceDelegate.getTrusted($sce.JS, value)

    参数

    参数 类型 详述
    value *

    The value to pass to $sce.getTrusted.

    返回值

    *

    The return value of $sce.getTrusted($sce.JS, value)

  • parseAsHtml(expression);

    Shorthand method. $sce.parseAsHtml(expression string) → $sce.parseAs($sce.HTML, value)

    参数

    参数 类型 详述
    expression string

    String expression to compile.

    返回值

    function(context, locals)

    a function which represents the compiled expression:

    • context – {Object} – an object against which any expressions embedded in the strings are evaluated against (typically a scope object).
    • locals – {Object=} – local variables context object, useful for overriding values in context.

  • parseAsCss(expression);

    Shorthand method. $sce.parseAsCss(value) → $sce.parseAs($sce.CSS, value)

    参数

    参数 类型 详述
    expression string

    String expression to compile.

    返回值

    function(context, locals)

    a function which represents the compiled expression:

    • context – {Object} – an object against which any expressions embedded in the strings are evaluated against (typically a scope object).
    • locals – {Object=} – local variables context object, useful for overriding values in context.

  • parseAsUrl(expression);

    Shorthand method. $sce.parseAsUrl(value) → $sce.parseAs($sce.URL, value)

    参数

    参数 类型 详述
    expression string

    String expression to compile.

    返回值

    function(context, locals)

    a function which represents the compiled expression:

    • context – {Object} – an object against which any expressions embedded in the strings are evaluated against (typically a scope object).
    • locals – {Object=} – local variables context object, useful for overriding values in context.

  • parseAsResourceUrl(expression);

    Shorthand method. $sce.parseAsResourceUrl(value) → $sce.parseAs($sce.RESOURCE_URL, value)

    参数

    参数 类型 详述
    expression string

    String expression to compile.

    返回值

    function(context, locals)

    a function which represents the compiled expression:

    • context – {Object} – an object against which any expressions embedded in the strings are evaluated against (typically a scope object).
    • locals – {Object=} – local variables context object, useful for overriding values in context.

  • parseAsJs(expression);

    Shorthand method. $sce.parseAsJs(value) → $sce.parseAs($sce.JS, value)

    参数

    参数 类型 详述
    expression string

    String expression to compile.

    返回值

    function(context, locals)

    a function which represents the compiled expression:

    • context – {Object} – an object against which any expressions embedded in the strings are evaluated against (typically a scope object).
    • locals – {Object=} – local variables context object, useful for overriding values in context.


AngularJS: API: ng/service/$sceDelegate

$sceDelegate

  1. - $sceDelegateProvider
  2. - service in module ng

$sceDelegate is a service that is used by the $sce service to provide Strict Contextual Escaping (SCE) services to AngularJS.

Typically, you would configure or override the $sceDelegate instead of the $sce service to customize the way Strict Contextual Escaping works in AngularJS. This is because, while the $sce provides numerous shorthand methods, etc., you really only need to override 3 core functions (trustAs, getTrusted and valueOf) to replace the way things work because $sce delegates to $sceDelegate for these operations.

Refer $sceDelegateProvider to configure this service.

The default instance of $sceDelegate should work out of the box with little pain. While you can override it completely to change the behavior of $sce, the common case would involve configuring the $sceDelegateProvider instead by setting your own whitelists and blacklists for trusting URLs used for loading AngularJS resources such as templates. Refer $sceDelegateProvider.resourceUrlWhitelist and $sceDelegateProvider.resourceUrlBlacklist

用法

$sceDelegate();

方法

  • trustAs(Type, value);

    Returns an object that is trusted by angular for use in specified strict contextual escaping contexts (such as ng-bind-html, ng-include, any src attribute interpolation, any dom event binding attribute interpolation such as for onclick, etc.) that uses the provided value. See $sce for enabling strict contextual escaping.

    参数

    参数 类型 详述
    type string

    The kind of context in which this value is safe for use.例如 url, resourceUrl, html, js and css.
    value *

    The value that that should be considered trusted/safe.

    返回值

    *

    A value that can be used to stand in for the provided value in places where Angular expects a $sce.trustAs() return value.

  • valueOf(value);

    If the passed parameter had been returned by a prior call to $sceDelegate.trustAs, returns the value that had been passed to $sceDelegate.trustAs.

    If the passed parameter is not a value that had been returned by $sceDelegate.trustAs, returns it as-is.

    参数

    参数 类型 详述
    value *

    The result of a prior $sceDelegate.trustAs call or anything else.

    返回值

    *

    The value that was originally provided to $sceDelegate.trustAs if value is the result of such a call. Otherwise, returns value unchanged.

  • getTrusted(Type, maybeTrusted);

    Takes the result of a $sceDelegate.trustAs call and returns the originally supplied value if the queried context type is a supertype of the created type. If this condition isn't satisfied, throws an exception.

    参数

    参数 类型 详述
    type string

    The kind of context in which this value is to be used.
    maybeTrusted *

    The result of a prior $sceDelegate.trustAs call.

    返回值

    *

    The value the was originally provided to $sceDelegate.trustAs if valid in this context. Otherwise, throws an exception.


AngularJS: API: ng/service/$templateCache

$templateCache

  1. - service in module ng

The first time a template is used, it is loaded in the template cache for quick retrieval. You can load templates directly into the cache in a script tag, or by consuming the $templateCache service directly.

Adding via the script tag:

  <script Type="text/ng-template" id="templateId.html">
    <p>This is the content of the template</p>
  </script>

注意： the script tag containing the template does not need to be included in the head of the document, but it must be below the ng-app definition.

Adding via the $templateCache service:

var myApp = angular.module('myApp', []);
myApp.run(Function($templateCache) {
  $templateCache.put('templateId.html', 'This is the content of the template');
});

To retrieve the template later, simply use it in your HTML:

<div ng-include=" 'templateId.html' "></div>

or get it via Javascript:

$templateCache.get('templateId.html')

参见 $cacheFactory.


AngularJS: API: ng/service/$timeout

$timeout

  1. - service in module ng

Angular's wrapper for window.setTimeout. The fn function is wrapped into a try/catch block and delegates any exceptions to $exceptionHandler service.

The return value of registering a timeout function is a promise, which will be resolved when the timeout is reached and the timeout function is executed.

To cancel a timeout request, call $timeout.cancel(promise).

In tests you can use $timeout.flush() to synchronously flush the queue of deferred functions.

用法

$timeout(fn, [delay], [invokeApply]);

参数

参数 | 类型 | 详述
fn | function() | A function, whose execution should be delayed.
delay (可选) | number | Delay in milliseconds.
invokeApply (可选) | boolean | If set to false skips model dirty checking, otherwise will invoke fn within the $apply block.

返回值

Promise

Promise that will be resolved when the timeout is reached. The value this promise will be resolved with is the return value of the fn function.

方法

  • cancel([promise]);

    Cancels a task associated with the promise. As a result of this, the promise will be resolved with a rejection.

    参数

    参数 类型 详述
    promise
    (可选)
             Promise

    Promise returned by the $timeout function.

    返回值

    boolean

    返回值true if the task hasn't executed yet and was successfully canceled.


AngularJS: API: ng/service/$window

$window

  1. - service in module ng

A reference to the browser's window object. While window is globally available in JavaScript, it causes testability problems, because it is a global variable. In angular we always refer to it through the $window service, so it may be overridden, removed or mocked for testing.

Expressions, like the one defined for the ngClick directive in the example below, are evaluated with respect to the current scope. Therefore, there is no risk of inadvertently coding in a dependency on a global value in such an expression.

示例

index.html
<script>
  angular.module('windowExample', [])
    .controller('ExampleController', ['$scope', '$window', Function ($scope, $window) {
      $scope.greeting = 'Hello, World!';
      $scope.doGreeting = Function(greeting) {
        $window.alert(greeting);
      };
    }]);</script><div ng-controller="ExampleController">
  <input Type="text" ng-model="greeting" />
  <button ng-click="doGreeting(greeting)">ALERT</button></div>
protractor.js
it('should display the greeting in the input box', Function() {
 element(by.model('greeting')).sendKeys('Hello, E2E Tests');
 // If we click the button it will block the test runner
 // element(':button').click();});


AngularJS: API: ng/type

Type components in ng

名称 | 描述
angular.Module | Interface for configuring angular modules.
$cacheFactory.Cache | A cache object used to store and retrieve data, primarily used by $http and the script directive to cache templates and other data.
$compile.directive.Attributes | A shared object between directive compile / linking functions which contains normalized DOM element attributes. The values reflect current binding state {{ }}. The normalization is needed since all of these are treated as equivalent in Angular:
form.FormController | FormController keeps track of all its controls and nested forms as well as the state of them, such as being valid/invalid or dirty/pristine.
ngModel.NgModelController | NgModelController provides API for the ng-model directive. The controller contains services for data-binding, validation, CSS updates, and value formatting and parsing. It purposefully does not contain any logic which deals with DOM rendering or listening to DOM events. Such DOM related logic should be provided by other directives which make use of NgModelController for data-binding.
$rootScope.Scope | A root scope can be retrieved using the $rootScope key from the $injector. Child scopes are created using the $new() method. (Most scopes are created automatically when compiled HTML template is executed.)


AngularJS: API: ng/type/$cacheFactory.Cache

$cacheFactory.Cache

  1. - type in module ng

A cache object used to store and retrieve data, primarily used by $http and the script directive to cache templates and other data.

 angular.module('superCache')
   .factory('superCache', ['$cacheFactory', Function($cacheFactory) {
     return $cacheFactory('super-cache');
   }]);

Example test:

 it('should behave like a cache', inject(Function(superCache) {
   superCache.put('key', 'value');
   superCache.put('another key', 'another value');

   expect(superCache.info()).toEqual({
     id: 'super-cache',
     size: 2
   });

   superCache.remove('another key');
   expect(superCache.get('another key')).toBeUndefined();

   superCache.removeAll();
   expect(superCache.info()).toEqual({
     id: 'super-cache',
     size: 0
   });
 }));

方法

  • put(key, value);

    Inserts a named entry into the Cache object to be retrieved later, and incrementing the size of the cache if the key was not already present in the cache. If behaving like an LRU cache, it will also remove stale entries from the set.

    It will not insert undefined values into the cache.

    参数

    参数 类型 详述
    key string

    the key under which the cached data is stored.
    value *

    the value to store alongside the key. If it is undefined, the key will not be stored.

    返回值

    *

    the value stored.

  • get(key);

    Retrieves named data stored in the Cache object.

    参数

    参数 类型 详述
    key string

    the key of the data to be retrieved

    返回值

    *

    the value stored.

  • remove(key);

    Removes an entry from the Cache object.

    参数

    参数 类型 详述
    key string

    the key of the entry to be removed

  • removeAll();

    Clears the cache object of any entries.

  • destroy();

    Destroys the Cache object entirely, removing it from the $cacheFactory set.

  • info();

    Retrieve information regarding a particular Cache.

    返回值

    Object

    an object with the following properties:

    • id: the id of the cache instance
    • size: the number of entries kept in the cache instance
    • ...: any additional properties from the options object when creating the cache.


AngularJS: API: ng/type/$compile.directive.Attributes

$compile.directive.Attributes

  1. - type in module ng

A shared object between directive compile / linking functions which contains normalized DOM element attributes. The values reflect current binding state {{ }}. The normalization is needed since all of these are treated as equivalent in Angular:

   <span ng:bind="a" ng-bind="a" data-ng-bind="a" x-ng-bind="a">

方法

  • $addClass(classVal);

    Adds the CSS class value specified by the classVal parameter to the element. If animations are enabled then an animation will be triggered for the class addition.

    参数

    参数 类型 详述
    classVal string

    The className value that will be added to the element

  • $removeClass(classVal);

    Removes the CSS class value specified by the classVal parameter from the element. If animations are enabled then an animation will be triggered for the class removal.

    参数

    参数 类型 详述
    classVal string

    The className value that will be removed from the element

  • $updateClass(newClasses, oldClasses);

    Adds and removes the appropriate CSS class values to the element based on the difference between the new and old CSS class values (specified as newClasses and oldClasses).

    参数

    参数 类型 详述
    newClasses string

    The current CSS className value
    oldClasses string

    The former CSS className value

  • $observe(key, fn);

    Observes an interpolated attribute.

    The observer function will be invoked once during the next $digest following compilation. The observer is then invoked whenever the interpolated value changes.

    参数

    参数 类型 详述
    key string

    Normalized key. (ie ngAttribute) .
    fn function(interpolatedValue)

    Function that will be called whenever the interpolated value of the attribute changes. See the Directives guide for more info.

    返回值

    function()

    Returns a deregistration function for this observer.

  • $set(名称, value);

    Set DOM element attribute value.

    参数

    参数 类型 详述
    name string

    Normalized element attribute name of the property to modify. The name is reverse-translated using the $attr property to the original name.
    value string

    Value to set the attribute to. The value can be an interpolated string.

属性

  • $attr


AngularJS: API: ng/type/$rootScope.Scope

$rootScope.Scope

  1. - type in module ng

A root scope can be retrieved using the $rootScope key from the $injector. Child scopes are created using the $new() method. (Most scopes are created automatically when compiled HTML template is executed.)

Here is a simple scope snippet to show how you can interact with the scope.

<file src="./test/ng/rootScopeSpec.js" tag="docs1" />

Inheritance

A scope can inherit from a parent scope, as in this example:

         var parent = $rootScope;
         var child = parent.$new();

         parent.salutation = "Hello";
         child.name= "World";
         expect(child.salutation).toEqual('Hello');

         child.salutation = "Welcome";
         expect(child.salutation).toEqual('Welcome');
         expect(parent.salutation).toEqual('Hello');

用法

$rootScope.Scope([providers], [instanceCache]);

参数

参数 | 类型 | 详述
providers (可选) | Object.<string, function()>= | Map of service factory which need to be provided for the current scope. Defaults to ng.
instanceCache (可选) | Object.<string, *>= | Provides pre-instantiated services which should append/override services provided by providers. This is handy when unit-testing and having the need to override a default service.

返回值

Object

Newly created scope.

方法

  • $new(isolate);

    Creates a new child scope.

    The parent scope will propagate the $digest() and $digest() events. The scope can be removed from the scope hierarchy using $destroy().

    $destroy() must be called on a scope when it is desired for the scope and its child scopes to be permanently detached from the parent and thus stop participating in model change detection and listener notification by invoking.

    参数

    参数 类型 详述
    isolate boolean

    If true, then the scope does not prototypically inherit from the parent scope. The scope is isolated, as it can not see parent scope properties. When creating widgets, it is useful for the widget to not accidentally read parent state.

    返回值

    Object

    The newly created child scope.

  • $watch(watchExpression, [listener], [objectEquality]);

    Registers a listener callback to be executed whenever the watchExpression changes.

    • The watchExpression is called on every call to $digest() and should return the value that will be watched. (Since $digest() reruns when it detects changes the watchExpression can execute multiple times per $digest() and should be idempotent.)
    • The listener is called only when the value from the current watchExpression and the previous call to watchExpression are not equal (with the exception of the initial run, see below). Inequality is determined according to reference inequality, strict comparison via the !== Javascript operator, unless objectEquality == true (see next point)
    • When objectEquality == true, inequality of the watchExpression is determined according to the angular.equals function. To save the value of the object for later comparison, the angular.copy function is used. This therefore means that watching complex objects will have adverse memory and performance implications.
    • The watch listener may change the model, which may trigger other listeners to fire. This is achieved by rerunning the watchers until no changes are detected. The rerun iteration limit is 10 to prevent an infinite loop deadlock.

    If you want to be notified whenever $digest is called, you can register a watchExpression function with no listener. (Since watchExpression can execute multiple times per $digest cycle when a change is detected, be prepared for multiple calls to your listener.)

    After a watcher is registered with the scope, the listener fn is called asynchronously (via $evalAsync) to initialize the watcher. In rare cases, this is undesirable because the listener is called when the result of watchExpression didn't change. To detect this scenario within the listener fn, you can compare the newVal and oldVal. If these two values are identical (===) then the listener was called due to initialization.

    The example below contains an illustration of using a function as your $watch listener

    示例:

               // let's assume that scope was dependency injected as the $rootScope
           var scope = $rootScope;
           scope.name= 'misko';
           scope.counter = 0;

           expect(scope.counter).toEqual(0);
           scope.$watch('name', Function(newValue, oldValue) {
             scope.counter = scope.counter + 1;
           });
           expect(scope.counter).toEqual(0);

           scope.$digest();
           // the listener is always called during the first $digest loop after it was registered
           expect(scope.counter).toEqual(1);

           scope.$digest();
           // but now it will not be called unless the value changes
           expect(scope.counter).toEqual(1);

           scope.name= 'adam';
           scope.$digest();
           expect(scope.counter).toEqual(2);

           // Using a listener function
           var food;
           scope.foodCounter = 0;
           expect(scope.foodCounter).toEqual(0);
           scope.$watch(
             // This is the listener function
             Function() { return food; },
             // This is the change handler
             Function(newValue, oldValue) {
               if ( newValue !== oldValue ) {
                 // Only increment the counter if the value changed
                 scope.foodCounter = scope.foodCounter + 1;
               }
             }
           );
           // No digest has been run so the counter will be zero
           expect(scope.foodCounter).toEqual(0);

           // Run the digest but since food has not changed count will still be zero
           scope.$digest();
           expect(scope.foodCounter).toEqual(0);

           // Update food and run digest.  Now the counter will increment
           food = 'cheeseburger';
           scope.$digest();
           expect(scope.foodCounter).toEqual(1);

    参数

    参数 类型 详述
    watchExpression function() string

    Expression that is evaluated on each $digest cycle. A change in the return value triggers a call to the listener.

    • string: Evaluated as expression
    • Function(scope): called with current scope as a parameter.
    listener
    (可选)
             function()=

    Callback called whenever the return value of the watchExpression changes.

    • string: Evaluated as expression
    • Function(newValue, oldValue, scope): called with current and previous values as parameters.
    objectEquality
    (可选)
             boolean

    Compare for object equality using angular.equals instead of comparing for reference equality.

    返回值

    function()

    Returns a deregistration function for this listener.

  • $watchGroup(watchExpressions, listener);

    A variant of $watch() where it watches an array of watchExpressions. If any one expression in the collection changes the listener is executed.

    • The items in the watchExpressions array are observed via standard $watch operation and are examined on every call to $digest() to see if any items changes.
    • The listener is called whenever any expression in the watchExpressions array changes.

    参数

    参数 类型 详述
    watchExpressions Array.<string|Function(scope)>

    Array of expressions that will be individually watched using $watch()
    listener function(newValues, oldValues, scope)

    Callback called whenever the return value of any expression in watchExpressions changes The newValues array contains the current values of the watchExpressions, with the indexes matching those of watchExpression and the oldValues array contains the previous values of the watchExpressions, with the indexes matching those of watchExpression The scope refers to the current scope.

    返回值

    function()

    Returns a de-registration function for all listeners.

  • $watchCollection(obj, listener);

    Shallow watches the properties of an object and fires whenever any of the properties change (for arrays, this implies watching the array items; for object maps, this implies watching the properties). If a change is detected, the listener callback is fired.

    • The obj collection is observed via standard $watch operation and is examined on every call to $digest() to see if any items have been added, removed, or moved.
    • The listener is called whenever anything within the obj has changed. Examples include adding, removing, and moving items belonging to an object or array.

    示例:

              $scope.names = ['igor', 'matias', 'misko', 'james'];
          $scope.dataCount = 4;

          $scope.$watchCollection('names', Function(newNames, oldNames) {
            $scope.dataCount = newNames.length;
          });

          expect($scope.dataCount).toEqual(4);
          $scope.$digest();

          //still at 4 ... no changes
          expect($scope.dataCount).toEqual(4);

          $scope.names.pop();
          $scope.$digest();

          //now there's been a change
          expect($scope.dataCount).toEqual(3);

    参数

    参数 类型 详述
    obj string function(scope)

    Evaluated as expression. The expression value should evaluate to an object or an array which is observed on each $digest cycle. Any shallow change within the collection will trigger a call to the listener.
    listener function(newCollection, oldCollection, scope)

    a callback function called when a change is detected.

    • The newCollection object is the newly modified data obtained from the obj expression
    • The oldCollection object is a copy of the former collection data. Due to performance considerations, theoldCollection value is computed only if the listener function declares two or more arguments.
    • The scope argument refers to the current scope.

    返回值

    function()

    Returns a de-registration function for this listener. When the de-registration function is executed, the internal watch operation is terminated.

  • $digest();

    Processes all of the watchers of the current scope and its children. Because a watcher's listener can change the model, the $digest() keeps calling the watchers until no more listeners are firing. This means that it is possible to get into an infinite loop. This function will throw 'Maximum iteration limit exceeded.' if the number of iterations exceeds 10.

    Usually, you don't call $digest() directly in controllers or in directives. Instead, you should call $apply() (typically from within a Directive), which will force a $digest().

    If you want to be notified whenever $digest() is called, you can register a watchExpression function with $watch() with no listener.

    In unit tests, you may need to call $digest() to simulate the scope life cycle.

    示例:

               var scope = ...;
           scope.name= 'misko';
           scope.counter = 0;

           expect(scope.counter).toEqual(0);
           scope.$watch('name', Function(newValue, oldValue) {
             scope.counter = scope.counter + 1;
           });
           expect(scope.counter).toEqual(0);

           scope.$digest();
           // the listener is always called during the first $digest loop after it was registered
           expect(scope.counter).toEqual(1);

           scope.$digest();
           // but now it will not be called unless the value changes
           expect(scope.counter).toEqual(1);

           scope.name= 'adam';
           scope.$digest();
           expect(scope.counter).toEqual(2);

  • $destroy();

    Removes the current scope (and all of its children) from the parent scope. Removal implies that calls to $digest() will no longer propagate to the current scope and its children. Removal also implies that the current scope is eligible for garbage collection.

    The $destroy() is usually used by directives such as ngRepeat for managing the unrolling of the loop.

    Just before a scope is destroyed, a $destroy event is broadcasted on this scope. Application code can register a $destroy event handler that will give it a chance to perform any necessary cleanup.

    Note that, in AngularJS, there is also a $destroy jQuery event, which can be used to clean up DOM bindings before an element is removed from the DOM.

  • $eval([expression], [locals]);

    Executes the expression on the current scope and returns the result. Any exceptions in the expression are propagated (uncaught). This is useful when evaluating Angular表达式s.

    示例:

               var scope = ng.$rootScope.Scope();
           scope.a = 1;
           scope.b = 2;

           expect(scope.$eval('a+b')).toEqual(3);
           expect(scope.$eval(Function(scope){ return scope.a + scope.b; })).toEqual(3);

    参数

    参数 类型 详述
    expression
    (可选)
             string function()

    An Angular表达式 to be executed.

    • string: execute using the rules as defined in expression.
    • Function(scope): execute the function with the current scope parameter.
    locals
    (可选)
             Object

    Local variables object, useful for overriding values in scope.

    返回值

    *

    The result of evaluating the expression.

  • $evalAsync([expression]);

    Executes the expression on the current scope at a later point in time.

    The $evalAsync makes no guarantees as to when the expression will be executed, only that:

    • it will execute after the function that scheduled the evaluation (preferably before DOM rendering).
    • at least one $digest cycle will be performed after expression execution.

    Any exceptions from the execution of the expression are forwarded to the $exceptionHandler service.

    注意： if this function is called outside of a $digest cycle, a new $digest cycle will be scheduled. However, it is encouraged to always call code that changes the model from within an $apply call. That includes code evaluated via $evalAsync.

    参数

    参数 类型 详述
    expression
    (可选)
             string function()

    An Angular表达式 to be executed.

    • string: execute using the rules as defined in expression.
    • Function(scope): execute the function with the current scope parameter.

  • $apply([exp]);

    $apply() is used to execute an expression in angular from outside of the angular framework. (For example from browser DOM events, setTimeout, XHR or third party libraries). Because we are calling into the angular framework we need to perform proper scope life cycle of exception handling, executing watches.

    Life cycle

    Pseudo-Code of $apply()

               Function $apply(expr) {
             try {
               return $eval(expr);
             } catch (e) {
               $exceptionHandler(e);
             } finally {
               $root.$digest();
             }
           }

    Scope's $apply() method transitions through the following stages:

    1. The expression is executed using the $eval() method.
    2. Any exceptions from the execution of the expression are forwarded to the $exceptionHandler service.
    3. The watch listeners are fired immediately after the expression was executed using the $digest() method.

    参数

    参数 类型 详述
    exp
    (可选)
             string function()

    An Angular表达式 to be executed.

    • string: execute using the rules as defined in expression.
    • Function(scope): execute the function with current scope parameter.

    返回值

    *

    The result of evaluating the expression.

  • $on(名称, listener);

    Listens on events of a given type. See $emit for discussion of event life cycle.

    The event listener function format is: Function(event, args...). The event object passed into the listener has the following attributes:

    • targetScope - {Scope}: the scope on which the event was $emit-ed or $broadcast-ed.
    • currentScope - {Scope}: the scope that is currently handling the event. Once the event propagates through the scope hierarchy, this property is set to null.
    • 名称 - {string}: name of the event.
    • stopPropagation - {Function=}: calling stopPropagation function will cancel further event propagation (available only for events that were $emit-ed).
    • preventDefault - {Function}: calling preventDefault sets defaultPrevented flag to true.
    • defaultPrevented - {boolean}: true if preventDefault was called.

    参数

    参数 类型 详述
    name string

    Event name to listen on.
    listener function(event, ...args)

    Function to call when the event is emitted.

    返回值

    function()

    Returns a deregistration function for this listener.

  • $emit(名称, args);

    Dispatches an event 名称 upwards through the scope hierarchy notifying the registered $rootScope.Scope listeners.

    The event life cycle starts at the scope on which $emit was called. All listeners listening for 名称 event on this scope get notified. Afterwards, the event traverses upwards toward the root scope and calls all registered listeners along the way. The event will stop propagating if one of the listeners cancels it.

    Any exception emitted from the listeners will be passed onto the $exceptionHandler service.

    参数

    参数 类型 详述
    name string

    Event name to emit.
    args *

    Optional one or more arguments which will be passed onto the event listeners.

    返回值

    Object

    Event object (see $rootScope.Scope).

  • $broadcast(名称, args);

    Dispatches an event 名称 downwards to all child scopes (and their children) notifying the registered $rootScope.Scope listeners.

    The event life cycle starts at the scope on which $broadcast was called. All listeners listening for 名称 event on this scope get notified. Afterwards, the event propagates to all direct and indirect scopes of the current scope and calls all registered listeners along the way. The event cannot be canceled.

    Any exception emitted from the listeners will be passed onto the $exceptionHandler service.

    参数

    参数 类型 详述
    name string

    Event name to broadcast.
    args *

    Optional one or more arguments which will be passed onto the event listeners.

    返回值

    Object

    Event object, see $rootScope.Scope

事件

  • $destroy

    Broadcasted when a scope and its children are being destroyed.

    Note that, in AngularJS, there is also a $destroy jQuery event, which can be used to clean up DOM bindings before an element is removed from the DOM.

    类型:

    broadcast

    目标:

    scope being destroyed

属性

  • $id


AngularJS: API: ng/type/angular.Module

angular.Module

  1. - type in module ng

Interface for configuring angular modules.

方法

  • Provider(名称, providerType);

    参见 $provide.provider().

    参数

    参数 类型 详述
    name string

    service name
    providerType Function

    Construction function for creating new instance of the service.

  • factory(名称, providerFunction);

    参见 $provide.factory().

    参数

    参数 类型 详述
    name string

    service name
    providerFunction Function

    Function for creating new instance of the service.

  • Service(名称, constructor);

    参见 $provide.service().

    参数

    参数 类型 详述
    name string

    service name
    constructor Function

    A constructor function that will be instantiated.

  • value(名称, Object);

    参见 $provide.value().

    参数

    参数 类型 详述
    name string

    service name
    object *

    Service instance object.

  • constant(名称, Object);

    Because the constant are fixed, they get applied before other provide methods. See $provide.constant().

    参数

    参数 类型 详述
    name string

    constant name
    object *

    Constant value.

  • animation(名称, animationFactory);

    注意: animations take effect only if the ngAnimate module is loaded.

    Defines an animation hook that can be later used with $animate service and directives that use this service.

    module.animation('.animation-name', Function($inject1, $inject2) {
  return {
    eventName : Function(element, done) {
      //code to run the animation
      //once complete, then run done()
      return Function cancellationFunction(element) {
        //code to cancel the animation
      }
    }
  }
})

    参见 $animateProvider.register() and ngAnimate module for more information.

    参数

    参数 类型 详述
    name string

    animation name
    animationFactory Function

    Factory function for creating new instance of an animation.

  • Filter(名称, filterFactory);

    参见 $filterProvider.register().

    参数

    参数 类型 详述
    name string

    Filter name.
    filterFactory Function

    Factory function for creating new instance of filter.

  • controller(名称, constructor);

    参见 $controllerProvider.register().

    参数

    参数 类型 详述
    name string Object

    Controller name, or an object map of controllers where the keys are the names and the values are the constructors.
    constructor Function

    Controller constructor function.

  • Directive(名称, directiveFactory);

    参见 $compileProvider.directive().

    参数

    参数 类型 详述
    name string Object

    Directive name, or an object map of directives where the keys are the names and the values are the factories.
    directiveFactory Function

    Factory function for creating new instance of directives.

  • config(configFn);

    Use this method to register work which needs to be performed on module loading. For more about how to configure services, see Provider Recipe.

    参数

    参数 类型 详述
    configFn Function

    Execute this function on module load. Useful for service configuration.

  • run(initializationFn);

    Use this method to register work which should be performed when the injector is done loading all modules.

    参数

    参数 类型 详述
    initializationFn Function

    Execute this function after injector creation. Useful for application initialization.

属性

  • requires

    Holds the list of modules which the injector will load before the current module is loaded.

  • 名称


AngularJS: API: ng/type/form.FormController

form.FormController

  1. - type in module ng

FormController keeps track of all its controls and nested forms as well as the state of them, such as being valid/invalid or dirty/pristine.

Each form directive creates an instance of FormController.

方法

  • $rollbackViewValue();

    Rollback all form controls pending updates to the $modelValue.

    Updates may be pending by a debounced event or because the input is waiting for a some future event defined in ng-model-options. This method is typically needed by the reset button of a form that uses ng-model-options to pend updates.

  • $commitViewValue();

    Commit all form controls pending updates to the $modelValue.

    Updates may be pending by a debounced event or because the input is waiting for a some future event defined in ng-model-options. This method is rarely needed as NgModelController usually handles calling this in response to input events.

  • $addControl();

    Register a control with the form.

    Input elements using ngModelController do this automatically when they are linked.

  • $removeControl();

    Deregister a control from the form.

    Input elements using ngModelController do this automatically when they are destroyed.

  • $setValidity();

    Sets the validity of a form control.

    This method will also propagate to parent forms.

  • $setDirty();

    Sets the form to a dirty state.

    This method can be called to add the 'ng-dirty' class and set the form to a dirty state (ng-dirty class). This method will also propagate to parent forms.

  • $setPristine();

    Sets the form to its pristine state.

    This method can be called to remove the 'ng-dirty' class and set the form to its pristine state (ng-pristine class). This method will also propagate to all the controls contained in this form.

    Setting a form back to a pristine state is often useful when we want to 'reuse' a form after saving or resetting it.

属性

  • $pristine

    boolean

    True if user has not interacted with the form yet.

  • $dirty

    boolean

    True if user has already interacted with the form.

  • $valid

    boolean

    True if all of the containing forms and controls are valid.

  • $invalid

    boolean

    True if at least one containing control or form is invalid.

  • $error

    Object

    Is an object hash, containing references to all invalid controls or forms, where:

    • keys are validation tokens (error names),
    • values are arrays of controls or forms that are invalid for given error name.

    Built-in validation tokens:

    • email
    • max
    • maxlength
    • min
    • minlength
    • number
    • pattern
    • required
    • url


AngularJS: API: ng/type/ngModel.NgModelController

ngModel.NgModelController

  1. - type in module ng

NgModelController provides API for the ng-model directive. The controller contains services for data-binding, validation, CSS updates, and value formatting and parsing. It purposefully does not contain any logic which deals with DOM rendering or listening to DOM events. Such DOM related logic should be provided by other directives which make use of NgModelController for data-binding.

Custom Control Example

This example shows how to use NgModelController with a custom control to achieve data-binding. Notice how different directives (contenteditable, ng-model, and required) collaborate together to achieve the desired result.

Note that contenteditable is an HTML5 attribute, which tells the browser to let the element contents be edited in place by the user. This will not work on older browsers.

We are using the $sce service here and include the $sanitize module to automatically remove "bad" content like inline event listener (如： <span onclick="...">). However, as we are using $sce the model can still decide to to provide unsafe content if it marks that content using the $sce service.

style.css
[contenteditable] {
  border: 1px solid black;
  background-color: white;
  min-height: 20px;}

.ng-invalid {
  border: 1px solid red;}
script.js
angular.module('customControl', ['ngSanitize']).
  directive('contenteditable', ['$sce', Function($sce) {
    return {
      restrict: 'A', // only activate on element attribute
      require: '?ngModel', // get a hold of NgModelController
      link: Function(scope, element, attrs, ngModel) {
        if(!ngModel) return; // do nothing if no ng-model

        // Specify how UI should be updated
        ngModel.$render = Function() {
          element.html($sce.getTrustedHtml(ngModel.$viewValue || ''));
        };

        // Listen for change events to enable binding
        element.on('blur keyup change', Function() {
          scope.$apply(read);
        });
        read(); // initialize

        // Write data to the model
        Function read() {
          var html = element.html();
          // When we clear the content editable the browser leaves a <br> behind
          // If strip-br attribute is provided then we strip this out
          if( attrs.stripBr && html == '<br>' ) {
            html = '';
          }
          ngModel.$setViewValue(html);
        }
      }
    };
  }]);
index.html
<form 名称="myForm">
 <div contenteditable
      名称="myWidget" ng-model="userContent"
      strip-br="true"
      required>Change me!</div>
  <span ng-show="myForm.myWidget.$error.required">Required!</span>
 <hr>
 <textarea ng-model="userContent"></textarea></form>
protractor.js
it('should data-bind and become invalid', Function() {if (browser.params.browser == 'safari' || browser.params.browser == 'firefox') {
  // SafariDriver can't handle contenteditable
  // and Firefox driver can't clear contenteditables very well
  return;}var contentEditable = element(by.css('[contenteditable]'));var content = 'Change me!';

expect(contentEditable.getText()).toEqual(content);

contentEditable.clear();
contentEditable.sendKeys(protractor.Key.BACK_SPACE);
expect(contentEditable.getText()).toEqual('');
expect(contentEditable.getAttribute('class')).toMatch(/ng-invalid-required/);});

方法

  • $render();

    Called when the view needs to be updated. It is expected that the user of the ng-model directive will implement this method.

    The $render() method is invoked in the following situations:

    • $rollbackViewValue() is called. If we are rolling back the view value to the last committed value then $render() is called to update the input control.
    • The value referenced by ng-model is changed programmatically and both the $modelValue and the $viewValue are different to last time.

    Since ng-model does not do a deep watch, $render() is only invoked if the values of $modelValue and $viewValue are actually different to their previous value. If $modelValue or $viewValue are objects (rather than a string or number) then $render() will not be invoked if you only change a property on the objects.

  • $isEmpty(value);

    This is called when we need to determine if the value of the input is empty.

    For instance, the required directive does this to work out if the input has data or not. The default $isEmpty function checks whether the value is undefined, '', null or NaN.

    You can override this for input directives whose concept of being empty is different to the default. The checkboxInputType directive does this because in its case a value of false implies empty.

    参数

    参数 类型 详述
    value *

    用于检测的引用。

    返回值

    boolean

    True if value is empty.

  • $setValidity(validationErrorKey, isValid);

    Change the validity state, and notifies the form when the control changes validity. (i.e. it does not notify form if given validator is already marked as invalid).

    This method can be called within $parsers/$formatters. However, if possible, please use the ngModel.$validators pipeline which is designed to handle validations with true/false values.

    参数

    参数 类型 详述
    validationErrorKey string

    Name of the validator. the validationErrorKey will assign to $error[validationErrorKey]=!isValid so that it is available for data-binding. The validationErrorKey should be in camelCase and will get converted into dash-case for class name. Example: myError will result in ng-valid-my-error and ng-invalid-my-error class and can be bound to as {{someForm.someControl.$error.myError}} .

    isValid boolean

    Whether the current state is valid (true) or invalid (false).

  • $setPristine();

    Sets the control to its pristine state.

    This method can be called to remove the 'ng-dirty' class and set the control to its pristine state (ng-pristine class). A model is considered to be pristine when the model has not been changed from when first compiled within then form.

  • $setUntouched();

    Sets the control to its untouched state.

    This method can be called to remove the 'ng-touched' class and set the control to its untouched state (ng-untouched class). Upon compilation, a model is set as untouched 默认情况下， however this function can be used to restore that state if the model has already been touched by the user.

  • $setTouched();

    Sets the control to its touched state.

    This method can be called to remove the 'ng-untouched' class and set the control to its touched state (ng-touched class). A model is considered to be touched when the user has first interacted (focussed) on the model input element and then shifted focus away (blurred) from the input element.

  • $rollbackViewValue();

    Cancel an update and reset the input element's value to prevent an update to the $modelValue, which may be caused by a pending debounced event or because the input is waiting for a some future事件上。

    If you have an input that uses ng-model-options to set up debounced events or events such as blur you can have a situation where there is a period when the $viewValue is out of synch with the ngModel's $modelValue.

    In this case, you can run into difficulties if you try to update the ngModel's $modelValue programmatically before these debounced/future events have resolved/occurred, because Angular's dirty checking mechanism is not able to tell whether the model has actually changed or not.

    The $rollbackViewValue() method should be called before programmatically changing the model of an input which may have such events pending. This is important in order to make sure that the input field will be updated with the new model value and any pending operations are cancelled.

    app.js
    angular.module('cancel-update-example', [])

.controller('CancelUpdateController', ['$scope', Function($scope) {
  $scope.resetWithCancel = Function (e) {
    if (e.keyCode == 27) {
      $scope.myForm.myInput1.$rollbackViewValue();
      $scope.myValue = '';
    }
  };
  $scope.resetWithoutCancel = Function (e) {
    if (e.keyCode == 27) {
      $scope.myValue = '';
    }
  };}]);
    index.html
    <div ng-controller="CancelUpdateController">
  <p>Try typing something in each input.  See that the model only updates when you
     blur off the input.
   </p>
   <p>Now see what happens if you start typing then press the Escape key</p>

  <form 名称="myForm" ng-model-options="{ updateOn: 'blur' }">
    <p>With $rollbackViewValue()</p>
    <input 名称="myInput1" ng-model="myValue" ng-keydown="resetWithCancel($event)"><br/>
    myValue: "{{ myValue }}"

    <p>Without $rollbackViewValue()</p>
    <input 名称="myInput2" ng-model="myValue" ng-keydown="resetWithoutCancel($event)"><br/>
    myValue: "{{ myValue }}"
  </form></div>

  • $validate();

    Runs each of the registered validations set on the $validators object.

  • $commitViewValue();

    Commit a pending update to the $modelValue.

    Updates may be pending by a debounced event or because the input is waiting for a some future event defined in ng-model-options. this method is rarely needed as NgModelController usually handles calling this in response to input events.

  • $setViewValue(value, trigger);

    Update the view value.

    This method should be called when an input directive want to change the view value; typically, this is done from within a DOM event handler.

    For example input calls it when the value of the input changes and select calls it when an option is selected.

    If the new value is an object (rather than a string or a number), we should make a copy of the object before passing it to $setViewValue. This is because ngModel does not perform a deep watch of objects, it only looks for a change of identity. If you only change the property of the object then ngModel will not realise that the object has changed and will not invoke the $parsers and $validators pipelines.

    For this reason, you should not change properties of the copy once it has been passed to $setViewValue. Otherwise you may cause the model value on the scope to change incorrectly.

    When this method is called, the new value will be staged for committing through the $parsers and $validators pipelines. If there are no special ngModelOptions specified then the staged value sent directly for processing, finally to be applied to $modelValue and then the expression specified in the ng-model attribute.

    Lastly, all the registered change listeners, in the $viewChangeListeners list, are called.

    In case the ngModelOptions directive is used with updateOn and the default trigger is not listed, all those actions will remain pending until one of the updateOn events is triggered on the DOM element. All these actions will be debounced if the ngModelOptions directive is used with a custom debounce for this particular事件上。

    Note that calling this function does not trigger a $digest.

    参数

    参数 类型 详述
    value string

    Value from the view.

    trigger string

    Event that triggered the update.

属性

  • $viewValue

    string

    Actual string value in the view.

  • $modelValue

    *

    The value in the model, that the control is bound to.

  • $parsers

    Array.<Function>

    Array of functions to execute, as a pipeline, whenever the control reads value from the DOM. Each function is called, in turn, passing the value through to the next. The last return value is used to populate the model. Used to sanitize / convert the value as well as validation. For validation, the parsers should update the validity state using $setValidity(), and return undefined for invalid values.

  • $formatters

    Array.<Function>

    Array of functions to execute, as a pipeline, whenever the model value changes. Each function is called, in turn, passing the value through to the next. Used to format / convert values for display in the control and validation.

    Function formatter(value) {
  if (value) {
    return value.toUpperCase();
  }}
ngModel.$formatters.push(formatter);

  • $validators

    Object.<string, function>

    A collection of validators that are applied whenever the model value changes. The key value within the object refers to the name of the validator while the function refers to the validation operation. The validation operation is provided with the model value as an argument and must return a true or false value depending on the response of that validation.

  • $viewChangeListeners

    Array.<Function>

    Array of functions to execute whenever the view value has changed. It is called with no arguments, and its return value is ignored. This can be used in place of additional $watches against the model value.

  • $error

    Object

    An object hash with all errors as keys.

  • $untouched

    boolean

    True if control has not lost focus yet.

  • $touched

    boolean

    True if control has lost focus.

  • $pristine

    boolean

    True if user has not interacted with the control yet.

  • $dirty

    boolean

    True if user has already interacted with the control.

  • $valid

    boolean

    True if there is no error.

  • $invalid

    boolean

    True if at least one error on the control.


AngularJS: API: ngAnimate

ngAnimate

The ngAnimate module provides support for JavaScript, CSS3 transition and CSS3 keyframe animation hooks within existing core and custom directives.

用法

To see animations in action, all that is required is to define the appropriate CSS classes or to register a JavaScript animation via the myModule.animation() function. The directives that support animation automatically are: ngRepeat, ngInclude, ngIf, ngSwitch, ngShow, ngHide, ngView and ngClass. Custom directives can take advantage of animation by using the $animate service.

Below is a more detailed breakdown of the supported animation events provided by pre-existing ng directives:

Directive | Supported Animations
ngRepeat | enter, leave and move
ngView | enter and leave
ngInclude | enter and leave
ngSwitch | enter and leave
ngIf | enter and leave
ngClass | add and remove (the CSS class(es) present)
ngShow & ngHide | add and remove (the ng-hide class value)
form & ngModel | add and remove (dirty, pristine, valid, invalid & all other validations)
ngMessages | add and remove (ng-active & ng-inactive)
ngMessage | enter and leave

You can find out more information about animations upon visiting each directive page.

Below is an example of how to apply animations to a directive that supports animation hooks:

<style Type="text/css">
.slide.ng-enter, .slide.ng-leave {
  -webkit-transition:0.5s linear all;
  transition:0.5s linear all;
}

.slide.ng-enter { }        /* starting animations for enter */
.slide.ng-enter.ng-enter-active { } /* terminal animations for enter */
.slide.ng-leave { }        /* starting animations for leave */
.slide.ng-leave.ng-leave-active { } /* terminal animations for leave */
</style>

<!--
the animate service will automatically add .ng-enter and .ng-leave to the element
to trigger the CSS transition/animations
-->
<ANY class="slide" ng-include="..."></ANY>

记住，默认情况下， if an animation is running, any child elements cannot be animated until the parent element's animation has completed. This blocking feature can be overridden by placing the ng-animate-children attribute on a parent container tag.

<div class="slide-animation" ng-if="on" ng-animate-children>
  <div class="fade-animation" ng-if="on">
    <div class="explode-animation" ng-if="on">
       ...
    </div>
  </div>
</div>

When the on expression value changes and an animation is triggered then each of the elements within will all animate without the block being applied to child elements.

CSS-defined Animations

The animate service will automatically apply two CSS classes to the animated element and these two CSS classes are designed to contain the start and end CSS styling. Both CSS transitions and keyframe animations are supported and can be used to play along with this naming structure.

The following code below demonstrates how to perform animations using CSS transitions with Angular:

<style Type="text/css">
/*
 The animate class is apart of the element and the ng-enter class
 is attached to the element once the enter animation event is triggered
*/
.reveal-animation.ng-enter {
 -webkit-transition: 1s linear all; /* Safari/Chrome */
 transition: 1s linear all; /* All other modern browsers and IE10+ */

 /* The animation preparation code */
 opacity: 0;
}

/*
 记住， that you want to combine both CSS
 classes together to avoid any CSS-specificity
 conflicts
*/
.reveal-animation.ng-enter.ng-enter-active {
 /* The animation code itself */
 opacity: 1;
}
</style>

<div class="view-container">
  <div ng-view class="reveal-animation"></div>
</div>

The following code below demonstrates how to perform animations using CSS animations with Angular:

<style Type="text/css">
.reveal-animation.ng-enter {
  -webkit-animation: enter_sequence 1s linear; /* Safari/Chrome */
  animation: enter_sequence 1s linear; /* IE10+ and Future Browsers */
}
@-webkit-keyframes enter_sequence {
  from { opacity:0; }
  to { opacity:1; }
}
@keyframes enter_sequence {
  from { opacity:0; }
  to { opacity:1; }
}
</style>

<div class="view-container">
  <div ng-view class="reveal-animation"></div>
</div>

Both CSS3 animations and transitions can be used together and the animate service will figure out the correct duration and delay timing.

Upon DOM mutation, the event class is added first (something like ng-enter), then the browser prepares itself to add the active class (in this case ng-enter-active) which then triggers the animation. The animation module will automatically detect the CSS code to determine when the animation ends. Once the animation is over then both CSS classes will be removed from the DOM. If a browser does not support CSS transitions or CSS animations then the animation will start and end immediately resulting in a DOM element that is at its final state. This final state is when the DOM element has no CSS transition/animation classes applied to it.

Structural transition animations

Structural transitions (such as enter, leave and move) will always apply a 0s none transition value to force the browser into rendering the styles defined in the setup (.ng-enter, .ng-leave or .ng-move) class. This means that any active transition animations operating on the element will be cut off to make way for the enter, leave or move animation.

Class-based transition animations

Class-based transitions refer to transition animations that are triggered when a CSS class is added to or removed from the element (via $animate.addClass, $animate.removeClass, $animate.setClass, or by directives such as ngClass, ngModel and form). They are different when compared to structural animations since they do not cancel existing animations nor do they block successive transitions from rendering on the same element. This distinction allows for multiple class-based transitions to be performed on the same element.

In addition to ngAnimate supporting the default (natural) functionality of class-based transition animations, ngAnimate also decorates the element with starting and ending CSS classes to aid the developer in further styling the element throughout the transition animation. Earlier versions of ngAnimate may have caused natural CSS transitions to break and not render properly due to $animate temporarily blocking transitions using 0s none in order to allow the setup CSS class (the -add or -remove class) to be applied without triggering an animation. However, as of version 1.3, this workaround has been removed with ngAnimate and all non-ngAnimate CSS class transitions are compatible with ngAnimate.

There is, however, one special case when dealing with class-based transitions in ngAnimate. When rendering class-based transitions that make use of the setup and active CSS classes (如： .fade-add and .fade-add-active for when .fade is added) be sure to define the transition value on the active CSS class and not the setup class.

.fade-add {
  /* remember to place a 0s transition here
     to ensure that the styles are applied instantly
     even if the element already has a transition style */
  transition:0s linear all;

  /* starting CSS styles */
  opacity:1;
}
.fade-add.fade-add-active {
  /* this will be the length of the animation */
  transition:1s linear all;
  opacity:0;
}

The setup CSS class (in this case .fade-add) also has a transition style property, however, it has a duration of zero. This may not be required, however, incase the browser is unable to render the styling present in this CSS class instantly then it could be that the browser is attempting to perform an unnecessary transition.

This workaround, however, does not apply to standard class-based transitions that are rendered when a CSS class containing a transition is applied to an element:

.fade {
  /* this works as expected */
  transition:1s linear all;
  opacity:0;
}

Please keep this in mind when coding the CSS markup that will be used within class-based transitions. Also, try not to mix the two class-based animation flavors together since the CSS code may become overly complex.

CSS Staggering Animations

A Staggering animation is a collection of animations that are issued with a slight delay in between each successive operation resulting in a curtain-like effect. The ngAnimate module, as of 1.2.0, supports staggering animations and the stagger effect can be performed by creating a ng-EVENT-stagger CSS class and attaching that class to the base CSS class used for the animation. The style property expected within the stagger class can either be a transition-delay or an animation-delay property (or both if your animation contains both transitions and keyframe animations).

.my-animation.ng-enter {
  /* standard transition code */
  -webkit-transition: 1s linear all;
  transition: 1s linear all;
  opacity:0;
}
.my-animation.ng-enter-stagger {
  /* this will have a 100ms delay between each successive leave animation */
  -webkit-transition-delay: 0.1s;
  transition-delay: 0.1s;

  /* in case the stagger doesn't work then these two values
   must be set to 0 to avoid an accidental CSS inheritance */
  -webkit-transition-duration: 0s;
  transition-duration: 0s;
}
.my-animation.ng-enter.ng-enter-active {
  /* standard transition styles */
  opacity:1;
}

Staggering animations work by default in ngRepeat (so long as the CSS class is defined). Outside of ngRepeat, to use staggering animations on your own, they can be triggered by firing multiple calls to the same event on $animate. However, the restrictions surrounding this are that each of the elements must have the same CSS className value as well as the same parent element. A stagger operation will also be reset if more than 10ms has passed after the last animation has been fired.

The following code will issue the ng-leave-stagger event on the element provided:

var kids = parent.children();

$animate.leave(kids[0]); //stagger index=0
$animate.leave(kids[1]); //stagger index=1
$animate.leave(kids[2]); //stagger index=2
$animate.leave(kids[3]); //stagger index=3
$animate.leave(kids[4]); //stagger index=4

$timeout(Function() {
  //stagger has reset itself
  $animate.leave(kids[5]); //stagger index=0
  $animate.leave(kids[6]); //stagger index=1
}, 100, false);

Stagger animations are currently only supported within CSS-defined animations.

JavaScript-defined Animations

In the event that you do not want to use CSS3 transitions or CSS3 animations or if you wish to offer animations on browsers that do not yet support CSS transitions/animations, then you can make use of JavaScript animations defined inside of your AngularJS module.

//!annotate="YourApp" Your AngularJS Module|Replace this or ngModule with the module that you used to define your application.
var ngModule = angular.module('YourApp', ['ngAnimate']);
ngModule.animation('.my-crazy-animation', Function() {
  return {
    enter: Function(element, done) {
      //run the animation here and call done when the animation is complete
      return Function(cancelled) {
        //this (可选) function will be called when the animation
        //completes or when the animation is cancelled (the cancelled
        //flag will be set to true if cancelled).
      };
    },
    leave: Function(element, done) { },
    move: Function(element, done) { },

    //animation that can be triggered before the class is added
    beforeAddClass: Function(element, className, done) { },

    //animation that can be triggered after the class is added
    addClass: Function(element, className, done) { },

    //animation that can be triggered before the class is removed
    beforeRemoveClass: Function(element, className, done) { },

    //animation that can be triggered after the class is removed
    removeClass: Function(element, className, done) { }
  };
});

JavaScript-defined animations are created with a CSS-like class selector and a collection of events which are set to run a javascript callback function. When an animation is triggered, $animate will look for a matching animation which fits the element's CSS class attribute value and then run the matching animation event function (if found). In other words, if the CSS classes present on the animated element match any of the JavaScript animations then the callback function will be executed. It should be also noted that only simple, single class selectors are allowed (compound class selectors are not supported).

Within a JavaScript animation, an object containing various event callback animation functions is expected to be returned. As explained above, these callbacks are triggered based on the animation event. Therefore if an enter animation is run, and the JavaScript animation is found, then the enter callback will handle that animation (in addition to the CSS keyframe animation or transition code that is defined via a stylesheet).

Installation

First include angular-animate.js in your HTML:

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

You can download this file from the following places:

  • Google CDN
    例如 //ajax.googleapis.com/ajax/libs/angularjs/X.Y.Z/angular-animate.js
  • Bower
    例如
    bower install angular-animate@X.Y.Z
  • code.angularjs.org
    例如
    "//code.angularjs.org/X.Y.Z/angular-animate.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', ['ngAnimate']);

With that you're ready to get started!

模块组件

Provider

名称 | 描述
$animateProvider | The $animateProvider allows developers to register JavaScript animation event handlers directly inside of a module. When an animation is triggered, the $animate service will query the $animate service to find any animations that match the provided name value.

Service

名称 | 描述
$animate | The $animate service provides animation detection support while performing DOM operations (enter, leave and move) as well as during addClass and removeClass operations. When any of these operations are run, the $animate service will examine any JavaScript-defined animations (which are defined by using the $animateProvider provider object) as well as any CSS-defined animations against the CSS classes present on the element once the DOM operation is run.


AngularJS: API: ngAnimate/provider

Provider components in ngAnimate

名称 | 描述
$animateProvider | The $animateProvider allows developers to register JavaScript animation event handlers directly inside of a module. When an animation is triggered, the $animate service will query the $animate service to find any animations that match the provided name value.


AngularJS: API: ngAnimate/provider/$animateProvider

$animateProvider

  1. - $animate
  2. - provider in module ngAnimate

The $animateProvider allows developers to register JavaScript animation event handlers directly inside of a module. When an animation is triggered, the $animate service will query the $animate service to find any animations that match the provided name value.

Requires the ngAnimate module to be installed.

Please visit the ngAnimate module overview page learn more about how to use animations in your application.


AngularJS: API: ngAnimate/service

Service components in ngAnimate

名称 | 描述
$animate | The $animate service provides animation detection support while performing DOM operations (enter, leave and move) as well as during addClass and removeClass operations. When any of these operations are run, the $animate service will examine any JavaScript-defined animations (which are defined by using the $animateProvider provider object) as well as any CSS-defined animations against the CSS classes present on the element once the DOM operation is run.


AngularJS: API: ngAnimate/service/$animate

$animate

  1. - $animateProvider
  2. - service in module ngAnimate

The $animate service provides animation detection support while performing DOM operations (enter, leave and move) as well as during addClass and removeClass operations. When any of these operations are run, the $animate service will examine any JavaScript-defined animations (which are defined by using the $animateProvider provider object) as well as any CSS-defined animations against the CSS classes present on the element once the DOM operation is run.

The $animate service is used behind the scenes with pre-existing directives and animation with these directives will work out of the box without any extra configuration.

Requires the ngAnimate module to be installed.

Please visit the ngAnimate module overview page learn more about how to use animations in your application.

用法

$animate();

方法

  • enter(element, parentElement, afterElement, [doneCallback]);

    Appends the element to the parentElement element that resides in the document and then runs the enter animation. Once the animation is started, the following CSS classes will be present on the element for the duration of the animation:

    Below is a breakdown of each step that occurs during enter animation:

    动画步骤 | 元素的class属性看上去像
    1. $animate.enter(...) is called | class="my-animation"
    2. element is inserted into the parentElement element or beside the afterElement element | class="my-animation"
    3. $animate waits for the next digest to start the animation | class="my-animation ng-animate"
    4. $animate runs the JavaScript-defined animations detected on the element | class="my-animation ng-animate"
    5. the .ng-enter class is added to the element | class="my-animation ng-animate ng-enter"
    6. $animate scans the element styles to get the CSS transition/animation duration and delay | class="my-animation ng-animate ng-enter"
    7. $animate blocks all CSS transitions on the element to ensure the .ng-enter class styling is applied right away | class="my-animation ng-animate ng-enter"
    8. $animate waits for a single animation frame (this performs a reflow) | class="my-animation ng-animate ng-enter"
    9. $animate removes the CSS transition block placed on the element | class="my-animation ng-animate ng-enter"
    10. the .ng-enter-active class is added (this triggers the CSS transition/animation) | class="my-animation ng-animate ng-enter ng-enter-active"
    11. $animate waits for the animation to complete (via events and timeout) | class="my-animation ng-animate ng-enter ng-enter-active"
    12. The animation ends and all generated CSS classes are removed from the element | class="my-animation"
    13. The doneCallback() callback is fired (if provided) | class="my-animation"

    参数

    参数 类型 详述
    element DOMElement

    the element that will be the focus of the enter animation
    parentElement DOMElement

    the parent element of the element that will be the focus of the enter animation
    afterElement DOMElement

    the sibling element (which is the previous element) of the element that will be the focus of the enter animation
    doneCallback
    (可选)
             function()=

    the callback function that will be called once the animation is complete

    返回值

    Function

    the animation cancellation function

  • leave(element, [doneCallback]);

    Runs the leave animation operation and, upon completion, removes the element from the DOM. Once the animation is started, the following CSS classes will be added for the duration of the animation:

    Below is a breakdown of each step that occurs during leave animation:

    动画步骤 | 元素的class属性看上去像
    1. $animate.leave(...) is called | class="my-animation"
    2. $animate runs the JavaScript-defined animations detected on the element | class="my-animation ng-animate"
    3. $animate waits for the next digest to start the animation | class="my-animation ng-animate"
    4. the .ng-leave class is added to the element | class="my-animation ng-animate ng-leave"
    5. $animate scans the element styles to get the CSS transition/animation duration and delay | class="my-animation ng-animate ng-leave"
    6. $animate blocks all CSS transitions on the element to ensure the .ng-leave class styling is applied right away | class="my-animation ng-animate ng-leave”
    7. $animate waits for a single animation frame (this performs a reflow) | class="my-animation ng-animate ng-leave"
    8. $animate removes the CSS transition block placed on the element | class="my-animation ng-animate ng-leave”
    9. the .ng-leave-active class is added (this triggers the CSS transition/animation) | class="my-animation ng-animate ng-leave ng-leave-active"
    10. $animate waits for the animation to complete (via events and timeout) | class="my-animation ng-animate ng-leave ng-leave-active"
    11. The animation ends and all generated CSS classes are removed from the element | class="my-animation"
    12. The element is removed from the DOM ...
    13. The doneCallback() callback is fired (if provided) ...

    参数

    参数 类型 详述
    element DOMElement

    the element that will be the focus of the leave animation
    doneCallback
    (可选)
             function()=

    the callback function that will be called once the animation is complete

    返回值

    Function

    the animation cancellation function

  • move(element, parentElement, afterElement, [doneCallback]);

    Fires the move DOM operation. Just before the animation starts, the animate service will either append it into the parentElement container or add the element directly after the afterElement element if present. Then the move animation will be run. Once the animation is started, the following CSS classes will be added for the duration of the animation:

    Below is a breakdown of each step that occurs during move animation:

    动画步骤 | 元素的class属性看上去像
    1. $animate.move(...) is called | class="my-animation"
    2. element is moved into the parentElement element or beside the afterElement element | class="my-animation"
    3. $animate waits for the next digest to start the animation | class="my-animation ng-animate"
    4. $animate runs the JavaScript-defined animations detected on the element | class="my-animation ng-animate"
    5. the .ng-move class is added to the element | class="my-animation ng-animate ng-move"
    6. $animate scans the element styles to get the CSS transition/animation duration and delay | class="my-animation ng-animate ng-move"
    7. $animate blocks all CSS transitions on the element to ensure the .ng-move class styling is applied right away | class="my-animation ng-animate ng-move”
    8. $animate waits for a single animation frame (this performs a reflow) | class="my-animation ng-animate ng-move"
    9. $animate removes the CSS transition block placed on the element | class="my-animation ng-animate ng-move”
    10. the .ng-move-active class is added (this triggers the CSS transition/animation) | class="my-animation ng-animate ng-move ng-move-active"
    11. $animate waits for the animation to complete (via events and timeout) | class="my-animation ng-animate ng-move ng-move-active"
    12. The animation ends and all generated CSS classes are removed from the element | class="my-animation"
    13. The doneCallback() callback is fired (if provided) | class="my-animation"

    参数

    参数 类型 详述
    element DOMElement

    the element that will be the focus of the move animation
    parentElement DOMElement

    the parentElement element of the element that will be the focus of the move animation
    afterElement DOMElement

    the sibling element (which is the previous element) of the element that will be the focus of the move animation
    doneCallback
    (可选)
             function()=

    the callback function that will be called once the animation is complete

    返回值

    Function

    the animation cancellation function

  • addClass(element, className, [doneCallback]);

    Triggers a custom animation event based off the className variable and then attaches the className value to the element as a CSS class. Unlike the other animation methods, the animate service will suffix the className value with -add in order to provide the animate service the setup and active CSS classes in order to trigger the animation (this will be skipped if no CSS transitions or keyframes are defined on the -add-active or base CSS class).

    Below is a breakdown of each step that occurs during addClass animation:

    动画步骤 | 元素的class属性看上去像
    1. $animate.addClass(element, 'super') is called | class="my-animation"
    2. $animate runs the JavaScript-defined animations detected on the element | class="my-animation ng-animate"
    3. the .super-add class is added to the element | class="my-animation ng-animate super-add"
    4. $animate waits for a single animation frame (this performs a reflow) | class="my-animation ng-animate super-add"
    5. the .super and .super-add-active classes are added (this triggers the CSS transition/animation) | class="my-animation ng-animate super super-add super-add-active"
    6. $animate scans the element styles to get the CSS transition/animation duration and delay | class="my-animation ng-animate super-add"
    7. $animate waits for the animation to complete (via events and timeout) | class="my-animation super super-add super-add-active"
    8. The animation ends and all generated CSS classes are removed from the element | class="my-animation super"
    9. The super class is kept on the element | class="my-animation super"
    10. The doneCallback() callback is fired (if provided) | class="my-animation super"

    参数

    参数 类型 详述
    element DOMElement

    the element that will be animated
    className string

    the CSS class that will be added to the element and then animated
    doneCallback
    (可选)
             function()=

    the callback function that will be called once the animation is complete

    返回值

    Function

    the animation cancellation function

  • removeClass(element, className, [doneCallback]);

    Triggers a custom animation event based off the className variable and then removes the CSS class provided by the className value from the element. Unlike the other animation methods, the animate service will suffix the className value with -remove in order to provide the animate service the setup and active CSS classes in order to trigger the animation (this will be skipped if no CSS transitions or keyframes are defined on the -remove or base CSS classes).

    Below is a breakdown of each step that occurs during removeClass animation:

    动画步骤 | 元素的class属性看上去像
    1. $animate.removeClass(element, 'super') is called | class="my-animation super"
    2. $animate runs the JavaScript-defined animations detected on the element | class="my-animation super ng-animate"
    3. the .super-remove class is added to the element | class="my-animation super ng-animate super-remove"
    4. $animate waits for a single animation frame (this performs a reflow) | class="my-animation super ng-animate super-remove"
    5. the .super-remove-active classes are added and .super is removed (this triggers the CSS transition/animation) | class="my-animation ng-animate super-remove super-remove-active"
    6. $animate scans the element styles to get the CSS transition/animation duration and delay | class="my-animation super ng-animate super-remove"
    7. $animate waits for the animation to complete (via events and timeout) | class="my-animation ng-animate super-remove super-remove-active"
    8. The animation ends and all generated CSS classes are removed from the element | class="my-animation"
    9. The doneCallback() callback is fired (if provided) | class="my-animation"

    参数

    参数 类型 详述
    element DOMElement

    the element that will be animated
    className string

    the CSS class that will be animated and then removed from the element
    doneCallback
    (可选)
             function()=

    the callback function that will be called once the animation is complete

    返回值

    Function

    the animation cancellation function

  • setClass(element, add, remove, [done]);

    Adds and/or removes the given CSS classes to and from the element. Once complete, the done() callback will be fired (if provided).

    动画步骤 | 元素的class属性看上去像
    1. $animate.removeClass(element, ‘on’, ‘off’) is called | class="my-animation super off”
    2. $animate runs the JavaScript-defined animations detected on the element | class="my-animation super ng-animate off”
    3. the .on-add and .off-remove classes are added to the element | class="my-animation ng-animate on-add off-remove off”
    4. $animate waits for a single animation frame (this performs a reflow) | class="my-animation ng-animate on-add off-remove off”
    5. the .on, .on-add-active and .off-remove-active classes are added and .off is removed (this triggers the CSS transition/animation) | class="my-animation ng-animate on on-add on-add-active off-remove off-remove-active”
    6. $animate scans the element styles to get the CSS transition/animation duration and delay | class="my-animation ng-animate on on-add on-add-active off-remove off-remove-active"
    7. $animate waits for the animation to complete (via events and timeout) | class="my-animation ng-animate on on-add on-add-active off-remove off-remove-active"
    8. The animation ends and all generated CSS classes are removed from the element | class="my-animation"
    9. The doneCallback() callback is fired (if provided) | class="my-animation"

    参数

    参数 类型 详述
    element DOMElement

    the element which will have its CSS classes changed removed from it
    add string

    the CSS classes which will be added to the element
    remove string

    the CSS class which will be removed from the element
    done
    (可选)
             function=

    the callback function (if provided) that will be fired after the CSS classes have been set on the element

    返回值

    Function

    the animation cancellation function

  • enabled([value], [element]);

    Globally enables/disables animations.

    参数

    参数 类型 详述
    value
    (可选)
             boolean

    If provided then set the animation on or off.
    element
    (可选)
             DOMElement

    If provided then the element will be used to represent the enable/disable operation

    返回值

    boolean

    Current animation state.


AngularJS: API: ngCookies

ngCookies

ngCookies

The ngCookies module provides a convenient wrapper for reading and writing browser cookies.

参见 $cookies and $cookieStore for usage.

Installation

First include angular-cookies.js in your HTML:

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

You can download this file from the following places:

  • Google CDN
    例如 //ajax.googleapis.com/ajax/libs/angularjs/X.Y.Z/angular-cookies.js
  • Bower
    例如
    bower install angular-cookies@X.Y.Z
  • code.angularjs.org
    例如
    "//code.angularjs.org/X.Y.Z/angular-cookies.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', ['ngCookies']);

With that you're ready to get started!

模块组件

Service

名称 | 描述
$cookies | Provides read/write access to browser's cookies.
$cookieStore | Provides a key-value (string-object) storage, that is backed by session cookies. Objects put or retrieved from this storage are automatically serialized or deserialized by angular's toJson/fromJson.


AngularJS: API: ngCookies/service

Service components in ngCookies

名称 | 描述
$cookies | Provides read/write access to browser's cookies.
$cookieStore | Provides a key-value (string-object) storage, that is backed by session cookies. Objects put or retrieved from this storage are automatically serialized or deserialized by angular's toJson/fromJson.


AngularJS: API: ngCookies/service/$cookies

$cookies

  1. - service in module ngCookies

Provides read/write access to browser's cookies.

Only a simple Object is exposed and by adding or removing properties to/from this object, new cookies are created/deleted at the end of current $eval. The object's properties can only be strings.

Requires the ngCookies module to be installed.

示例

angular.module('cookiesExample', ['ngCookies'])
  .controller('ExampleController', ['$cookies', Function($cookies) {
    // Retrieving a cookie
    var favoriteCookie = $cookies.myFavorite;
    // Setting a cookie
    $cookies.myFavorite = 'oatmeal';
  }]);


AngularJS: API: ngCookies/service/$cookieStore

$cookieStore

  1. - service in module ngCookies

Provides a key-value (string-object) storage, that is backed by session cookies. Objects put or retrieved from this storage are automatically serialized or deserialized by angular's toJson/fromJson.

Requires the ngCookies module to be installed.

依赖

  • $cookies

方法

  • get(key);

    Returns the value of given cookie key

    参数

    参数 类型 详述
    key string

    Id to use for lookup.

    返回值

    Object

    Deserialized cookie value.

  • put(key, value);

    Sets a value for given cookie key

    参数

    参数 类型 详述
    key string

    Id for the value.
    value Object

    Value to be stored.

  • remove(key);

    Remove given cookie

    参数

    参数 类型 详述
    key string

    Id of the key-value pair to delete.

示例

angular.module('cookieStoreExample', ['ngCookies'])
  .controller('ExampleController', ['$cookieStore', Function($cookieStore) {
    // Put cookie
    $cookieStore.put('myFavorite','oatmeal');
    // Get cookie
    var favoriteCookie = $cookieStore.get('myFavorite');
    // Removing a cookie
    $cookieStore.remove('myFavorite');
  }]);


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.


AngularJS: API: ngMessages/directive

Directive components in ngMessages

名称 | 描述
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.


AngularJS: API: ngMessages/directive/ngMessage

ngMessage

  1. - directive in module ngMessages

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.

指令信息

  • 这个指令会创建新的作用域(scope)。
  • 这个指令执行优先级为0.

用法

<!-- using attribute directives -->
<ANY ng-messages="expression">
  <ANY ng-message="keyValue1">...</ANY>
  <ANY ng-message="keyValue2">...</ANY>
  <ANY ng-message="keyValue3">...</ANY>
</ANY>

<!-- or by using element directives -->
<ng-messages for="expression">
  <ng-message when="keyValue1">...</ng-message>
  <ng-message when="keyValue2">...</ng-message>
  <ng-message when="keyValue3">...</ng-message>
</ng-messages>

点击这里 to learn more about ngMessages and ngMessage.

参数

参数 | 类型 | 详述
ngMessage | string | a string value corresponding to the message key.


AngularJS: API: ngMessages/directive/ngMessages

ngMessages

  1. - directive in module 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).

ngMessages manages the state of internal messages within its container element. The internal messages use the ngMessage directive and will be inserted/removed from the page depending on if they're present within the key/value object. 默认情况下， only one message will be displayed at a time and this depends on the prioritization of the messages within the template. (This can be changed by using the ng-messages-multiple on the directive container.)

A remote template can also be used to promote message reuseability and messages can also be overridden.

点击这里 to learn more about ngMessages and ngMessage.

指令信息

  • 这个指令执行优先级为0.

用法

<!-- using attribute directives --><ANY ng-messages="expression">
  <ANY ng-message="keyValue1">...</ANY>
  <ANY ng-message="keyValue2">...</ANY>
  <ANY ng-message="keyValue3">...</ANY></ANY>

<!-- or by using element directives --><ng-messages for="expression">
  <ng-message when="keyValue1">...</ng-message>
  <ng-message when="keyValue2">...</ng-message>
  <ng-message when="keyValue3">...</ng-message></ng-messages>

参数

参数 | 类型 | 详述
ngMessages | string | an Angular表达式 evaluating to a key/value object (this is typically the $error object on an ngModel instance).
ngMessagesMultiple | multiple (可选) | string | when set, all messages will be displayed with true
ngMessagesInclude | include (可选) | string | when set, the specified template will be included into the ng-messages container

示例

index.html
<form name="myForm">
  <label>Enter your name:</label>
  <input Type="text"
         name="myName"
         ng-model="name"
         ng-minlength="5"
         ng-maxlength="20"
         required />

  <pre>myForm.myName.$error = {{ myForm.myName.$error | json }}</pre>

  <div ng-messages="myForm.myName.$error" style="color:maroon">
    <div ng-message="required">You did not enter a field</div>
    <div ng-message="minlength">Your field is too short</div>
    <div ng-message="maxlength">Your field is too long</div>
  </div></form>
script.js
angular.module('ngMessagesExample', ['ngMessages']);


AngularJS: API: ngMock

ngMock

ngMock

The ngMock module provides support to inject and mock Angular services into unit tests. 此外， ngMock also extends various core ng services such that they can be inspected and controlled in a synchronous manner within test code.

Installation

First include angular-mock.js in your HTML:

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

You can download this file from the following places:

  • Google CDN
    例如 //ajax.googleapis.com/ajax/libs/angularjs/X.Y.Z/angular-mock.js
  • Bower
    例如
    bower install angular-mock@X.Y.Z
  • code.angularjs.org
    例如
    "//code.angularjs.org/X.Y.Z/angular-mock.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', ['ngMock']);

With that you're ready to get started!

模块组件

Object

名称 | 描述
angular.mock | Namespace from 'angular-mocks.js' which contains testing related code.

Provider

名称 | 描述
$exceptionHandlerProvider | Configures the mock implementation of $exceptionHandler to rethrow or to log errors passed into the $exceptionHandler.

Service

名称 | 描述
$exceptionHandler | Mock implementation of $exceptionHandler that rethrows or logs errors passed into it. See $exceptionHandlerProvider for configuration information.
$log | Mock implementation of $log that gathers all logged messages in arrays (one array per logging level). These arrays are exposed as logs property of each of the level-specific log function,例如 for level error the array is exposed as $log.error.logs.
$interval | Mock implementation of the $interval service.
$httpBackend | Fake HTTP backend implementation suitable for unit testing applications that use the $http service.
$timeout | This service is just a simple decorator for $timeout service that adds a "flush" and "verifyNoPendingTasks" methods.

Type

名称 | 描述
angular.mock.TzDate | 注意: this is not an injectable instance, just a globally available mock class of Date.

Function

名称 | 描述
angular.mock.dump | 注意: this is not an injectable instance, just a globally available function.
angular.mock.module | 注意: This function is also published on window for easy access.
angular.mock.inject | 注意: This function is also published on window for easy access.


AngularJS: API: ngMock/function

Function components in ngMock

名称 | 描述
angular.mock.dump | 注意: this is not an injectable instance, just a globally available function.
angular.mock.module | 注意: This function is also published on window for easy access.
angular.mock.inject | 注意: This function is also published on window for easy access.


AngularJS: API: ngMock/function/angular.mock.dump

angular.mock.dump

  1. - function in module ngMock

注意: this is not an injectable instance, just a globally available function.

Method for serializing common angular objects (scope, elements, etc..) into strings, useful for debugging.

This method is also available on window, where it can be used to display objects on debug console.

用法

angular.mock.dump(Object);

参数

参数 | 类型 | 详述
object | * | any object to turn into string.

返回值

string

a serialized string of the argument


AngularJS: API: ngMock/function/angular.mock.inject

angular.mock.inject

  1. - function in module ngMock

注意: This function is also published on window for easy access.

The inject function wraps a function into an injectable function. The inject() creates new instance of $injector per test, which is then used for resolving references.

Resolving References (Underscore Wrapping)

Often, we would like to inject a reference once, in a beforeEach() block and reuse this in multiple it() clauses. To be able to do this we must assign the reference to a variable that is declared in the scope of the describe() block. Since we would, most likely, want the variable to have the same name of the reference we have a problem, since the parameter to the inject() function would hide the outer variable.

To help with this, the injected parameters can, optionally, be enclosed with underscores. These are ignored by the injector when the reference name is resolved.

例如，the parameter _myService_ would be resolved as the reference myService. Since it is available in the function body as myService, we can then assign it to a variable defined in an outer scope.

// Defined out reference variable outside
var myService;

// Wrap the parameter in underscores
beforeEach( inject( Function(_myService_){
  myService = _myService_;
}));

// Use myService in a series of tests.
it('makes use of myService', Function() {
  myService.doStuff();
});

参见 angular.mock.module

示例

Example of what a typical jasmine tests looks like with the inject method.

  angular.module('myApplicationModule', [])
      .value('mode', 'app')
      .value('version', 'v1.0.1');

  describe('MyApp', Function() {

    // You need to load modules that you want to test,
    // it loads only the "ng" module by default.
    beforeEach(module('myApplicationModule'));

    // inject() is used to inject arguments of all given functions
    it('should provide a version', inject(Function(mode, version) {
      expect(version).toEqual('v1.0.1');
      expect(mode).toEqual('app');
    }));

    // The inject and module method can also be used inside of the it or beforeEach
    it('should override a version and test the new version is injected', Function() {
      // module() takes functions or strings (module aliases)
      module(Function($provide) {
        $provide.value('version', 'overridden'); // override version here
      });

      inject(Function(version) {
        expect(version).toEqual('overridden');
      });
    });
  });

用法

angular.mock.inject(fns);

参数

参数 | 类型 | 详述
fns | ...Function | any number of functions which will be injected using the injector.


AngularJS: API: ngMock/function/angular.mock.module

angular.mock.module

  1. - function in module ngMock

注意: This function is also published on window for easy access.

This function registers a module configuration code. It collects the configuration information which will be used when the injector is created by inject.

参见 inject for usage example

用法

angular.mock.module(fns);

参数

参数 | 类型 | 详述
fns | string function() Object | any number of modules which are represented as string aliases or as anonymous module initialization functions. The modules are used to configure the injector. The 'ng' and 'ngMock' modules are automatically loaded. If an object literal is passed they will be registered as values in the module, the key being the module name and the value being what is returned.


AngularJS: API: ngMock/object

Object components in ngMock

名称 | 描述
angular.mock | Namespace from 'angular-mocks.js' which contains testing related code.


AngularJS: API: ngMock/object/angular.mock

angular.mock

  1. - object in module ngMock

Namespace from 'angular-mocks.js' which contains testing related code.


AngularJS: API: ngMock/provider

Provider components in ngMock

名称 | 描述
$exceptionHandlerProvider | Configures the mock implementation of $exceptionHandler to rethrow or to log errors passed into the $exceptionHandler.


AngularJS: API: ngMock/provider/$exceptionHandlerProvider

$exceptionHandlerProvider

  1. - $exceptionHandler
  2. - provider in module ngMock

Configures the mock implementation of $exceptionHandler to rethrow or to log errors passed into the $exceptionHandler.

方法

  • mode(mode);

    Sets the logging mode.

    参数

    参数 类型 详述
    mode string

    Mode of operation, defaults to rethrow.

    • rethrow: If any errors are passed into the handler in tests, it typically
             means that there is a bug in the application or test, so this mock will
       make these tests fail.
    • log: Sometimes it is desirable to test that an error is thrown, for this case the log
         mode stores an array of errors in `$exceptionHandler.errors`, to allow later
   assertion of them. 参见  assertEmpty() and
   reset()


AngularJS: API: ngMock/service

Service components in ngMock

名称 | 描述
$exceptionHandler | Mock implementation of $exceptionHandler that rethrows or logs errors passed into it. See $exceptionHandlerProvider for configuration information.
$log | Mock implementation of $log that gathers all logged messages in arrays (one array per logging level). These arrays are exposed as logs property of each of the level-specific log function,例如 for level error the array is exposed as $log.error.logs.
$interval | Mock implementation of the $interval service.
$httpBackend | Fake HTTP backend implementation suitable for unit testing applications that use the $http service.
$timeout | This service is just a simple decorator for $timeout service that adds a "flush" and "verifyNoPendingTasks" methods.


AngularJS: API: ngMock/service/$exceptionHandler

$exceptionHandler

  1. - $exceptionHandlerProvider
  2. - service in module ngMock

Mock implementation of $exceptionHandler that rethrows or logs errors passed into it. See $exceptionHandlerProvider for configuration information.

  describe('$exceptionHandlerProvider', Function() {

    it('should capture log messages and exceptions', Function() {

      module(Function($exceptionHandlerProvider) {
        $exceptionHandlerProvider.mode('log');
      });

      inject(Function($log, $exceptionHandler, $timeout) {
        $timeout(Function() { $log.log(1); });
        $timeout(Function() { $log.log(2); throw 'banana peel'; });
        $timeout(Function() { $log.log(3); });
        expect($exceptionHandler.errors).toEqual([]);
        expect($log.assertEmpty());
        $timeout.flush();
        expect($exceptionHandler.errors).toEqual(['banana peel']);
        expect($log.log.logs).toEqual([[1], [2], [3]]);
      });
    });
  });


AngularJS: API: ngMock/service/$httpBackend

$httpBackend

  1. - service in module ngMock

Fake HTTP backend implementation suitable for unit testing applications that use the $http service.

注意: For fake HTTP backend implementation suitable for end-to-end testing or backend-less development please see e2e $httpBackend mock.

During unit testing, we want our unit tests to run quickly and have no external dependencies so we don’t want to send XHR or JSONP requests to a real server. All we really need is to verify whether a certain request has been sent or not, or alternatively just let the application make requests, respond with pre-trained responses and assert that the end result is what we expect it to be.

This mock implementation can be used to respond with static or dynamic responses via the expect and when apis and their shortcuts (expectGET, whenPOST, etc).

When an Angular application needs some data from a server, it calls the $http service, which sends the request to a real server using $httpBackend service. With 依赖注入, it is easy to inject $httpBackend mock (which has the same API as $httpBackend) and use it to verify the requests and respond with some testing data without sending a request to a real server.

There are two ways to specify what test data should be returned as http responses by the mock backend when the code under test makes http requests:

  • $httpBackend.expect - specifies a request expectation
  • $httpBackend.when - specifies a backend definition

Request Expectations vs Backend Definitions

Request expectations provide a way to make assertions about requests made by the application and to define responses for those requests. The test will fail if the expected requests are not made or they are made in the wrong order.

Backend definitions allow you to define a fake backend for your application which doesn't assert if a particular request was made or not, it just returns a trained response if a request is made. The test will pass whether or not the request gets made during testing.

 | Request expectations | Backend definitions
Syntax | .expect(...).respond(...) | .when(...).respond(...)
Typical usage | strict unit tests | loose (black-box) unit testing
Fulfills multiple requests | NO | YES
Order of requests matters | YES | NO
Request required | YES | NO
Response required | optional (see below) | YES

In cases where both backend definitions and request expectations are specified during unit testing, the request expectations are evaluated first.

If a request expectation has no response specified, the algorithm will search your backend definitions for an appropriate response.

If a request didn't match any expectation or if the expectation doesn't have the response defined, the backend definitions are evaluated in sequential order to see if any of them match the request. The response from the first matched definition is returned.

Flushing HTTP requests

The $httpBackend used in production always responds to requests asynchronously. If we preserved this behavior in unit testing, we'd have to create async unit tests, which are hard to write, to follow and to maintain. But neither can the testing mock respond synchronously; that would change the execution of the code under test. For this reason, the mock $httpBackend has a flush() method, which allows the test to explicitly flush pending requests. This preserves the async api of the backend, while allowing the test to execute synchronously.

Unit testing with mock $httpBackend

The following code shows how to setup and use the mock backend when unit testing a controller. First we create the controller under test:

  // The controller code
  Function MyController($scope, $http) {
    var authToken;

    $http.get('/auth.py').success(Function(data, status, headers) {
      authToken = headers('A-Token');
      $scope.user = data;
    });

    $scope.saveMessage = Function(message) {
      var headers = { 'Authorization': authToken };
      $scope.status = 'Saving...';

      $http.post('/add-msg.py', message, { headers: headers } ).success(Function(response) {
        $scope.status = '';
      }).error(Function() {
        $scope.status = 'ERROR!';
      });
    };
  }

Now we setup the mock backend and create the test specs:

    // testing controller
    describe('MyController', Function() {
       var $httpBackend, $rootScope, createController;

       beforeEach(inject(Function($injector) {
         // Set up the mock http service responses
         $httpBackend = $injector.get('$httpBackend');
         // backend definition common for all tests
         $httpBackend.when('GET', '/auth.py').respond({userId: 'userX'}, {'A-Token': 'xxx'});

         // Get hold of a scope (i.e. the root scope)
         $rootScope = $injector.get('$rootScope');
         // The $controller service is used to create instances of controllers
         var $controller = $injector.get('$controller');

         createController = Function() {
           return $controller('MyController', {'$scope' : $rootScope });
         };
       }));

       afterEach(Function() {
         $httpBackend.verifyNoOutstandingExpectation();
         $httpBackend.verifyNoOutstandingRequest();
       });

       it('should fetch authentication token', Function() {
         $httpBackend.expectGET('/auth.py');
         var controller = createController();
         $httpBackend.flush();
       });

       it('should send msg to server', Function() {
         var controller = createController();
         $httpBackend.flush();

         // now you don’t care about the authentication, but
         // the controller will still send the request and
         // $httpBackend will respond without you having to
         // specify the expectation and response for this request

         $httpBackend.expectPOST('/add-msg.py', 'message content').respond(201, '');
         $rootScope.saveMessage('message content');
         expect($rootScope.status).toBe('Saving...');
         $httpBackend.flush();
         expect($rootScope.status).toBe('');
       });

       it('should send auth header', Function() {
         var controller = createController();
         $httpBackend.flush();

         $httpBackend.expectPOST('/add-msg.py', undefined, Function(headers) {
           // check if the header was send, if it wasn't the expectation won't
           // match the request and the test will fail
           return headers['Authorization'] == 'xxx';
         }).respond(201, '');

         $rootScope.saveMessage('whatever');
         $httpBackend.flush();
       });
    });

方法

  • when(method, url, [data], [headers]);

    Creates a new backend definition.

    参数

    参数 类型 详述
    method string

    HTTP method.
    url string RegExp function(string)

    HTTP url or function that receives the url and returns true if the url match the current definition.
    data
    (可选)
             string RegExp function(string)

    HTTP request body or function that receives data string and returns true if the data is as expected.
    headers
    (可选)
             Object function(Object)

    HTTP headers or function that receives http header object and returns true if the headers match the current definition.

    返回值

    requestHandler

    Returns an object with respond method that controls how a matched request is handled.

    • respond – {Function([status,] data[, headers, statusText]) | Function(Function(method, url, data, headers)} – The respond method takes a set of static data to be returned or a function that can return an array containing response status (number), response data (string), response headers (Object), and the text for the status (string).

  • whenGET(url, [headers]);

    Creates a new backend definition for GET requests. For more info see when().

    参数

    参数 类型 详述
    url string RegExp function(string)

    HTTP url or function that receives the url and returns true if the url match the current definition.
    headers
    (可选)
             Object function(Object)

    HTTP headers.

    返回值

    requestHandler

    Returns an object with respond method that control how a matched request is handled.

  • whenHEAD(url, [headers]);

    Creates a new backend definition for HEAD requests. For more info see when().

    参数

    参数 类型 详述
    url string RegExp function(string)

    HTTP url or function that receives the url and returns true if the url match the current definition.
    headers
    (可选)
             Object function(Object)

    HTTP headers.

    返回值

    requestHandler

    Returns an object with respond method that control how a matched request is handled.

  • whenDELETE(url, [headers]);

    Creates a new backend definition for DELETE requests. For more info see when().

    参数

    参数 类型 详述
    url string RegExp function(string)

    HTTP url or function that receives the url and returns true if the url match the current definition.
    headers
    (可选)
             Object function(Object)

    HTTP headers.

    返回值

    requestHandler

    Returns an object with respond method that control how a matched request is handled.

  • whenPOST(url, [data], [headers]);

    Creates a new backend definition for POST requests. For more info see when().

    参数

    参数 类型 详述
    url string RegExp function(string)

    HTTP url or function that receives the url and returns true if the url match the current definition.
    data
    (可选)
             string RegExp function(string)

    HTTP request body or function that receives data string and returns true if the data is as expected.
    headers
    (可选)
             Object function(Object)

    HTTP headers.

    返回值

    requestHandler

    Returns an object with respond method that control how a matched request is handled.

  • whenPUT(url, [data], [headers]);

    Creates a new backend definition for PUT requests. For more info see when().

    参数

    参数 类型 详述
    url string RegExp function(string)

    HTTP url or function that receives the url and returns true if the url match the current definition.
    data
    (可选)
             string RegExp function(string)

    HTTP request body or function that receives data string and returns true if the data is as expected.
    headers
    (可选)
             Object function(Object)

    HTTP headers.

    返回值

    requestHandler

    Returns an object with respond method that control how a matched request is handled.

  • whenJSONP(url);

    Creates a new backend definition for JSONP requests. For more info see when().

    参数

    参数 类型 详述
    url string RegExp function(string)

    HTTP url or function that receives the url and returns true if the url match the current definition.

    返回值

    requestHandler

    Returns an object with respond method that control how a matched request is handled.

  • expect(method, url, [data], [headers]);

    Creates a new request expectation.

    参数

    参数 类型 详述
    method string

    HTTP method.
    url string RegExp function(string)

    HTTP url or function that receives the url and returns true if the url match the current definition.
    data
    (可选)
             string RegExp function(string) Object

    HTTP request body or function that receives data string and returns true if the data is as expected, or Object if request body is in JSON format.
    headers
    (可选)
             Object function(Object)

    HTTP headers or function that receives http header object and returns true if the headers match the current expectation.

    返回值

    requestHandler

    Returns an object with respond method that control how a matched request is handled.

    • respond – {Function([status,] data[, headers, statusText]) | Function(Function(method, url, data, headers)} – The respond method takes a set of static data to be returned or a function that can return an array containing response status (number), response data (string), response headers (Object), and the text for the status (string).

  • expectGET(url, [headers]);

    Creates a new request expectation for GET requests. For more info see expect().

    参数

    参数 类型 详述
    url string RegExp function(string)

    HTTP url or function that receives the url and returns true if the url match the current definition.
    headers
    (可选)
             Object

    HTTP headers.

    返回值

    requestHandler

    Returns an object with respond method that control how a matched request is handled. See #expect for more info.

  • expectHEAD(url, [headers]);

    Creates a new request expectation for HEAD requests. For more info see expect().

    参数

    参数 类型 详述
    url string RegExp function(string)

    HTTP url or function that receives the url and returns true if the url match the current definition.
    headers
    (可选)
             Object

    HTTP headers.

    返回值

    requestHandler

    Returns an object with respond method that control how a matched request is handled.

  • expectDELETE(url, [headers]);

    Creates a new request expectation for DELETE requests. For more info see expect().

    参数

    参数 类型 详述
    url string RegExp function(string)

    HTTP url or function that receives the url and returns true if the url match the current definition.
    headers
    (可选)
             Object

    HTTP headers.

    返回值

    requestHandler

    Returns an object with respond method that control how a matched request is handled.

  • expectPOST(url, [data], [headers]);

    Creates a new request expectation for POST requests. For more info see expect().

    参数

    参数 类型 详述
    url string RegExp function(string)

    HTTP url or function that receives the url and returns true if the url match the current definition.
    data
    (可选)
             string RegExp function(string) Object

    HTTP request body or function that receives data string and returns true if the data is as expected, or Object if request body is in JSON format.
    headers
    (可选)
             Object

    HTTP headers.

    返回值

    requestHandler

    Returns an object with respond method that control how a matched request is handled.

  • expectPUT(url, [data], [headers]);

    Creates a new request expectation for PUT requests. For more info see expect().

    参数

    参数 类型 详述
    url string RegExp function(string)

    HTTP url or function that receives the url and returns true if the url match the current definition.
    data
    (可选)
             string RegExp function(string) Object

    HTTP request body or function that receives data string and returns true if the data is as expected, or Object if request body is in JSON format.
    headers
    (可选)
             Object

    HTTP headers.

    返回值

    requestHandler

    Returns an object with respond method that control how a matched request is handled.

  • expectPATCH(url, [data], [headers]);

    Creates a new request expectation for PATCH requests. For more info see expect().

    参数

    参数 类型 详述
    url string RegExp function(string)

    HTTP url or function that receives the url and returns true if the url match the current definition.
    data
    (可选)
             string RegExp function(string) Object

    HTTP request body or function that receives data string and returns true if the data is as expected, or Object if request body is in JSON format.
    headers
    (可选)
             Object

    HTTP headers.

    返回值

    requestHandler

    Returns an object with respond method that control how a matched request is handled.

  • expectJSONP(url);

    Creates a new request expectation for JSONP requests. For more info see expect().

    参数

    参数 类型 详述
    url string RegExp function(string)

    HTTP url or function that receives the url and returns true if the url match the current definition.

    返回值

    requestHandler

    Returns an object with respond method that control how a matched request is handled.

  • flush([count]);

    Flushes all pending requests using the trained responses.

    参数

    参数 类型 详述
    count
    (可选)
             number

    Number of responses to flush (in the order they arrived). If undefined, all pending requests will be flushed. If there are no pending requests when the flush method is called an exception is thrown (as this typically a sign of programming error).

  • verifyNoOutstandingExpectation();

    Verifies that all of the requests defined via the expect api were made. If any of the requests were not made, verifyNoOutstandingExpectation throws an exception.

    Typically, you would call this method following each test case that asserts requests using an "afterEach" clause.

      afterEach($httpBackend.verifyNoOutstandingExpectation);

  • verifyNoOutstandingRequest();

    Verifies that there are no outstanding requests that need to be flushed.

    Typically, you would call this method following each test case that asserts requests using an "afterEach" clause.

      afterEach($httpBackend.verifyNoOutstandingRequest);

  • resetExpectations();

    Resets all request expectations, but preserves all backend definitions. Typically, you would call resetExpectations during a multiple-phase test when you want to reuse the same instance of $httpBackend mock.


AngularJS: API: ngMock/service/$interval

$interval

  1. - service in module ngMock

Mock implementation of the $interval service.

Use $interval.flush(millis) to move forward by millis milliseconds and trigger any functions scheduled to run in that time.

用法

$interval(fn, delay, [count], [invokeApply]);

参数

参数 | 类型 | 详述
fn | function() | A function that should be called repeatedly.
delay | number | Number of milliseconds between each function call.
count (可选) | number | Number of times to repeat. If not set, or 0, will repeat indefinitely.
invokeApply (可选) | boolean | If set to false skips model dirty checking, otherwise will invoke fn within the $apply block.

返回值

promise

A promise which will be notified on each iteration.

方法

  • cancel(promise);

    Cancels a task associated with the promise.

    参数

    参数 类型 详述
    promise promise

    A promise from calling the $interval function.

    返回值

    boolean

    返回值true if the task was successfully cancelled.

  • flush([millis]);

    Runs interval tasks scheduled to be run in the next millis milliseconds.

    参数

    参数 类型 详述
    millis
    (可选)
             number

    maximum timeout amount to flush up until.

    返回值

    number

    The amount of time moved forward.


AngularJS: API: ngMock/service/$log

$log

  1. - service in module ngMock

Mock implementation of $log that gathers all logged messages in arrays (one array per logging level). These arrays are exposed as logs property of each of the level-specific log function,例如 for level error the array is exposed as $log.error.logs.

方法

  • reset();

    Reset all of the logging arrays to empty.

  • assertEmpty();

    Assert that the all of the logging methods have no logged messages. If messages present, an exception is thrown.

属性

  • log.logs

    Array of messages logged using $log.

  • info.logs

    Array of messages logged using $log.

  • warn.logs

    Array of messages logged using $log.

  • error.logs

    Array of messages logged using $log.

  • debug.logs

    Array of messages logged using $log.


AngularJS: API: ngMock/service/$timeout

$timeout

  1. - service in module ngMock

This service is just a simple decorator for $timeout service that adds a "flush" and "verifyNoPendingTasks" methods.

方法

  • flush([delay]);

    Flushes the queue of pending tasks.

    参数

    参数 类型 详述
    delay
    (可选)
             number

    maximum timeout amount to flush up until

  • verifyNoPendingTasks();

    Verifies that there are no pending tasks that need to be flushed.


AngularJS: API: ngMock/type

Type components in ngMock

名称 | 描述
angular.mock.TzDate | 注意: this is not an injectable instance, just a globally available mock class of Date.


AngularJS: API: ngMock/type/angular.mock.TzDate

angular.mock.TzDate

  1. - type in module ngMock

注意: this is not an injectable instance, just a globally available mock class of Date.

Mock of the Date type which has its timezone specified via constructor arg.

The main purpose is to create Date-like instances with timezone fixed to the specified timezone offset, so that we can test code that depends on local timezone settings without dependency on the time zone settings of the machine where the code is running.

用法

angular.mock.TzDate(offset, timestamp);

参数

参数 | 类型 | 详述
offset | number | Offset of the desired timezone in hours (fractions will be honored)
timestamp | number string | Timestamp representing the desired time in UTC

示例

!!!! 警告 !!!!! This is not a complete Date object so only methods that were implemented can be called safely. To make matters worse, TzDate instances inherit stuff from Date via a prototype.

We do our best to intercept calls to "unimplemented" methods, but since the list of methods is incomplete we might be missing some non-standard methods. This can result in errors like: "Date.prototype.foo called on incompatible Object".

var newYearInBratislava = new TzDate(-1, '2009-12-31T23:00:00Z');
newYearInBratislava.getTimezoneOffset() => -60;
newYearInBratislava.getFullYear() => 2010;
newYearInBratislava.getMonth() => 0;
newYearInBratislava.getDate() => 1;
newYearInBratislava.getHours() => 0;
newYearInBratislava.getMinutes() => 0;
newYearInBratislava.getSeconds() => 0;


AngularJS: API: ngMockE2E

ngMockE2E

The ngMockE2E is an angular module which contains mocks suitable for end-to-end testing. Currently there is only one mock present in this module - the e2e $httpBackend mock.

Installation

First include angular-mocke2e.js in your HTML:

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

You can download this file from the following places:

  • Google CDN
    例如 //ajax.googleapis.com/ajax/libs/angularjs/X.Y.Z/angular-mocke2e.js
  • Bower
    例如
    bower install angular-mocke2e@X.Y.Z
  • code.angularjs.org
    例如
    "//code.angularjs.org/X.Y.Z/angular-mocke2e.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', ['ngMockE2E']);

With that you're ready to get started!

模块组件

Service

名称 | 描述
$httpBackend | Fake HTTP backend implementation suitable for end-to-end testing or backend-less development of applications that use the $http service.


AngularJS: API: ngMockE2E/service

Service components in ngMockE2E

名称 | 描述
$httpBackend | Fake HTTP backend implementation suitable for end-to-end testing or backend-less development of applications that use the $http service.


AngularJS: API: ngMockE2E/service/$httpBackend

$httpBackend

  1. - service in module ngMockE2E

Fake HTTP backend implementation suitable for end-to-end testing or backend-less development of applications that use the $http service.

注意: For fake http backend implementation suitable for unit testing please see unit-testing $httpBackend mock.

This implementation can be used to respond with static or dynamic responses via the when api and its shortcuts (whenGET, whenPOST, etc) and optionally pass through requests to the real $httpBackend for specific requests (如： to interact with certain remote apis or to fetch templates from a webserver).

As opposed to unit-testing, in an end-to-end testing scenario or in scenario when an application is being developed with the real backend api replaced with a mock, it is often desirable for certain category of requests to bypass the mock and issue a real http request (如： to fetch templates or static files from the webserver). To configure the backend with this behavior use the passThrough request handler of when instead of respond.

此外， we don't want to manually have to flush mocked out requests like we do during unit testing. For this reason the e2e $httpBackend automatically flushes mocked out requests automatically, closely simulating the behavior of the XMLHttpRequest object.

To setup the application to run with this http backend, you have to create a module that depends on the ngMockE2E and your application modules and defines the fake backend:

  myAppDev = angular.module('myAppDev', ['myApp', 'ngMockE2E']);
  myAppDev.run(Function($httpBackend) {
    phones = [{name: 'phone1'}, {name: 'phone2'}];

    // returns the current list of phones
    $httpBackend.whenGET('/phones').respond(phones);

    // adds a new phone to the phones array
    $httpBackend.whenPOST('/phones').respond(Function(method, url, data) {
      var phone = angular.fromJson(data);
      phones.push(phone);
      return [200, phone, {}];
    });
    $httpBackend.whenGET(/^\/templates\//).passThrough();
    //...
  });

Afterwards, bootstrap your app with this new module.

方法

  • when(method, url, [data], [headers]);

    Creates a new backend definition.

    参数

    参数 类型 详述
    method string

    HTTP method.
    url string RegExp function(string)

    HTTP url or function that receives the url and returns true if the url match the current definition.
    data
    (可选)
             string RegExp

    HTTP request body.
    headers
    (可选)
             Object function(Object)

    HTTP headers or function that receives http header object and returns true if the headers match the current definition.

    返回值

    requestHandler

    Returns an object with respond and passThrough methods that control how a matched request is handled.

    • respond – {Function([status,] data[, headers, statusText]) | Function(Function(method, url, data, headers)} – The respond method takes a set of static data to be returned or a function that can return an array containing response status (number), response data (string), response headers (Object), and the text for the status (string).
    • passThrough – {Function()} – Any request matching a backend definition with passThrough handler will be passed through to the real backend (an XHR request will be made to the server.)

  • whenGET(url, [headers]);

    Creates a new backend definition for GET requests. For more info see when().

    参数

    参数 类型 详述
    url string RegExp function(string)

    HTTP url or function that receives the url and returns true if the url match the current definition.
    headers
    (可选)
             Object function(Object)

    HTTP headers.

    返回值

    requestHandler

    Returns an object with respond and passThrough methods that control how a matched request is handled.

  • whenHEAD(url, [headers]);

    Creates a new backend definition for HEAD requests. For more info see when().

    参数

    参数 类型 详述
    url string RegExp function(string)

    HTTP url or function that receives the url and returns true if the url match the current definition.
    headers
    (可选)
             Object function(Object)

    HTTP headers.

    返回值

    requestHandler

    Returns an object with respond and passThrough methods that control how a matched request is handled.

  • whenDELETE(url, [headers]);

    Creates a new backend definition for DELETE requests. For more info see when().

    参数

    参数 类型 详述
    url string RegExp function(string)

    HTTP url or function that receives the url and returns true if the url match the current definition.
    headers
    (可选)
             Object function(Object)

    HTTP headers.

    返回值

    requestHandler

    Returns an object with respond and passThrough methods that control how a matched request is handled.

  • whenPOST(url, [data], [headers]);

    Creates a new backend definition for POST requests. For more info see when().

    参数

    参数 类型 详述
    url string RegExp function(string)

    HTTP url or function that receives the url and returns true if the url match the current definition.
    data
    (可选)
             string RegExp

    HTTP request body.
    headers
    (可选)
             Object function(Object)

    HTTP headers.

    返回值

    requestHandler

    Returns an object with respond and passThrough methods that control how a matched request is handled.

  • whenPUT(url, [data], [headers]);

    Creates a new backend definition for PUT requests. For more info see when().

    参数

    参数 类型 详述
    url string RegExp function(string)

    HTTP url or function that receives the url and returns true if the url match the current definition.
    data
    (可选)
             string RegExp

    HTTP request body.
    headers
    (可选)
             Object function(Object)

    HTTP headers.

    返回值

    requestHandler

    Returns an object with respond and passThrough methods that control how a matched request is handled.

  • whenPATCH(url, [data], [headers]);

    Creates a new backend definition for PATCH requests. For more info see when().

    参数

    参数 类型 详述
    url string RegExp function(string)

    HTTP url or function that receives the url and returns true if the url match the current definition.
    data
    (可选)
             string RegExp

    HTTP request body.
    headers
    (可选)
             Object function(Object)

    HTTP headers.

    返回值

    requestHandler

    Returns an object with respond and passThrough methods that control how a matched request is handled.

  • whenJSONP(url);

    Creates a new backend definition for JSONP requests. For more info see when().

    参数

    参数 类型 详述
    url string RegExp function(string)

    HTTP url or function that receives the url and returns true if the url match the current definition.

    返回值

    requestHandler

    Returns an object with respond and passThrough methods that control how a matched request is handled.


AngularJS: API: ngResource

ngResource

ngResource

The ngResource module provides interaction support with RESTful services via the $resource service.

参见 $resource for usage.

Installation

First include angular-resource.js in your HTML:

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

You can download this file from the following places:

  • Google CDN
    例如 //ajax.googleapis.com/ajax/libs/angularjs/X.Y.Z/angular-resource.js
  • Bower
    例如
    bower install angular-resource@X.Y.Z
  • code.angularjs.org
    例如
    "//code.angularjs.org/X.Y.Z/angular-resource.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', ['ngResource']);

With that you're ready to get started!

模块组件

Service

名称 | 描述
$resource | A factory which creates a resource object that lets you interact with RESTful server-side data sources.


AngularJS: API: ngResource/service

Service components in ngResource

名称 | 描述
$resource | A factory which creates a resource object that lets you interact with RESTful server-side data sources.


AngularJS: API: ngResource/service/$resource

$resource

  1. - service in module ngResource

A factory which creates a resource object that lets you interact with RESTful server-side data sources.

The returned resource object has action methods which provide high-level behaviors without the need to interact with the low level $http service.

Requires the ngResource module to be installed.

默认情况下， trailing slashes will be stripped from the calculated URLs, which can pose problems with server backends that do not expect that behavior. This can be disabled by configuring the $resourceProvider like this:

     app.config(['$resourceProvider', Function ($resourceProvider) {
       // Don't strip trailing slashes from calculated URLs
       $resourceProvider.defaults.stripTrailingSlashes = false;
     }]);

依赖

  • $http

用法

$resource(url, [paramDefaults], [actions], options);

参数

参数 类型 详述
url string

A parametrized URL template with parameters prefixed by : as in /user/:username. If you are using a URL with a port number (如： http://example.com:8080/api), it will be respected.

If you are using a url with a suffix, just add the suffix, like this: $resource('http://example.com/resource.json') or $resource('http://example.com/:id.json') or even $resource('http://example.com/resource/:resource_id.:format') If the parameter before the suffix is empty, :resource_id in this case, then the /. will be collapsed down to a single .. If you need this sequence to appear and not collapse then you can escape it with /\..
paramDefaults
(可选)
 Object

Default values for url parameters. These can be overridden in actions methods. If any of the parameter value is a function, it will be executed every time when a param value needs to be obtained for a request (unless the param was overridden).

Each key value in the parameter object is first bound to url template if present and then any excess keys are appended to the url search query after the ?.

Given a template /path/:verb and parameter {verb:'greet', salutation:'Hello'} results in URL /path/greet?salutation=Hello.

If the parameter value is prefixed with @ then the value of that parameter will be taken from the corresponding key on the data object (useful for non-GET operations).
actions
(可选)
 Object.<Object>=

Hash with declaration of custom action that should extend the default set of resource actions. The declaration should be created in the format of $http.config:

  {action1: {method:?, params:?, isArray:?, headers:?, ...},
   action2: {method:?, params:?, isArray:?, headers:?, ...},
   ...}

Where:

  • action – {string} – The name of action. This name becomes the name of the method on your resource object.
  • method – {string} – HTTP request method. Valid methods are: GET, POST, PUT, DELETE, and JSONP.
  • params – {Object=} – Optional set of pre-bound parameters for this action. If any of the parameter value is a function, it will be executed every time when a param value needs to be obtained for a request (unless the param was overridden).
  • url – {string} – action specific url override. The url templating is supported just like for the resource-level urls.
  • isArray – {boolean=} – If true then the returned object for this action is an array, see 返回值 section.
  • transformRequest – {Function(data, headersGetter)|Array.<Function(data, headersGetter)>} – transform function or an array of such functions. The transform function takes the http request body and headers and returns its transformed (typically serialized) version.
  • transformResponse – {Function(data, headersGetter)|Array.<Function(data, headersGetter)>} – transform function or an array of such functions. The transform function takes the http response body and headers and returns its transformed (typically deserialized) version.
  • cache – {boolean|Cache} – If true, a default $http cache will be used to cache the GET request, otherwise if a cache instance built with $cacheFactory, this cache will be used for caching.
  • timeout – {number|Promise} – timeout in milliseconds, or promise that should abort the request when resolved.
  • withCredentials - {boolean} - whether to set the withCredentials flag on the XHR object. See requests with credentials for more information.
  • responseType - {string} - see requestType.
  • interceptor - {Object=} - The interceptor object has two optional methods - response and responseError. Both response and responseError interceptors get called with http response object. See $http interceptors.
options Object

Hash with custom settings that should extend the default $resourceProvider behavior. The only supported option is

Where:

  • stripTrailingSlashes – {boolean} – If true then the trailing slashes from any calculated URL will be stripped. (Defaults to true.)

返回值

Object

A resource "class" object with methods for the default set of resource actions optionally extended with custom actions. The default set contains these actions:

  { 'get':    {method:'GET'},
    'save':   {method:'POST'},
    'query':  {method:'GET', isArray:true},
    'remove': {method:'DELETE'},
    'delete': {method:'DELETE'} };

Calling these methods invoke an $http with the specified http method, destination and parameters. When the data is returned from the server then the object is an instance of the resource class. The actions save, remove and delete are available on it as methods with the $ prefix. This allows you to easily perform CRUD operations (create, read, update, delete) on server-side data like this:

  var User = $resource('/user/:userId', {userId:'@id'});
  var user = User.get({userId:123}, Function() {
    user.abc = true;
    user.$save();
  });

It is important to realize that invoking a $resource object method immediately returns an empty reference (object or array depending on isArray). Once the data is returned from the server the existing reference is populated with the actual data. This is a useful trick since usually the resource is assigned to a model which is then rendered by the view. Having an empty object results in no rendering, once the data arrives from the server then the object is populated with the data and the view automatically re-renders itself showing the new data. This means that in most cases one never has to write a callback function for the action methods.

The action methods on the class object or instance object can be invoked with the following parameters:

  • HTTP GET "class" actions: Resource.action([参数], [success], [error])
  • non-GET "class" actions: Resource.action([参数], postData, [success], [error])

  • non-GET instance actions: instance.$action([参数], [success], [error])

    Success callback is called with (value, responseHeaders) arguments. Error callback is called with (httpResponse) argument.

    Class actions return empty instance (with additional properties below). Instance actions return promise of the action.

    The Resource instances and collection have these additional properties:

  • $promise: the promise of the original server interaction that created this instance or collection.

    On success, the promise is resolved with the same resource instance or collection object, updated with data from server. This makes it easy to use in resolve section of $routeProvider.when() to defer view rendering until the resource(s) are loaded.

    On failure, the promise is resolved with the http response object, without the resource property.

    If an interceptor object was provided, the promise will instead be resolved with the value returned by the interceptor.

  • $resolved: true after first server interaction is completed (either with success or rejection), false before that. Knowing if the Resource has been resolved is useful in data-binding.

示例

Credit card resource

     // Define CreditCard class
     var CreditCard = $resource('/user/:userId/card/:cardId',
      {userId:123, cardId:'@id'}, {
       charge: {method:'POST', params:{charge:true}}
      });

     // We can retrieve a collection from the server
     var cards = CreditCard.query(Function() {
       // GET: /user/123/card
       // server returns: [ {id:456, number:'1234', name:'Smith'} ];

       var card = cards[0];
       // each item is an instance of CreditCard
       expect(card instanceof CreditCard).toEqual(true);
       card.name= "J. Smith";
       // non GET methods are mapped onto the instances
       card.$save();
       // POST: /user/123/card/456 {id:456, number:'1234', name:'J. Smith'}
       // server returns: {id:456, number:'1234', name: 'J. Smith'};

       // our custom method is mapped as well.
       card.$charge({amount:9.99});
       // POST: /user/123/card/456?amount=9.99&charge=true {id:456, number:'1234', name:'J. Smith'}
     });

     // we can create an instance as well
     var newCard = new CreditCard({number:'0123'});
     newCard.name= "Mike Smith";
     newCard.$save();
     // POST: /user/123/card {number:'0123', name:'Mike Smith'}
     // server returns: {id:789, number:'0123', name: 'Mike Smith'};
     expect(newCard.id).toEqual(789);

The object returned from this function execution is a resource "class" which has "static" method for each action in the definition.

Calling these methods invoke $http on the url template with the given method, params and headers. When the data is returned from the server then the object is an instance of the resource type and all of the non-GET methods are available with $ prefix. This allows you to easily support CRUD operations (create, read, update, delete) on server-side data.

     var User = $resource('/user/:userId', {userId:'@id'});
     User.get({userId:123}, Function(user) {
       user.abc = true;
       user.$save();
     });

It's worth noting that the success callback for get, query and other methods gets passed in the response that came from the server as well as $http header getter function, so one could rewrite the above example and get access to http headers as:

     var User = $resource('/user/:userId', {userId:'@id'});
     User.get({userId:123}, Function(u, getResponseHeaders){
       u.abc = true;
       u.$save(Function(u, putResponseHeaders) {
         //u => saved user object
         //putResponseHeaders => $http header getter
       });
     });

You can also access the raw $http promise via the $promise property on the object returned

     var User = $resource('/user/:userId', {userId:'@id'});
     User.get({userId:123})
         .$promise.then(Function(user) {
           $scope.user = user;
         });

Creating a custom 'PUT' request

In this example we create a custom method on our resource to make a PUT request

    var app = angular.module('app', ['ngResource', 'ngRoute']);

    // Some APIs expect a PUT request in the format URL/object/ID
    // Here we are creating an 'update' method
    app.factory('Notes', ['$resource', Function($resource) {
   return $resource('/notes/:id', null,
       {
           'update': { method:'PUT' }
       });
    }]);

    // In our controller we get the ID from the URL using ngRoute and $routeParams
    // We pass in $routeParams and our Notes factory along with $scope
    app.controller('NotesCtrl', ['$scope', '$routeParams', 'Notes',
                                      Function($scope, $routeParams, Notes) {
   // First get a note object from the factory
   var note = Notes.get({ id:$routeParams.id });
   $id = note.id;

   // Now call update passing in the ID first then the object you are updating
   Notes.update({ id:$id }, note);

   // This will PUT /notes/ID with the note object in the request payload
    }]);


AngularJS: API: ngRoute

ngRoute

ngRoute

The ngRoute module provides routing and deeplinking services and directives for angular apps.

示例

参见 $route for an example of configuring and using ngRoute.

Installation

First include angular-route.js in your HTML:

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

You can download this file from the following places:

  • Google CDN
    例如 //ajax.googleapis.com/ajax/libs/angularjs/X.Y.Z/angular-route.js
  • Bower
    例如
    bower install angular-route@X.Y.Z
  • code.angularjs.org
    例如
    "//code.angularjs.org/X.Y.Z/angular-route.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', ['ngRoute']);

With that you're ready to get started!

模块组件

Directive

名称 描述
ngView

Overview

ngView is a directive that complements the $route service by including the rendered template of the current route into the main layout (index.html) file. Every time the current route changes, the included view changes with it according to the configuration of the $route service.

Provider

名称 | 描述
$routeProvider | Used for configuring routes.

Service

名称 | 描述
$route | $route is used for deep-linking URLs to controllers and views (HTML partials). It watches $location.url() and tries to map the path to an existing route definition.
$routeParams | The $routeParams service allows you to retrieve the current set of route parameters.


AngularJS: API: ngRoute/directive

Directive components in ngRoute

名称 描述
ngView

Overview

ngView is a directive that complements the $route service by including the rendered template of the current route into the main layout (index.html) file. Every time the current route changes, the included view changes with it according to the configuration of the $route service.


AngularJS: API: ngRoute/directive/ngView

ngView

  1. - directive in module ngRoute

Overview

ngView is a directive that complements the $route service by including the rendered template of the current route into the main layout (index.html) file. Every time the current route changes, the included view changes with it according to the configuration of the $route service.

Requires the ngRoute module to be installed.

指令信息

  • 这个指令会创建新的作用域(scope)。
  • 这个指令执行优先级为400.

用法

  • 作为元素使用: (这个指令能用于自定义元素，但要注意IE限制)。
    <ng-view
  [onload=""]
  [autoscroll=""]>
...
</ng-view>
  • 作为属性使用:
    <ANY
  [onload=""]
  [autoscroll=""]>
...
</ANY>
  • 作为CSS类使用:
    <ANY class="[onload: ;] [autoscroll: ;]"> ... </ANY>

动画

enter - animation is used to bring new content into the browser. leave - animation is used to animate existing content away.

The enter and leave animation occur concurrently.

点击这里 了解更多关于涉及动画的步骤。

参数

参数 类型 详述
onload
(可选)
string

Expression to evaluate whenever the view updates.

autoscroll
(可选)
string

Whether ngView should call $anchorScroll to scroll the viewport after the view is updated.

             - If the attribute is not set, disable scrolling.
             - If the attribute is set without value, enable scrolling.
             - Otherwise enable scrolling only if the `autoscroll` attribute value evaluated
               as an expression yields a truthy value.

事件

  • $viewContentLoaded

    Emitted every time the ngView content is reloaded.

    类型:

    emit

    目标:

    the current ngView scope

示例

index.html
<div ng-controller="MainCtrl as main">
  Choose:
  <a href="Book/Moby">Moby</a> |
  <a href="Book/Moby/ch/1">Moby: Ch1</a> |
  <a href="Book/Gatsby">Gatsby</a> |
  <a href="Book/Gatsby/ch/4?key=value">Gatsby: Ch4</a> |
  <a href="Book/Scarlet">Scarlet Letter</a><br/>

  <div class="view-animate-container">
    <div ng-view class="view-animate"></div>
  </div>
  <hr />

  <pre>$location.path() = {{main.$location.path()}}</pre>
  <pre>$route.current.templateUrl = {{main.$route.current.templateUrl}}</pre>
  <pre>$route.current.params = {{main.$route.current.params}}</pre>
  <pre>$routeParams = {{main.$routeParams}}</pre></div>
book.html
<div>
  controller: {{book.name}}<br />
  Book Id: {{book.params.bookId}}<br /></div>
chapter.html
<div>
  controller: {{chapter.name}}<br />
  Book Id: {{chapter.params.bookId}}<br />
  Chapter Id: {{chapter.params.chapterId}}
</div>
animations.css
.view-animate-container {
  position:relative;
  height:100px!important;
  position:relative;
  background:white;
  border:1px solid black;
  height:40px;
  overflow:hidden;}

.view-animate {
  padding:10px;}

.view-animate.ng-enter, .view-animate.ng-leave {
  -webkit-transition:all cubic-bezier(0.250, 0.460, 0.450, 0.940) 1.5s;
  transition:all cubic-bezier(0.250, 0.460, 0.450, 0.940) 1.5s;

  display:block;
  width:100%;
  border-left:1px solid black;

  position:absolute;
  top:0;
  left:0;
  right:0;
  bottom:0;
  padding:10px;}

.view-animate.ng-enter {
  left:100%;}.view-animate.ng-enter.ng-enter-active {
  left:0;}.view-animate.ng-leave.ng-leave-active {
  left:-100%;}
script.js
angular.module('ngViewExample', ['ngRoute', 'ngAnimate'])
  .config(['$routeProvider', '$locationProvider',
    Function($routeProvider, $locationProvider) {
      $routeProvider
        .when('/Book/:bookId', {
          templateUrl: 'book.html',
          controller: 'BookCtrl',
          controllerAs: 'book'
        })
        .when('/Book/:bookId/ch/:chapterId', {
          templateUrl: 'chapter.html',
          controller: 'ChapterCtrl',
          controllerAs: 'chapter'
        });

      // configure html5 to get links working on jsfiddle
      $locationProvider.html5Mode(true);
  }])
  .controller('MainCtrl', ['$route', '$routeParams', '$location',
    Function($route, $routeParams, $location) {
      this.$route = $route;
      this.$location = $location;
      this.$routeParams = $routeParams;
  }])
  .controller('BookCtrl', ['$routeParams', Function($routeParams) {
    this.名称= "BookCtrl";
    this.params = $routeParams;
  }])
  .controller('ChapterCtrl', ['$routeParams', Function($routeParams) {
    this.名称= "ChapterCtrl";
    this.params = $routeParams;
  }]);
protractor.js
it('should load and compile correct template', Function() {
  element(by.linkText('Moby: Ch1')).click();
  var content = element(by.css('[ng-view]')).getText();
  expect(content).toMatch(/controller\: ChapterCtrl/);
  expect(content).toMatch(/Book Id\: Moby/);
  expect(content).toMatch(/Chapter Id\: 1/);

  element(by.partialLinkText('Scarlet')).click();

  content = element(by.css('[ng-view]')).getText();
  expect(content).toMatch(/controller\: BookCtrl/);
  expect(content).toMatch(/Book Id\: Scarlet/);});


AngularJS: API: ngRoute/provider

Provider components in ngRoute

名称 | 描述
$routeProvider | Used for configuring routes.


AngularJS: API: ngRoute/provider/$routeProvider

$routeProvider

  1. - $route
  2. - provider in module ngRoute

Used for configuring routes.

示例

参见 $route for an example of configuring and using ngRoute.

依赖

Requires the ngRoute module to be installed.

用法

$routeProvider();

方法

  • when(path, route);

    Adds a new route definition to the $route service.

    参数

    参数 类型 详述
    path string

    Route path (matched against $location.path). If $location.path contains redundant trailing slash or is missing one, the route will still match and the $location.path will be updated to add or drop the trailing slash to exactly match the route definition.

    • path can contain named groups starting with a colon:例如 :名称. All characters up to the next slash are matched and stored in $routeParams under the given 名称 when the route matches.
    • path can contain named groups starting with a colon and ending with a star:例如:名称*. All characters are eagerly stored in $routeParams under the given 名称 when the route matches.

    • path can contain optional named groups with a question mark:例如:名称?.

      例如，routes like /color/:color/largecode/:largecode*\/edit will match /color/brown/largecode/code/with/slashes/edit and extract:

    • color: brown

    • largecode: code/with/slashes.
    route Object

    Mapping information to be assigned to $route.current on route match.

    Object properties:

    • controller – {(string|Function()=} – Controller fn that should be associated with newly created scope or the name of a registered controller if passed as a string.
    • controllerAs – {string=} – A controller alias name. If present the controller will be published to scope under the controllerAs name.

    • template – {string=|Function()=} – html template as a string or a function that returns an html template as a string which should be used by ngView or ngInclude directives. This property takes precedence over templateUrl.

      If template is a function, it will be called with the following parameters:

      • {Array.<Object>} - route parameters extracted from the current $location.path() by applying the current route

    • templateUrl – {string=|Function()=} – path or function that returns a path to an html template that should be used by ngView.

      If templateUrl is a function, it will be called with the following parameters:

      • {Array.<Object>} - route parameters extracted from the current $location.path() by applying the current route

    • resolve - {Object.<string, Function>=} - An optional map of dependencies which should be injected into the controller. If any of these dependencies are promises, the router will wait for them all to be resolved or one to be rejected before the controller is instantiated. If all the promises are resolved successfully, the values of the resolved promises are injected and $routeChangeSuccess event is fired. If any of the promises are rejected the $routeChangeError event is fired. The map object is:

      • key – {string}: a name of a dependency to be injected into the controller.
      • factory - {string|Function}: If string then it is an alias for a service. Otherwise if function, then it is injected and the return value is treated as the dependency. If the result is a promise, it is resolved before its value is injected into the controller. Be aware that ngRoute.$routeParams will still refer to the previous route within these resolve functions. Use $route.current.params to access the new route parameters, instead.

    • redirectTo – {(string|function())=} – value to update $location path with and trigger route redirection.

      If redirectTo is a function, it will be called with the following parameters:

      • {Object.<string>} - route parameters extracted from the current $location.path() by applying the current route templateUrl.
      • {string} - current $location.path()
      • {Object} - current $location.search()

      The custom redirectTo function is expected to return a string which will be used to update $location.path() and $location.search().

    • [reloadOnSearch=true] - {boolean=} - reload route when only $location.search() or $location.hash() changes.

      If the option is set to false and url in the browser changes, then $routeUpdate event is broadcasted on the root scope.

    • [caseInsensitiveMatch=false] - {boolean=} - match routes without being case sensitive

      If the option is set to true, then the particular route can be matched without being case sensitive

    返回值

    Object

    self

  • otherwise(params);

    Sets route definition that will be used on route change when no other route definition is matched.

    参数

    参数 类型 详述
    params Object

    Mapping information to be assigned to $route.current.

    返回值

    Object

    self


AngularJS: API: ngRoute/service

Service components in ngRoute

名称 | 描述
$route | $route is used for deep-linking URLs to controllers and views (HTML partials). It watches $location.url() and tries to map the path to an existing route definition.
$routeParams | The $routeParams service allows you to retrieve the current set of route parameters.


AngularJS: API: ngRoute/service/$route

$route

  1. - $routeProvider
  2. - service in module ngRoute

$route is used for deep-linking URLs to controllers and views (HTML partials). It watches $location.url() and tries to map the path to an existing route definition.

Requires the ngRoute module to be installed.

You can define routes through $routeProvider's API.

The $route service is typically used in conjunction with the ngView directive and the $routeParams service.

依赖

  • $location
  • $routeParams

方法

  • reload();

    Causes $route service to reload the current route even if $location hasn't changed.

    As a result of that, ngView creates new scope, reinstantiates the controller.

事件

  • $routeChangeStart

    Broadcasted before a route change. At this point the route services starts resolving all of the dependencies needed for the route change to occur. Typically this involves fetching the view template as well as any dependencies defined in resolve route property. Once all of the dependencies are resolved $routeChangeSuccess is fired.

    类型:

    broadcast

    目标:

    root scope

  • $routeChangeSuccess

    Broadcasted after a route dependencies are resolved. ngView listens for the directive to instantiate the controller and render the view.

    类型:

    broadcast

    目标:

    root scope

  • $routeChangeError

    Broadcasted if any of the resolve promises are rejected.

    类型:

    broadcast

    目标:

    root scope

  • $routeUpdate

    The reloadOnSearch property has been set to false, and we are reusing the same instance of the Controller.

    类型:

    broadcast

    目标:

    root scope

属性

  • current

    Object

    Reference to the current route definition. The route definition contains:

    • controller: The controller constructor as define in route definition.

    • locals: A map of locals which is used by $controller service for controller instantiation. The locals contain the resolved values of the resolve map. Additionally the locals also contain:

      • $scope - The current route scope.
      • $template - The current route template HTML.

  • routes

    Object

    Object with all route configuration Objects as its properties.

示例

This example shows how changing the URL hash causes the $route to match a route against the URL, and the ngView pulls in the partial.

Note that this example is using inlined templates to get it working on jsfiddle as well.

index.html
<div ng-controller="MainController">
  Choose:
  <a href="Book/Moby">Moby</a> |
  <a href="Book/Moby/ch/1">Moby: Ch1</a> |
  <a href="Book/Gatsby">Gatsby</a> |
  <a href="Book/Gatsby/ch/4?key=value">Gatsby: Ch4</a> |
  <a href="Book/Scarlet">Scarlet Letter</a><br/>

  <div ng-view></div>

  <hr />

  <pre>$location.path() = {{$location.path()}}</pre>
  <pre>$route.current.templateUrl = {{$route.current.templateUrl}}</pre>
  <pre>$route.current.params = {{$route.current.params}}</pre>
  <pre>$route.current.scope.name = {{$route.current.scope.name}}</pre>
  <pre>$routeParams = {{$routeParams}}</pre></div>
book.html
controller: {{名称}}<br />Book Id: {{params.bookId}}<br />
chapter.html
controller: {{名称}}<br />Book Id: {{params.bookId}}<br />Chapter Id: {{params.chapterId}}
script.js
angular.module('ngRouteExample', ['ngRoute'])

 .controller('MainController', Function($scope, $route, $routeParams, $location) {
     $scope.$route = $route;
     $scope.$location = $location;
     $scope.$routeParams = $routeParams;
 })

 .controller('BookController', Function($scope, $routeParams) {
     $scope.name= "BookController";
     $scope.params = $routeParams;
 })

 .controller('ChapterController', Function($scope, $routeParams) {
     $scope.name= "ChapterController";
     $scope.params = $routeParams;
 })

.config(Function($routeProvider, $locationProvider) {
  $routeProvider
   .when('/Book/:bookId', {
    templateUrl: 'book.html',
    controller: 'BookController',
    resolve: {
      // I will cause a 1 second delay
      delay: Function($q, $timeout) {
        var delay = $q.defer();
        $timeout(delay.resolve, 1000);
        return delay.promise;
      }
    }
  })
  .when('/Book/:bookId/ch/:chapterId', {
    templateUrl: 'chapter.html',
    controller: 'ChapterController'
  });

  // configure html5 to get links working on jsfiddle
  $locationProvider.html5Mode(true);});
protractor.js
it('should load and compile correct template', Function() {
  element(by.linkText('Moby: Ch1')).click();
  var content = element(by.css('[ng-view]')).getText();
  expect(content).toMatch(/controller\: ChapterController/);
  expect(content).toMatch(/Book Id\: Moby/);
  expect(content).toMatch(/Chapter Id\: 1/);

  element(by.partialLinkText('Scarlet')).click();

  content = element(by.css('[ng-view]')).getText();
  expect(content).toMatch(/controller\: BookController/);
  expect(content).toMatch(/Book Id\: Scarlet/);});


AngularJS: API: ngRoute/service/$routeParams

$routeParams

  1. - service in module ngRoute

The $routeParams service allows you to retrieve the current set of route parameters.

Requires the ngRoute module to be installed.

The route parameters are a combination of $location's search() and path(). The path parameters are extracted when the $route path is matched.

In case of parameter name collision, path params take precedence over search params.

The service guarantees that the identity of the $routeParams object will remain unchanged (but its properties will likely change) even when a route change occurs.

Note that the $routeParams are only updated after a route change completes successfully. This means that you cannot rely on $routeParams being correct in route resolve functions. Instead you can use $route.current.params to access the new route's parameters.

依赖

  • $route

示例

 // Given:
 // URL: http://server.com/index.html#/Chapter/1/Section/2?search=moby
 // Route: /Chapter/:chapterId/Section/:sectionId
 //
 // Then
 $routeParams ==> {chapterId:'1', sectionId:'2', search:'moby'}


AngularJS: API: ngSanitize

ngSanitize

ngSanitize

The ngSanitize module provides functionality to sanitize HTML.

参见 $sanitize for usage.

Installation

First include angular-sanitize.js in your HTML:

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

You can download this file from the following places:

  • Google CDN
    例如 //ajax.googleapis.com/ajax/libs/angularjs/X.Y.Z/angular-sanitize.js
  • Bower
    例如
    bower install angular-sanitize@X.Y.Z
  • code.angularjs.org
    例如
    "//code.angularjs.org/X.Y.Z/angular-sanitize.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', ['ngSanitize']);

With that you're ready to get started!

模块组件

Filter

名称 | 描述
linky | Finds links in text input and turns them into html links. Supports http/https/ftp/mailto and plain email address links.

Service

名称 | 描述
$sanitize | The input is sanitized by parsing the html into tokens. All safe tokens (from a whitelist) are then serialized back to properly escaped html string. This means that no unsafe input can make it into the returned string, however, since our parser is more strict than a typical browser parser, it's possible that some obscure input, which would be recognized as valid HTML by a browser, won't make it through the sanitizer. The whitelist is configured using the functions aHrefSanitizationWhitelist and imgSrcSanitizationWhitelist of $compileProvider.


AngularJS: API: ngSanitize/filter

Filter components in ngSanitize

名称 | 描述
linky | Finds links in text input and turns them into html links. Supports http/https/ftp/mailto and plain email address links.


AngularJS: API: ngSanitize/filter/linky

linky

  1. - filter in module ngSanitize

Finds links in text input and turns them into html links. Supports http/https/ftp/mailto and plain email address links.

Requires the ngSanitize module to be installed.

用法

用于HTML模板绑定

<span ng-bind-html="linky_expression | linky"></span>

用于JavaScript

$filter('linky')(text, target)

参数

参数 | 类型 | 详述
text | string | Input text.
target | string | Window (_blank|_self|_parent|_top) or named frame to open links in.

返回值

string

Html-linkified text.

示例

index.html
<script>
  angular.module('linkyExample', ['ngSanitize'])
    .controller('ExampleController', ['$scope', Function($scope) {
      $scope.snippet =
        'Pretty text with some links:\n'+
        'http://angularjs.org/,\n'+
        'mailto:us@somewhere.org,\n'+
        'another@somewhere.org,\n'+
        'and one more: ftp://127.0.0.1/.';
      $scope.snippetWithTarget = 'http://angularjs.org/';
    }]);</script><div ng-controller="ExampleController">
Snippet: <textarea ng-model="snippet" cols="60" rows="3"></textarea><table>
  <tr>
    <td>Filter</td>
    <td>Source</td>
    <td>Rendered</td>
  </tr>
  <tr id="linky-filter">
    <td>linky filter</td>
    <td>
      <pre><div ng-bind-html="snippet | linky"><br></div></pre>
    </td>
    <td>
      <div ng-bind-html="snippet | linky"></div>
    </td>
  </tr>
  <tr id="linky-target">
   <td>linky target</td>
   <td>
     <pre><div ng-bind-html="snippetWithTarget | linky:'_blank'"><br></div></pre>
   </td>
   <td>
     <div ng-bind-html="snippetWithTarget | linky:'_blank'"></div>
   </td>
  </tr>
  <tr id="escaped-html">
    <td>no filter</td>
    <td><pre><div ng-bind="snippet"><br></div></pre></td>
    <td><div ng-bind="snippet"></div></td>
  </tr></table>
protractor.js
it('should linkify the snippet with urls', Function() {
  expect(element(by.id('linky-filter')).element(by.binding('snippet | linky')).getText()).
      toBe('Pretty text with some links: http://angularjs.org/, us@somewhere.org, ' +
           'another@somewhere.org, and one more: ftp://127.0.0.1/.');
  expect(element.all(by.css('#linky-filter a')).count()).toEqual(4);});

it('should not linkify snippet without the linky filter', Function() {
  expect(element(by.id('escaped-html')).element(by.binding('snippet')).getText()).
      toBe('Pretty text with some links: http://angularjs.org/, mailto:us@somewhere.org, ' +
           'another@somewhere.org, and one more: ftp://127.0.0.1/.');
  expect(element.all(by.css('#escaped-html a')).count()).toEqual(0);});

it('should update', Function() {
  element(by.model('snippet')).clear();
  element(by.model('snippet')).sendKeys('new http://link.');
  expect(element(by.id('linky-filter')).element(by.binding('snippet | linky')).getText()).
      toBe('new http://link.');
  expect(element.all(by.css('#linky-filter a')).count()).toEqual(1);
  expect(element(by.id('escaped-html')).element(by.binding('snippet')).getText())
      .toBe('new http://link.');});

it('should work with the target property', Function() {
 expect(element(by.id('linky-target')).
     element(by.binding("snippetWithTarget | linky:'_blank'")).getText()).
     toBe('http://angularjs.org/');
 expect(element(by.css('#linky-target a')).getAttribute('target')).toEqual('_blank');});


AngularJS: API: ngSanitize/service

Service components in ngSanitize

名称 | 描述
$sanitize | The input is sanitized by parsing the html into tokens. All safe tokens (from a whitelist) are then serialized back to properly escaped html string. This means that no unsafe input can make it into the returned string, however, since our parser is more strict than a typical browser parser, it's possible that some obscure input, which would be recognized as valid HTML by a browser, won't make it through the sanitizer. The whitelist is configured using the functions aHrefSanitizationWhitelist and imgSrcSanitizationWhitelist of $compileProvider.


AngularJS: API: ngSanitize/service/$sanitize

$sanitize

  1. - service in module ngSanitize

The input is sanitized by parsing the html into tokens. All safe tokens (from a whitelist) are then serialized back to properly escaped html string. This means that no unsafe input can make it into the returned string, however, since our parser is more strict than a typical browser parser, it's possible that some obscure input, which would be recognized as valid HTML by a browser, won't make it through the sanitizer. The whitelist is configured using the functions aHrefSanitizationWhitelist and imgSrcSanitizationWhitelist of $compileProvider.

用法

$sanitize(html);

参数

参数 | 类型 | 详述
html | string | Html input.

返回值

string

Sanitized html.

示例

index.html
<script>
    angular.module('sanitizeExample', ['ngSanitize'])
      .controller('ExampleController', ['$scope', '$sce', Function($scope, $sce) {
        $scope.snippet =
          '<p style="color:blue">an html\n' +
          '<em onmouseover="this.textContent=\'PWN3D!\'">click here</em>\n' +
          'snippet</p>';
        $scope.deliberatelyTrustDangerousSnippet = Function() {
          return $sce.trustAsHtml($scope.snippet);
        };
      }]);</script><div ng-controller="ExampleController">
   Snippet: <textarea ng-model="snippet" cols="60" rows="3"></textarea>
  <table>
    <tr>
      <td>Directive</td>
      <td>How</td>
      <td>Source</td>
      <td>Rendered</td>
    </tr>
    <tr id="bind-html-with-sanitize">
      <td>ng-bind-html</td>
      <td>Automatically uses $sanitize</td>
      <td><pre><div ng-bind-html="snippet"><br/></div></pre></td>
      <td><div ng-bind-html="snippet"></div></td>
    </tr>
    <tr id="bind-html-with-trust">
      <td>ng-bind-html</td>
      <td>Bypass $sanitize by explicitly trusting the dangerous value</td>
      <td>
      <pre><div ng-bind-html="deliberatelyTrustDangerousSnippet()"></div></pre>
      </td>
      <td><div ng-bind-html="deliberatelyTrustDangerousSnippet()"></div></td>
    </tr>
    <tr id="bind-default">
      <td>ng-bind</td>
      <td>Automatically escapes</td>
      <td><pre><div ng-bind="snippet"><br/></div></pre></td>
      <td><div ng-bind="snippet"></div></td>
    </tr>
  </table>
  </div>
protractor.js
it('should sanitize the html snippet by default', Function() {
  expect(element(by.css('#bind-html-with-sanitize div')).getInnerHtml()).
    toBe('<p>an html\n<em>click here</em>\nsnippet</p>');});

it('should inline raw snippet if bound to a trusted value', Function() {
  expect(element(by.css('#bind-html-with-trust div')).getInnerHtml()).
    toBe("<p style=\"color:blue\">an html\n" +
         "<em onmouseover=\"this.textContent='PWN3D!'\">click here</em>\n" +
         "snippet</p>");});

it('should escape snippet without any filter', Function() {
  expect(element(by.css('#bind-default div')).getInnerHtml()).
    toBe("<p style=\"color:blue\">an html\n" +
         "<em onmouseover=\"this.textContent='PWN3D!'\">click here</em>\n" +
         "snippet</p>");});

it('should update', Function() {
  element(by.model('snippet')).clear();
  element(by.model('snippet')).sendKeys('new <b onclick="alert(1)">text</b>');
  expect(element(by.css('#bind-html-with-sanitize div')).getInnerHtml()).
    toBe('new <b>text</b>');
  expect(element(by.css('#bind-html-with-trust div')).getInnerHtml()).toBe(
    'new <b onclick="alert(1)">text</b>');
  expect(element(by.css('#bind-default div')).getInnerHtml()).toBe(
    "new <b onclick=\"alert(1)\">text</b>");});


AngularJS: API: ngTouch

ngTouch

ngTouch

The ngTouch module provides touch events and other helpers for touch-enabled devices. The implementation is based on jQuery Mobile touch event handling (jquerymobile.com).

参见 $swipe for usage.

Installation

First include angular-touch.js in your HTML:

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

You can download this file from the following places:

  • Google CDN
    例如 //ajax.googleapis.com/ajax/libs/angularjs/X.Y.Z/angular-touch.js
  • Bower
    例如
    bower install angular-touch@X.Y.Z
  • code.angularjs.org
    例如
    "//code.angularjs.org/X.Y.Z/angular-touch.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', ['ngTouch']);

With that you're ready to get started!

模块组件

Directive

名称 | 描述
ngClick | A more powerful replacement for the default ngClick designed to be used on touchscreen devices. Most mobile browsers wait about 300ms after a tap-and-release before sending the click event. This version handles them immediately, and then prevents the following click event from propagating.
ngSwipeLeft | Specify custom behavior when an element is swiped to the left on a touchscreen device. A leftward swipe is a quick, right-to-left slide of the finger. Though ngSwipeLeft is designed for touch-based devices, it will work with a mouse click and drag too.
ngSwipeRight | Specify custom behavior when an element is swiped to the right on a touchscreen device. A rightward swipe is a quick, left-to-right slide of the finger. Though ngSwipeRight is designed for touch-based devices, it will work with a mouse click and drag too.

Service

名称 | 描述
$swipe | The $swipe service is a service that abstracts the messier details of hold-and-drag swipe behavior, to make implementing swipe-related directives more convenient.


AngularJS: API: ngTouch/directive

Directive components in ngTouch

名称 | 描述
ngClick | A more powerful replacement for the default ngClick designed to be used on touchscreen devices. Most mobile browsers wait about 300ms after a tap-and-release before sending the click event. This version handles them immediately, and then prevents the following click event from propagating.
ngSwipeLeft | Specify custom behavior when an element is swiped to the left on a touchscreen device. A leftward swipe is a quick, right-to-left slide of the finger. Though ngSwipeLeft is designed for touch-based devices, it will work with a mouse click and drag too.
ngSwipeRight | Specify custom behavior when an element is swiped to the right on a touchscreen device. A rightward swipe is a quick, left-to-right slide of the finger. Though ngSwipeRight is designed for touch-based devices, it will work with a mouse click and drag too.


AngularJS: API: ngTouch/directive/ngClick

ngClick

  1. - directive in module ngTouch

A more powerful replacement for the default ngClick designed to be used on touchscreen devices. Most mobile browsers wait about 300ms after a tap-and-release before sending the click event. This version handles them immediately, and then prevents the following click event from propagating.

Requires the ngTouch module to be installed.

This directive can fall back to using an ordinary click event, and so works on desktop browsers as well as mobile.

This directive also sets the CSS class ng-click-active while the element is being held down (by a mouse click or touch) so you can restyle the depressed element if you wish.

指令信息

  • 这个指令执行优先级为0.

用法

  • 作为属性使用:
    <ANY
  ng-click="">
...
</ANY>

参数

参数 | 类型 | 详述
ngClick | expression | 在xx触发时执行的表达式 tap. (事件对象存于 $event)

示例

index.html
<button ng-click="count = count + 1" ng-init="count=0">
  Increment
</button>
count: {{ count }}
script.js
angular.module('ngClickExample', ['ngTouch']);


AngularJS: API: ngTouch/directive/ngSwipeLeft

ngSwipeLeft

  1. - directive in module ngTouch

Specify custom behavior when an element is swiped to the left on a touchscreen device. A leftward swipe is a quick, right-to-left slide of the finger. Though ngSwipeLeft is designed for touch-based devices, it will work with a mouse click and drag too.

To disable the mouse click and drag functionality, add ng-swipe-disable-mouse to the ng-swipe-left or ng-swipe-right DOM Element.

Requires the ngTouch module to be installed.

指令信息

  • 这个指令执行优先级为0.

用法

  • 作为属性使用:
    <ANY
  ng-swipe-left="">
...
</ANY>

参数

参数 | 类型 | 详述
ngSwipeLeft | expression | 在xx触发时执行的表达式 left swipe. (事件对象存于 $event)

示例

index.html
<div ng-show="!showActions" ng-swipe-left="showActions = true">
  Some list content, like an email in the inbox
</div><div ng-show="showActions" ng-swipe-right="showActions = false">
  <button ng-click="reply()">Reply</button>
  <button ng-click="delete()">Delete</button></div>
script.js
angular.module('ngSwipeLeftExample', ['ngTouch']);


AngularJS: API: ngTouch/directive/ngSwipeRight

ngSwipeRight

  1. - directive in module ngTouch

Specify custom behavior when an element is swiped to the right on a touchscreen device. A rightward swipe is a quick, left-to-right slide of the finger. Though ngSwipeRight is designed for touch-based devices, it will work with a mouse click and drag too.

Requires the ngTouch module to be installed.

指令信息

  • 这个指令执行优先级为0.

用法

  • 作为属性使用:
    <ANY
  ng-swipe-right="">
...
</ANY>

参数

参数 | 类型 | 详述
ngSwipeRight | expression | 在xx触发时执行的表达式 right swipe. (事件对象存于 $event)

示例

index.html
<div ng-show="!showActions" ng-swipe-left="showActions = true">
  Some list content, like an email in the inbox
</div><div ng-show="showActions" ng-swipe-right="showActions = false">
  <button ng-click="reply()">Reply</button>
  <button ng-click="delete()">Delete</button></div>
script.js
angular.module('ngSwipeRightExample', ['ngTouch']);


AngularJS: API: ngTouch/service

Service components in ngTouch

名称 | 描述
$swipe | The $swipe service is a service that abstracts the messier details of hold-and-drag swipe behavior, to make implementing swipe-related directives more convenient.


AngularJS: API: ngTouch/service/$swipe

$swipe

  1. - service in module ngTouch

The $swipe service is a service that abstracts the messier details of hold-and-drag swipe behavior, to make implementing swipe-related directives more convenient.

Requires the ngTouch module to be installed.

$swipe is used by the ngSwipeLeft and ngSwipeRight directives in ngTouch, and by ngCarousel in a separate component.

用法

The $swipe service is an object with a single method: bind. bind takes an element which is to be watched for swipes, and an object with four handler functions. See the documentation for bind below.

方法

  • bind();

    The main method of $swipe. It takes an element to be watched for swipe motions, and an object containing event handlers. The pointer types that should be used can be specified via the optional third argument, which is an array of strings 'mouse' and 'touch'. 默认情况下， $swipe will listen for mouse and touch events.

    The four events are start, move, end, and cancel. start, move, and end receive as a parameter a coordinates object of the form { x: 150, y: 310 }.

    start is called on either mousedown or touchstart. After this event, $swipe is watching for touchmove or mousemove events. These events are ignored until the total distance moved in either dimension exceeds a small threshold.

    Once this threshold is exceeded, either the horizontal or vertical delta is greater.

    • If the horizontal distance is greater, this is a swipe and move and end events follow.
    • If the vertical distance is greater, this is a scroll, and we let the browser take over. A cancel event is sent.

    move is called on mousemove and touchmove after the above logic has determined that a swipe is in progress.

    end is called when a swipe is successfully completed with a touchend or mouseup.

    cancel is called either on a touchcancel from the browser, or when we begin scrolling as described above.