ng 核心模块

0
(0)

ng

ng (核心模块)

这个ng模块是当AngularJS应用启动的时候默认加载的。这个模块自己包含了一个AngularJS应用工作必需的组件。下面的表格用等级的分类列出了核心模块中可用的每个services/factories,filters,directives和测试组件。

Module Components

Function

Name Description
angular.lowercase 转换特定的字符串为小写形式
angular.uppercase 转换特定的字符串为大写形式
angular.forEach 为obj集合中的每个项执行iterator函数,obj可以是一个对象或者是数组。这个iterator函数执行基于iterator(value,key,obj)结构的函数,value是一个对象的属性或者是数组的元素,key是对象的key或者是数组中的index,或者是obj自己。指定一个context给这个函数是可选的,context将作为iterator函数的this。
angular.extend 扩展目标对象dst,使用从src对象复制可枚举属性到dst。我可以指定多个src对象。如果你想要保留原始的对象,你可以通过一个空的目标对象实现:var object = angular.extend({}, object1, object2)。注意:记住angular.extend不支持递归合并(深度copy)。
angular.noop 这个函数不执行任何的操作。这个函数可以用于当需要一个函数风格的代码时。

function foo(callback) {
  var result = calculateResult();
  (callback || angular.noop)(result);
}
angular.identity 这个函数返回它的第一个参数。这个函数在编写函数形式的代码时有用
angular.isUndefined 判断一个变量是未声明的
angular.isDefined 判断一个变量是已经声明的
angular.isObject 判断一个引用是否是一个对象。不同于typeof关键字,null不被看作一个对象。注意,数组是对象。
angular.isString 判断一个引用是不是一个字符串对象
angular.isNumber 判断一个变量是不是数字对象
angular.isDate 判断一个值是不是date
angular.isArray 判断一个变量是数组
angular.isFunction 判断一个引用是函数
angular.isElement 判断一个引用是一个dom元素或者是被jquery包装过的元素
angular.copy 创建一个对象的深度拷贝,它可以是一个对象或者是数组
angular.equals 判断如果两个对象或者两个值是否相同。支持值类型,正则表达式,数组和对象。
angular.bind 返回一个函数fn,绑定了self参数为这个函数的this。你可以再传递一个args参数预先绑定到这个函数上。这个特性也称为局部应用,区别与函数柯里化。这里的柯里化很难理解,还没有理解是怎么一回事。
angular.toJson 序列化对象为JSON格式的字符串。属性如果以$$开头,则会被排除,因为angular内部使用这个标记。
angular.fromJson 反序列化JSON字符串为对象。
angular.bootstrap 使用这个函数去手动启动angular应用。
angular.reloadWithDebugInfo 使用这个函数去开启debug信息重新加载当前的应用。这个方式优先与调用$compileProvider.debugInfoEnabled(false)。
angular.injector 创建一个注射器对象它能够用于获取service的同时注入依赖(了解依赖注入
angular.element 包装一个原始的DOM元素或者HTML字符串为一个jQuery的元素。
angular.module angular.module是一个全局的用于创建、注册、获取angular模块。所有的模块(核心模块或者是第三方的)可用需要应用使用这个机制注册了这些模块。

Directive

Name Description
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 – e.g. on the <body> or <html> tags.

使用这个指令去自动启动一个AngularJS应用。ngApp指令指定应用的根元素并且通常放置在接近页面的根元素 – 例如 在body或者html标签上。

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

修改html的a标签的默认行为,所以当href为空白的时候,会阻止默认的行为。

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. The ngHref directive solves this problem.

使用Angular标记类似于{{hash}}在一个href属性中,如果点击的时机早于Angular替换{{hash}}标记将导致连接到错误的URL。直到Angular替换这个标签前这个连接将失败,最可能返回404错误。这个ngHref指令解决这个问题。

ngSrc Using Angular markup like {{hash}} in a srcattribute 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.

使用Angular 标记例如{{hash}}在一个src属性中不能正确工作:浏览器将从带有{{hash}}的URL中获取资源直到Angular替换了这个表达式。使用ngSrc指令可以解决这个问题。

ngSrcset Using Angular markup like {{hash}} in asrcset 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.

使用Angular 标记例如{{hash}}在一个srcset属性中不能正确工作:浏览器将从带有{{hash}}的URL中获取资源直到Angular替换了这个表达式。使用ngSrcset指令可以解决这个问题。

ngDisabled This directive sets the disabled attribute on the element if the expression inside ngDisabledevaluates to truthy.

如果元素上的ngDisabled表达式计算后得出真,这个指令将设置disabled指令到元素上

ngChecked The HTML specification does not require browsers to preserve the values of boolean attributes such as checked. (Their presence means true and their absence means false.) If we put an Angular interpolation expression into such an attribute then the binding information would be lost when the browser removes the attribute. The ngChecked directive solves this problem for the checked attribute. This complementary directive is not removed by the browser and so provides a permanent reliable place to store the binding information.

HTML的规范没有规定浏览器保存checked的boolean值。(当checked有的时候代表true,没有checked的时候表示false),如果我们放了一个angular 插值表达式到一个属性中来绑定这个信息,当浏览器删除这个属性的时候我们将失去绑定关系。ngChecked指令用来解决checked属性的这个问题,这个补充指令不会在浏览器删除因为它提供了一个可靠的位置去存储绑定信息。

ngReadonly The HTML specification does not require browsers to preserve the values of boolean attributes such as readonly. (Their presence means true and their absence means false.) If we put an Angular interpolation expression into such an attribute then the binding information would be lost when the browser removes the attribute. The ngReadonly directive solves this problem for the readonly attribute. This complementary directive is not removed by the browser and so provides a permanent reliable place to store the binding information.
ngSelected The HTML specification does not require browsers to preserve the values of boolean attributes such as selected. (Their presence means true and their absence means false.) If we put an Angular interpolation expression into such an attribute then the binding information would be lost when the browser removes the attribute. The ngSelected directive solves this problem for the selected attribute. This complementary directive is not removed by the browser and so provides a permanent reliable place to store the binding information.
ngOpen The HTML specification does not require browsers to preserve the values of boolean attributes such as open. (Their presence means true and their absence means false.) If we put an Angular interpolation expression into such an attribute then the binding information would be lost when the browser removes the attribute. ThengOpen directive solves this problem for theopen attribute. This complementary directive is not removed by the browser and so provides a permanent reliable place to store the binding information.
ngForm Nestable alias of form directive. HTML does not allow nesting of form elements. 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. When used together with ngModel, it provides data-binding, input state control, and validation. Input control follows HTML5 input types and polyfills the HTML5 validation behavior for older browsers.
ngValue Binds the given expression to the value of<option> or input[radio], so that when the element is selected, the ngModel of that element is set to the bound value.
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 thengBindTemplate attribute. Unlike ngBind, thengBindTemplate can contain multiple {{ }}expressions. This directive is needed since some HTML elements (such as TITLE and OPTION) cannot contain SPAN elements.
ngBindHtml Evaluates the expression and inserts the resulting HTML into the element in a secure way. By default, the resulting HTML content will be sanitized using the $sanitize service. To utilize this functionality, ensure that $sanitize is available, for example, by including ngSanitizein your module’s dependencies (not in core Angular). In order to use ngSanitize in your module’s dependencies, you need to include “angular-sanitize.js” in your application.
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).
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 specify custom behavior on a dblclick event.
ngMousedown The ngMousedown directive allows you to specify custom behavior on mousedown event.
ngMouseup Specify custom behavior on mouseup event.
ngMouseover Specify custom behavior on mouseover event.
ngMouseenter Specify custom behavior on mouseenter event.
ngMouseleave Specify custom behavior on mouseleave event.
ngMousemove Specify custom behavior on mousemove event.
ngKeydown Specify custom behavior on keydown event.
ngKeyup Specify custom behavior on keyup event.
ngKeypress Specify custom behavior on keypress event.
ngSubmit Enables binding angular expressions to onsubmit events.
ngFocus Specify custom behavior on focus event.
ngBlur Specify custom behavior on blur event.
ngCopy Specify custom behavior on copy event.
ngCut Specify custom behavior on cut event.
ngPaste Specify custom behavior on paste event.
ngIf The ngIf directive removes or recreates a portion of the DOM tree based on an {expression}. If the expression assigned to ngIfevaluates 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.
ngList Text input that converts between a delimited string and an array of strings. The default delimiter is a comma followed by a space – equivalent to ng-list=", ". You can specify a custom delimiter as the value of the ngListattribute – for example, ng-list=" | ".
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.
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.
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 plural categories 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 addangular-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 theng-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 addangular-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 ngSwitchbut without ngSwitchWhen or ngSwitchDefaultdirectives 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

Name Description
angular.version An object that contains information about the current AngularJS version. This object has the following properties:

Type

Name Description
angular.Module Interface for configuring angularmodules.
$cacheFactory.Cache A cache object used to store and retrieve data, primarily used by $httpand 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 ngModel 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 to control elements. Angular provides this DOM logic for most input elements. At the end of this page you can find a custom control example that usesngModelController to bind tocontenteditable elements.
$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.) See also the Scopes guide for an in-depth introduction and usage examples.

Provider

Name Description
$anchorScrollProvider Use $anchorScrollProvider to disable automatic scrolling whenever$location.hash() changes.
$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.resourceUrlWhitelistand$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

Service

Name Description
$anchorScroll When called, it checks the current value of$location.hash() and scrolls to the related element, according to the rules specified in theHtml5 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 ascript 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’swindow.document object.
$exceptionHandler Any uncaught exception in angular expressions 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’sXMLHttpRequest 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 delaymilliseconds.
$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 thewindow.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 service that helps you run functions asynchronously, and use their return values (or exceptions) when they are done processing.
$rootElement The root element of Angular application. This is either the element where ngApp was declared or the element passed intoangular.bootstrap. The element represents the root element of application. It is also the location where the application’s $injectorservice gets published, and 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.
$templateRequest The $templateRequest service runs security checks then downloads the provided template using $http and, upon success, stores the contents inside of $templateCache. If the HTTP request fails or the response data of the HTTP request is empty, a $compile error will be thrown (the exception can be thwarted by setting the 2nd parameter of the function to true). Note that the contents of$templateCache are trusted, so the call to$sce.getTrustedUrl(tpl) is omitted whentpl is of type string and $templateCache has the matching entry.
$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.

Input

Name Description
input[text] Standard HTML text input with angular data binding, inherited by most of the inputelements.
input[date] Input with date validation and transformation. In browsers that do not yet support the HTML5 date input, a text element will be used. In that case, text must be entered in a valid ISO-8601 date format (yyyy-MM-dd), for example: 2009-01-06. Since many modern browsers do not yet support this input type, it is important to provide cues to users on the expected input format via a placeholder or label.
input[datetime-local] 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:ss), for example:2010-12-28T14:57:00.
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:ss), for example: 14:57:00. Model must be a Date object. This binding will always output a Date object to the model of January 1, 1970, or local datenew Date(1970, 0, 1, HH, mm, ss).
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##), for example: 2013-W02.
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), for example:2009-01.
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 urlvalidation error key if the content is not a valid URL.
input[email] Text input with email validation. Sets the emailvalidation error key if not a valid email address.
input[radio] HTML radio button.
input[checkbox] HTML checkbox.

Filter

Name Description
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 requestedformat.
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, string or number, as specified by the value and sign (positive or negative) of limit. If a number is used as input, it is converted to a string.
orderBy Orders a specified array by the expressionpredicate. It is ordered alphabetically for strings and numerically for numbers. Note: if you notice numbers are not being sorted correctly, make sure they are actually being saved as numbers and not strings.

这篇文章有用吗?

平均评分 0 / 5. 投票数: 0

到目前为止还没有投票!成为第一位评论此文章。

很抱歉,这篇文章对您没有用!

让我们改善这篇文章!

告诉我们我们如何改善这篇文章?

发表回复

您的电子邮箱地址不会被公开。 必填项已用 * 标注

此站点使用Akismet来减少垃圾评论。了解我们如何处理您的评论数据