docs(guide): minor grammar fixes

This commit is contained in:
Matt Rohrer 2012-09-26 15:30:55 +02:00 committed by Brian Ford
parent 66f051386e
commit d4312b731a
32 changed files with 201 additions and 177 deletions

View file

@ -3,7 +3,7 @@
@description @description
External resources are URLs that provide JSON data, which are then rendered with the help of External resources are URLs that provide JSON data, which are then rendered with the help of
templates. angular has a resource factory that can be used to give names to the URLs and then templates. Angular has a resource factory that can be used to give names to the URLs and then
attach behavior to them. For example you can use the attach behavior to them. For example you can use the
{@link http://code.google.com/apis/buzz/v1/getting_started.html#background-operations| Google Buzz {@link http://code.google.com/apis/buzz/v1/getting_started.html#background-operations| Google Buzz
API} API}

View file

@ -5,7 +5,7 @@
Deep linking allows you to encode the state of the application in the URL so that it can be Deep linking allows you to encode the state of the application in the URL so that it can be
bookmarked and the application can be restored from the URL to the same state. bookmarked and the application can be restored from the URL to the same state.
While angular does not force you to deal with bookmarks in any particular way, it has services While Angular does not force you to deal with bookmarks in any particular way, it has services
which make the common case described here very easy to implement. which make the common case described here very easy to implement.
# Assumptions # Assumptions

View file

@ -2,7 +2,7 @@
@name Cookbook: Form @name Cookbook: Form
@description @description
A web application's main purpose is to present and gather data. For this reason angular strives A web application's main purpose is to present and gather data. For this reason Angular strives
to make both of these operations trivial. This example shows off how you can build a simple form to to make both of these operations trivial. This example shows off how you can build a simple form to
allow a user to enter data. allow a user to enter data.

View file

@ -28,10 +28,10 @@
Take a look through the source and note: Take a look through the source and note:
* The script tag that {@link guide/bootstrap bootstraps} the angular environment. * The script tag that {@link guide/bootstrap bootstraps} the Angular environment.
* The text {@link api/ng.directive:input input form control} which is * The text {@link api/ng.directive:input input form control} which is
bound to the greeting name text. bound to the greeting name text.
* No need for listener registration and event firing on change events. * There is no need for listener registration and event firing on change events.
* The implicit presence of the `name` variable which is in the root {@link api/ng.$rootScope.Scope scope}. * The implicit presence of the `name` variable which is in the root {@link api/ng.$rootScope.Scope scope}.
* The double curly brace `{{markup}}`, which binds the name variable to the greeting text. * The double curly brace `{{markup}}`, which binds the name variable to the greeting text.
* The concept of {@link guide/dev_guide.templates.databinding data binding}, which reflects any * The concept of {@link guide/dev_guide.templates.databinding data binding}, which reflects any

View file

@ -2,7 +2,7 @@
@name Cookbook @name Cookbook
@description @description
Welcome to the angular cookbook. Here we will show you typical uses of angular by example. Welcome to the Angular cookbook. Here we will show you typical uses of Angular by example.
# Hello World # Hello World
@ -45,7 +45,7 @@ allowing you to send links to specific screens in your app.
# Services # Services
{@link api/ng Services}: Services are long lived objects in your applications that are {@link api/ng Services}: Services are long lived objects in your applications that are
available across controllers. A collection of useful services are pre-bundled with angular but you available across controllers. A collection of useful services are pre-bundled with Angular but you
will likely add your own. Services are initialized using dependency injection, which resolves the will likely add your own. Services are initialized using dependency injection, which resolves the
order of initialization. This safeguards you from the perils of global state (a common way to order of initialization. This safeguards you from the perils of global state (a common way to
implement long lived objects). implement long lived objects).
@ -55,4 +55,4 @@ implement long lived objects).
{@link buzz Resources}: Web applications must be able to communicate with the external {@link buzz Resources}: Web applications must be able to communicate with the external
services to get and update data. Resources are the abstractions of external URLs which are services to get and update data. Resources are the abstractions of external URLs which are
specially tailored to angular data binding. specially tailored to Angular data binding.

View file

@ -2,7 +2,7 @@
@name Cookbook: MVC @name Cookbook: MVC
@description @description
MVC allows for a clean an testable separation between the behavior (controller) and the view MVC allows for a clean and testable separation between the behavior (controller) and the view
(HTML template). A Controller is just a JavaScript class which is grafted onto the scope of the (HTML template). A Controller is just a JavaScript class which is grafted onto the scope of the
view. This makes it very easy for the controller and the view to share the model. view. This makes it very easy for the controller and the view to share the model.
@ -115,7 +115,7 @@ view.
# Things to notice # Things to notice
* The controller is defined in JavaScript and has no reference to the rendering logic. * The controller is defined in JavaScript and has no reference to the rendering logic.
* The controller is instantiated by <angular/> and injected into the view. * The controller is instantiated by Angular and injected into the view.
* The controller can be instantiated in isolation (without a view) and the code will still execute. * The controller can be instantiated in isolation (without a view) and the code will still execute.
This makes it very testable. This makes it very testable.
* The HTML view is a projection of the model. In the above example, the model is stored in the * The HTML view is a projection of the model. In the above example, the model is stored in the

View file

@ -9,7 +9,7 @@ browser new HTML syntax. The compiler allows you to attach behavior to any HTML
and even create new HTML element or attributes with custom behavior. Angular calls these behavior and even create new HTML element or attributes with custom behavior. Angular calls these behavior
extensions {@link api/ng.$compileProvider#directive directives}. extensions {@link api/ng.$compileProvider#directive directives}.
HTML has a lot of constructs for formatting the HTML for static documents in declarative fashion. HTML has a lot of constructs for formatting the HTML for static documents in a declarative fashion.
For example if something needs to be centered, there is no need to provide instructions to the For example if something needs to be centered, there is no need to provide instructions to the
browser how the window size needs to be divided in half so that center is found, and that this browser how the window size needs to be divided in half so that center is found, and that this
center needs to be aligned with the text's center. Simply add `align="center"` attribute to any center needs to be aligned with the text's center. Simply add `align="center"` attribute to any
@ -37,7 +37,7 @@ process happens into two phases.
2. **Link:** combine the directives with a scope and produce a live view. Any changes in the 2. **Link:** combine the directives with a scope and produce a live view. Any changes in the
scope model are reflected in the view, and any user interactions with the view are reflected scope model are reflected in the view, and any user interactions with the view are reflected
in the scope model. Making the scope model a single source of truth. in the scope model. This makes the scope model the single source of truth.
Some directives such {@link api/ng.directive:ngRepeat Some directives such {@link api/ng.directive:ngRepeat
`ng-repeat`} clone DOM elements once for each item in collection. Having a compile and link phase `ng-repeat`} clone DOM elements once for each item in collection. Having a compile and link phase
@ -47,9 +47,9 @@ once for each clone instance.
# Directive # Directive
Directive is a behavior which should be triggered when specific HTML constructs are encountered in A directive is a behavior which should be triggered when specific HTML constructs are encountered in
compilation process. The directives can be placed in element names, attributes, class names, as the compilation process. The directives can be placed in element names, attributes, class names, as
well as comments. Here are some equivalent examples of invoking {@link well as comments. Here are some equivalent examples of invoking the {@link
api/ng.directive:ngBind `ng-bind`} directive. api/ng.directive:ngBind `ng-bind`} directive.
<pre> <pre>
@ -59,7 +59,7 @@ api/ng.directive:ngBind `ng-bind`} directive.
<!-- directive: ng-bind exp --> <!-- directive: ng-bind exp -->
</pre> </pre>
Directive is just a function which executes when the compiler encounters it in the DOM. See {@link A directive is just a function which executes when the compiler encounters it in the DOM. See {@link
api/ng.$compileProvider#directive directive API} for in-depth documentation on how api/ng.$compileProvider#directive directive API} for in-depth documentation on how
to write directives. to write directives.
@ -107,9 +107,9 @@ Here is a directive which makes any element draggable. Notice the `draggable` at
</example> </example>
The presence of `draggable` attribute on any element gives the element new behavior. The beauty of The presence of the `draggable` attribute on any element gives the element new behavior. The beauty of
this approach is that we have taught the browser a new trick. We have extended the vocabulary of this approach is that we have taught the browser a new trick. We have extended the vocabulary of
what the browser understands in a way, which is natural to anyone who is familiar with HTML what the browser understands in a way which is natural to anyone who is familiar with HTML
principles. principles.
@ -122,7 +122,7 @@ an element.
<img src="img/One_Way_Data_Binding.png"> <img src="img/One_Way_Data_Binding.png">
This means that any changes to the data need to be re-merged with the template and then This means that any changes to the data need to be re-merged with the template and then
`innerHTML`ed into the DOM. Some of the issues are: reading user input and merging it with data, `innerHTML`ed into the DOM. Some of the issues with this approach are: reading user input and merging it with data,
clobbering user input by overwriting it, managing the whole update process, and lack of behavior clobbering user input by overwriting it, managing the whole update process, and lack of behavior
expressiveness. expressiveness.

View file

@ -26,20 +26,20 @@ This is how we get the ball rolling (refer to the diagram and example below):
<img class="pull-right" style="padding-left: 3em;" src="img/guide/concepts-startup.png"> <img class="pull-right" style="padding-left: 3em;" src="img/guide/concepts-startup.png">
1. Browser loads the HTML and parses it into a DOM 1. The browser loads the HTML and parses it into a DOM
2. Browser loads `angular.js` script 2. The browser loads `angular.js` script
3. Angular waits for `DOMContentLoaded` event 3. Angular waits for `DOMContentLoaded` event
4. Angular looks for {@link api/ng.directive:ngApp ng-app} 4. Angular looks for {@link api/ng.directive:ngApp ng-app}
{@link guide/directive directive}, which designates application boundary {@link guide/directive directive}, which designates the application boundary
5. {@link guide/module Module} specified in {@link 5. The {@link guide/module Module} specified in {@link
api/ng.directive:ngApp ng-app} (if any) is used to configure api/ng.directive:ngApp ng-app} (if any) is used to configure
the {@link api/AUTO.$injector $injector} the {@link api/AUTO.$injector $injector}
6. {@link api/AUTO.$injector $injector} is used to create the {@link 6. The {@link api/AUTO.$injector $injector} is used to create the {@link
api/ng.$compile $compile} service as well as {@link api/ng.$compile $compile} service as well as {@link
api/ng.$rootScope $rootScope} api/ng.$rootScope $rootScope}
7. {@link api/ng.$compile $compile} service is used to compile the DOM and link 7. The {@link api/ng.$compile $compile} service is used to compile the DOM and link
it with {@link api/ng.$rootScope $rootScope} it with {@link api/ng.$rootScope $rootScope}
8. {@link api/ng.directive:ngInit ng-init} {@link 8. The {@link api/ng.directive:ngInit ng-init} {@link
guide/directive directive} assigns `World` to the `name` property on the {@link guide/scope guide/directive directive} assigns `World` to the `name` property on the {@link guide/scope
scope} scope}
9. The `{{name}}` {@link api/ng.$interpolate interpolates} the expression to 9. The `{{name}}` {@link api/ng.$interpolate interpolates} the expression to
@ -59,21 +59,21 @@ This is how we get the ball rolling (refer to the diagram and example below):
<img class="pull-right" style="padding-left: 3em; padding-bottom: 1em;" src="img/guide/concepts-runtime.png"> <img class="pull-right" style="padding-left: 3em; padding-bottom: 1em;" src="img/guide/concepts-runtime.png">
The diagram and the example below describe how Angular interacts with browser's event loop. The diagram and the example below describe how Angular interacts with the browser's event loop.
1. Browsers event-loop waits for an event to arrive. Event is a user interactions, timer event, 1. The browser's event-loop waits for an event to arrive. An event is a user interactions, timer event,
or network event (response from a server). or network event (response from a server).
2. The events callback gets executed. This enters the JavaScript context. The callback can 2. The event's callback gets executed. This enters the JavaScript context. The callback can
modify the DOM structure. modify the DOM structure.
3. Once the callback finishes execution, the browser leaves the JavaScript context and 3. Once the callback executes, the browser leaves the JavaScript context and
re-renders the view based on DOM changes. re-renders the view based on DOM changes.
Angular modifies the normal JavaScript flow by providing it's own event processing loop. This Angular modifies the normal JavaScript flow by providing its own event processing loop. This
splits the JavaScript into classical and Angular execution context. Only operations which are splits the JavaScript into classical and Angular execution context. Only operations which are
applied in Angular execution context will benefit from angular data-binding, exception handling, applied in Angular execution context will benefit from Angular data-binding, exception handling,
property watching, etc... Use $apply() to enter Angular execution context from JavaScript. Keep in property watching, etc... You can also use $apply() to enter Angular execution context from JavaScript. Keep in
mind that in most places (controllers, services) the $apply has already been called for you by the mind that in most places (controllers, services) $apply has already been called for you by the
directive which is handling the event. The need to call $apply is reserved only when directive which is handling the event. An explicit call to $apply is needed only when
implementing custom event callbacks, or when working with a third-party library callbacks. implementing custom event callbacks, or when working with a third-party library callbacks.
1. Enter Angular execution context by calling {@link guide/scope scope}`.`{@link 1. Enter Angular execution context by calling {@link guide/scope scope}`.`{@link
@ -89,14 +89,14 @@ implementing custom event callbacks, or when working with a third-party library
$evalAsync} queue is empty and the {@link api/ng.$rootScope.Scope#$watch $evalAsync} queue is empty and the {@link api/ng.$rootScope.Scope#$watch
$watch} list does not detect any changes. $watch} list does not detect any changes.
4. The {@link api/ng.$rootScope.Scope#$evalAsync $evalAsync} queue is used to 4. The {@link api/ng.$rootScope.Scope#$evalAsync $evalAsync} queue is used to
schedule work which needs to occur outside of current stack frame, but before the browser schedule work which needs to occur outside of current stack frame, but before the browser's
view render. This is usually done with `setTimeout(0)`, but the `setTimeout(0)` approach view render. This is usually done with `setTimeout(0)`, but the `setTimeout(0)` approach
suffers from slowness and may cause view flickering since the browser renders the view after suffers from slowness and may cause view flickering since the browser renders the view after
each event. each event.
5. The {@link api/ng.$rootScope.Scope#$watch $watch} list is a set of expressions 5. The {@link api/ng.$rootScope.Scope#$watch $watch} list is a set of expressions
which may have changed since last iteration. If a change is detected then the `$watch` which may have changed since last iteration. If a change is detected then the `$watch`
function is called which typically updates the DOM with the new value. function is called which typically updates the DOM with the new value.
6. Once Angular {@link api/ng.$rootScope.Scope#$digest $digest} loop finishes 6. Once the Angular {@link api/ng.$rootScope.Scope#$digest $digest} loop finishes
the execution leaves the Angular and JavaScript context. This is followed by the browser the execution leaves the Angular and JavaScript context. This is followed by the browser
re-rendering the DOM to reflect any changes. re-rendering the DOM to reflect any changes.
@ -188,7 +188,7 @@ a diagram depicting the scope boundaries.
<img class="pull-right" style="padding-left: 3em; padding-bottom: 1em;" src="img/guide/concepts-controller.png"> <img class="pull-right" style="padding-left: 3em; padding-bottom: 1em;" src="img/guide/concepts-controller.png">
Controller is the code behind the view. Its job is to construct the model and publish it to the A controller is the code behind the view. Its job is to construct the model and publish it to the
view along with callback methods. The view is a projection of the scope onto the template (the view along with callback methods. The view is a projection of the scope onto the template (the
HTML). The scope is the glue which marshals the model to the view and forwards the events to the HTML). The scope is the glue which marshals the model to the view and forwards the events to the
controller. controller.
@ -233,7 +233,7 @@ The separation of the controller and the view is important because:
<img class="pull-right" style="padding-left: 3em; padding-bottom: 1em;" src="img/guide/concepts-model.png"> <img class="pull-right" style="padding-left: 3em; padding-bottom: 1em;" src="img/guide/concepts-model.png">
The model is the data which is used merged with the template to produce the view. To be able to The model is the data which is used merged with the template to produce the view. To be able to
render the model into the view, the model has to be referenceable from the scope. Unlike many render the model into the view, the model has to be able to be referenced from the scope. Unlike many
other frameworks Angular makes no restrictions or requirements an the model. There are no classes other frameworks Angular makes no restrictions or requirements an the model. There are no classes
to inherit from or special accessor methods for accessing or changing the model. The model can be to inherit from or special accessor methods for accessing or changing the model. The model can be
primitive, object hash, or a full object Type. In short the model is a plain JavaScript object. primitive, object hash, or a full object Type. In short the model is a plain JavaScript object.
@ -250,7 +250,7 @@ primitive, object hash, or a full object Type. In short the model is a plain Jav
The view is what the users sees. The view begins its life as a template, it is merged with the The view is what the users sees. The view begins its life as a template, it is merged with the
model and finally rendered into the browser DOM. Angular takes a very different approach to model and finally rendered into the browser DOM. Angular takes a very different approach to
rendering the view, to most other templating systems. rendering the view, compared to most other templating systems.
* **Others** - Most templating systems begin as an HTML string with special templating markup. * **Others** - Most templating systems begin as an HTML string with special templating markup.
Often the template markup breaks the HTML syntax which means that the template can not be Often the template markup breaks the HTML syntax which means that the template can not be
@ -261,9 +261,9 @@ rendering the view, to most other templating systems.
is the granularity of the DOM updates. The key here is that the templating system manipulates is the granularity of the DOM updates. The key here is that the templating system manipulates
strings. strings.
* **Angular** - Angular is different, since its templating system works on DOM objects not on * **Angular** - Angular is different, since its templating system works on DOM objects not on
strings. The template is still written in HTML string, but it is HTML (not HTML with strings. The template is still written in an HTML string, but it is HTML (not HTML with
template sprinkled in.) The browser parses the HTML into DOM, and the DOM becomes the input to template sprinkled in.) The browser parses the HTML into the DOM, and the DOM becomes the input to
the template engine know as the {@link api/ng.$compile compiler}. The compiler the template engine known as the {@link api/ng.$compile compiler}. The compiler
looks for {@link guide/directive directives} which in turn set up {@link looks for {@link guide/directive directives} which in turn set up {@link
api/ng.$rootScope.Scope#$watch watches} on the model. The result is a api/ng.$rootScope.Scope#$watch watches} on the model. The result is a
continuously updating view which does not need template model re-merging. Your model becomes continuously updating view which does not need template model re-merging. Your model becomes
@ -291,7 +291,7 @@ rendering the view, to most other templating systems.
<a name="directives"></a> <a name="directives"></a>
# Directives # Directives
A directive is a behavior or DOM transformation which is triggered by a presence of an attribute, A directive is a behavior or DOM transformation which is triggered by the presence of a custom attribute,
element name, or a class name. A directive allows you to extend the HTML vocabulary in a element name, or a class name. A directive allows you to extend the HTML vocabulary in a
declarative fashion. Following is an example which enables data-binding for the `contenteditable` declarative fashion. Following is an example which enables data-binding for the `contenteditable`
in HTML. in HTML.
@ -337,7 +337,7 @@ in HTML.
<a name="filters"></a> <a name="filters"></a>
# Filters # Filters
{@link api/ng.$filter Filters} perform data transformation roles. Typically {@link api/ng.$filter Filters} perform data transformation. Typically
they are used in conjunction with the locale to format the data in locale specific output. they are used in conjunction with the locale to format the data in locale specific output.
They follow the spirit of UNIX filters and use similar syntax `|` (pipe). They follow the spirit of UNIX filters and use similar syntax `|` (pipe).
@ -358,7 +358,7 @@ They follow the spirit of UNIX filters and use similar syntax `|` (pipe).
<img class="pull-right" style="padding-left: 3em; padding-bottom: 1em;" src="img/guide/concepts-module-injector.png"> <img class="pull-right" style="padding-left: 3em; padding-bottom: 1em;" src="img/guide/concepts-module-injector.png">
An {@link api/AUTO.$injector injector} is a service locator. There is a single The {@link api/AUTO.$injector injector} is a service locator. There is a single
{@link api/AUTO.$injector injector} per Angular {@link {@link api/AUTO.$injector injector} per Angular {@link
api/ng.directive:ngApp application}. The {@link api/ng.directive:ngApp application}. The {@link
api/AUTO.$injector injector} provides a way to look up an object instance by its api/AUTO.$injector injector} provides a way to look up an object instance by its
@ -438,7 +438,7 @@ dependencies, look for dependencies, or even get a reference to the injector.
</file> </file>
<file name="script.js"> <file name="script.js">
angular.module('timeExampleModule', []). angular.module('timeExampleModule', []).
// Declare new object call time, // Declare new object called time,
// which will be available for injection // which will be available for injection
factory('time', function($timeout) { factory('time', function($timeout) {
var time = {}; var time = {};

View file

@ -11,7 +11,7 @@ that will help you verify the health of your Angular application.
# Overview # Overview
You will write scenario tests in JavaScript, which describe how your application should behave, You will write scenario tests in JavaScript, which describe how your application should behave,
given a certain interaction in a specific state. A scenario is comprised of one or more it blocks given a certain interaction in a specific state. A scenario is comprised of one or more `it` blocks
(you can think of these as the requirements of your application), which in turn are made of (you can think of these as the requirements of your application), which in turn are made of
**commands** and **expectations**. Commands tell the Runner to do something with the application **commands** and **expectations**. Commands tell the Runner to do something with the application
(such as navigate to a page or click on a button), and expectations tell the Runner to assert (such as navigate to a page or click on a button), and expectations tell the Runner to assert
@ -175,4 +175,4 @@ Executes the `method` passing in `key` and `value` on the element matching the g
JavaScript is a dynamically typed language which comes with great power of expression, but it also JavaScript is a dynamically typed language which comes with great power of expression, but it also
come with almost no-help from the compiler. For this reason we feel very strongly that any code come with almost no-help from the compiler. For this reason we feel very strongly that any code
written in JavaScript needs to come with a strong set of tests. We have built many features into written in JavaScript needs to come with a strong set of tests. We have built many features into
angular which makes testing your angular applications easy. So there is no excuse for not do it. angular which makes testing your angular applications easy. So there is no excuse for not testing.

View file

@ -3,11 +3,11 @@
@description @description
While Model-View-Controller (MVC) has acquired different shades of meaning over the years since it While Model-View-Controller (MVC) has acquired different shades of meaning over the years since it
first appeared, angular incorporates the basic principles behind the original {@link first appeared, Angular incorporates the basic principles behind the original {@link
http://en.wikipedia.org/wiki/Modelviewcontroller MVC} software design pattern into its way of http://en.wikipedia.org/wiki/Modelviewcontroller MVC} software design pattern into its way of
building client-side web applications. building client-side web applications.
The MVC pattern greatly summarized: The MVC pattern summarized:
* Separate applications into distinct presentation, data, and logic components * Separate applications into distinct presentation, data, and logic components
* Encourage loose coupling between these components * Encourage loose coupling between these components

View file

@ -2,10 +2,10 @@
@name Developer Guide: About MVC in Angular: Understanding the Controller Component @name Developer Guide: About MVC in Angular: Understanding the Controller Component
@description @description
In angular, a controller is a JavaScript function(type/class) that is used to augment instances of In Angular, a controller is a JavaScript function(type/class) that is used to augment instances of
angular {@link scope Scope}, excluding the root scope. When you or angular create a new angular {@link scope Scope}, excluding the root scope. When you or Angular create a new
child scope object via the {@link api/ng.$rootScope.Scope#$new scope.$new} API , there is an child scope object via the {@link api/ng.$rootScope.Scope#$new scope.$new} API , there is an
option to pass in a controller as a method argument. This will tell angular to associate the option to pass in a controller as a method argument. This will tell Angular to associate the
controller with the new scope and to augment its behavior. controller with the new scope and to augment its behavior.
Use controllers to: Use controllers to:
@ -15,10 +15,10 @@ Use controllers to:
# Setting up the initial state of a scope object # Setting up the initial state of a scope object
Typically, when you create an application you need to set up an initial state for an angular scope. Typically, when you create an application you need to set up an initial state for an Angular scope.
Angular applies (in the sense of JavaScript's `Function#apply`) the controller constructor function Angular applies (in the sense of JavaScript's `Function#apply`) the controller constructor function
to a new angular scope object, which sets up an initial scope state. This means that angular never to a new Angular scope object, which sets up an initial scope state. This means that Angular never
creates instances of the controller type (by invoking the `new` operator on the controller creates instances of the controller type (by invoking the `new` operator on the controller
constructor). Constructors are always applied to an existing scope object. constructor). Constructors are always applied to an existing scope object.
@ -30,9 +30,23 @@ function GreetingCtrl($scope) {
The `GreetingCtrl` controller creates a `greeting` model which can be referred to in a template. The `GreetingCtrl` controller creates a `greeting` model which can be referred to in a template.
**NOTE**: Many of the examples in the documentation show the creation of functions
in the global scope. This is only for demonstration purposes - in a real
application you should use the `.controller` method of your Angular module for
your application as follows:
var myApp = angular.module('myApp',[]);
myApp.controller('GreetingCtrl', ['$scope', function(scope) {
scope.greeting = 'Hola!';
}]);
Note also that we use the array notation to explicitly specify the dependency
of the controller on the `$scope` service provided by Angular.
# Adding Behavior to a Scope Object # Adding Behavior to a Scope Object
Behavior on an angular scope object is in the form of scope method properties available to the Behavior on an Angular scope object is in the form of scope method properties available to the
template/view. This behavior interacts with and modifies the application model. template/view. This behavior interacts with and modifies the application model.
As discussed in the {@link dev_guide.mvc.understanding_model Model} section of this guide, any As discussed in the {@link dev_guide.mvc.understanding_model Model} section of this guide, any
@ -55,14 +69,14 @@ Do not use controllers for:
- Any kind of DOM manipulation — Controllers should contain only business logic. DOM - Any kind of DOM manipulation — Controllers should contain only business logic. DOM
manipulation—the presentation logic of an application—is well known for being hard to test. manipulation—the presentation logic of an application—is well known for being hard to test.
Putting any presentation logic into controllers significantly affects testability of the business Putting any presentation logic into controllers significantly affects testability of the business
logic. Angular offers {@link dev_guide.templates.databinding} for automatic DOM manipulation. If logic. Angular offers {@link dev_guide.templates.databinding databinding} for automatic DOM manipulation. If
you have to perform your own manual DOM manipulation, encapsulate the presentation logic in you have to perform your own manual DOM manipulation, encapsulate the presentation logic in
{@link guide/directive directives}. {@link guide/directive directives}.
- Input formatting — Use {@link forms angular form controls} instead. - Input formatting — Use {@link forms angular form controls} instead.
- Output filtering — Use {@link dev_guide.templates.filters angular filters} instead. - Output filtering — Use {@link dev_guide.templates.filters angular filters} instead.
- Run stateless or stateful code shared across controllers — Use {@link dev_guide.services angular - To run stateless or stateful code shared across controllers — Use {@link dev_guide.services angular
services} instead. services} instead.
- Instantiate or manage the life-cycle of other components (for example, to create service - To instantiate or manage the life-cycle of other components (for example, to create service
instances). instances).
@ -157,7 +171,7 @@ input box) in the second button.
## Controller Inheritance Example ## Controller Inheritance Example
Controller inheritance in angular is based on {@link api/ng.$rootScope.Scope Scope} inheritance. Let's Controller inheritance in Angular is based on {@link api/ng.$rootScope.Scope Scope} inheritance. Let's
have a look at an example: have a look at an example:
<pre> <pre>
@ -197,7 +211,7 @@ Inheritance works between controllers in the same way as it does with models. So
examples, all of the models could be replaced with controller methods that return string values. examples, all of the models could be replaced with controller methods that return string values.
Note: Standard prototypical inheritance between two controllers doesn't work as one might expect, Note: Standard prototypical inheritance between two controllers doesn't work as one might expect,
because as we mentioned earlier, controllers are not instantiated directly by angular, but rather because as we mentioned earlier, controllers are not instantiated directly by Angular, but rather
are applied to the scope object. are applied to the scope object.
@ -241,8 +255,8 @@ describe('myController function', function() {
</pre> </pre>
If you need to test a nested controller one needs to create the same scope hierarchy If you need to test a nested controller you need to create the same scope hierarchy
in your test as exist in the DOM. in your test that exists in the DOM.
<pre> <pre>
describe('state', function() { describe('state', function() {

View file

@ -2,16 +2,16 @@
@name Developer Guide: About MVC in Angular: Understanding the Model Component @name Developer Guide: About MVC in Angular: Understanding the Model Component
@description @description
Depending on the context of the discussion in angular documentation, the term _model_ can refer to Depending on the context of the discussion in the Angular documentation, the term _model_ can refer to
either a single object representing one entity (for example, a model called "phones" with its value either a single object representing one entity (for example, a model called "phones" with its value
being an array of phones) or the entire data model for the application (all entities). being an array of phones) or the entire data model for the application (all entities).
In angular, a model is any data that is reachable as a property of an angular {@link In Angular, a model is any data that is reachable as a property of an angular {@link
scope Scope} object. The name of the property is the model identifier and the value is scope Scope} object. The name of the property is the model identifier and the value is
any JavaScript object (including arrays and primitives). any JavaScript object (including arrays and primitives).
The only requirement for a JavaScript object to be a model in angular is that the object must be The only requirement for a JavaScript object to be a model in Angular is that the object must be
referenced by an angular scope as a property of that scope object. This property reference can be referenced by an Angular scope as a property of that scope object. This property reference can be
created explicitly or implicitly. created explicitly or implicitly.
You can create models by explicitly creating scope properties referencing JavaScript objects in the You can create models by explicitly creating scope properties referencing JavaScript objects in the
@ -52,11 +52,11 @@ cloud".
The code above creates one child scope for each item in the "phones" array and creates a "phone" The code above creates one child scope for each item in the "phones" array and creates a "phone"
object (model) on each of these scopes with its value set to the value of "phone" in the array. object (model) on each of these scopes with its value set to the value of "phone" in the array.
In angular, a JavaScript object stops being a model when: In Angular, a JavaScript object stops being a model when:
* No angular scope contains a property that references the object. * No Angular scope contains a property that references the object.
* All angular scopes that contain a property referencing the object become stale and eligible for * All Angular scopes that contain a property referencing the object become stale and eligible for
garbage collection. garbage collection.
The following illustration shows a simple data model created implicitly from a simple template: The following illustration shows a simple data model created implicitly from a simple template:

View file

@ -2,14 +2,14 @@
@name Developer Guide: About MVC in Angular: Understanding the View Component @name Developer Guide: About MVC in Angular: Understanding the View Component
@description @description
In angular, the view is the DOM loaded and rendered in the browser, after angular has transformed In Angular, the view is the DOM loaded and rendered in the browser, after Angular has transformed
the DOM based on information in the template, controller and model. the DOM based on information in the template, controller and model.
<img src="img/guide/about_view_final.png"> <img src="img/guide/about_view_final.png">
In the angular implementation of MVC, the view has knowledge of both the model and the controller. In the Angular implementation of MVC, the view has knowledge of both the model and the controller.
The view knows about the model where two-way data-binding occurs. The view has knowledge of the The view knows about the model where two-way data-binding occurs. The view has knowledge of the
controller through angular directives, such as {@link api/ng.directive:ngController controller through Angular directives, such as {@link api/ng.directive:ngController
ngController} and {@link api/ng.directive:ngView ngView}, and through bindings of this form: ngController} and {@link api/ng.directive:ngView ngView}, and through bindings of this form:
`{{someControllerFunction()}}`. In these ways, the view can call functions in an associated `{{someControllerFunction()}}`. In these ways, the view can call functions in an associated
controller function. controller function.

View file

@ -73,10 +73,9 @@ Any time your application needs to react to a change in the current URL or if yo
the current URL in the browser. the current URL in the browser.
## What does it not do? ## What does it not do?
Does not cause a full page reload when the browser URL is changed. To reload the page after It does not cause a full page reload when the browser URL is changed. To reload the page after
changing the URL, use the lower-level API, `$window.location.href`. changing the URL, use the lower-level API, `$window.location.href`.
# General overview of the API # General overview of the API
The `$location` service can behave differently, depending on the configuration that was provided to The `$location` service can behave differently, depending on the configuration that was provided to
@ -133,12 +132,12 @@ current URL without creating a new browser history record you can call:
// or you can chain these as: $location.path('/someNewPath').replace(); // or you can chain these as: $location.path('/someNewPath').replace();
</pre> </pre>
Note that the setters don't update `window.location` immediately. Instead, `$location` service is Note that the setters don't update `window.location` immediately. Instead, the `$location` service is
aware of the {@link api/ng.$rootScope.Scope scope} life-cycle and coalesces multiple `$location` aware of the {@link api/ng.$rootScope.Scope scope} life-cycle and coalesces multiple `$location`
mutations into one "commit" to the `window.location` object during the scope `$digest` phase. Since mutations into one "commit" to the `window.location` object during the scope `$digest` phase. Since
multiple changes to the $location's state will be pushed to the browser as a single change, it's multiple changes to the $location's state will be pushed to the browser as a single change, it's
enough to call the `replace()` method just once to make the entire "commit" a replace operation enough to call the `replace()` method just once to make the entire "commit" a replace operation
rather than addition to the browser history. Once the browser is updated, the $location service rather than an addition to the browser history. Once the browser is updated, the $location service
resets the flag set by `replace()` method and future mutations will create new history records, resets the flag set by `replace()` method and future mutations will create new history records,
unless `replace()` is called again. unless `replace()` is called again.
@ -304,7 +303,7 @@ history API or not; the `$location` service makes this transparent to you.
### Html link rewriting ### Html link rewriting
When you use the history API mode, you will need different links in different browser, but all you When you use HTML5 history API mode, you will need different links in different browsers, but all you
have to do is specify regular URL links, such as: `<a href="/some?foo=bar">link</a>` have to do is specify regular URL links, such as: `<a href="/some?foo=bar">link</a>`
When a user clicks on this link, When a user clicks on this link,

View file

@ -48,9 +48,9 @@ create this instance when called.
# Dependencies # Dependencies
Services can not only be depended upon, but also have its own dependencies. These can be specified Services can not only be depended upon, but can also have their own dependencies. These can be specified
as arguments of the factory function. {@link di Read more} about the DI as arguments of the factory function. {@link di Read more} about dependency injection (DI)
in Angular and the use of array notation and $inject property to make DI annotation in Angular and the use of array notation and the $inject property to make DI annotation
minification-proof. minification-proof.
Following is an example of a very simple service. This service depends on the `$window` service Following is an example of a very simple service. This service depends on the `$window` service
@ -78,7 +78,7 @@ angular.module('myModule', [], function($provide) {
All services in Angular are instantiated lazily. This means that a service will be created All services in Angular are instantiated lazily. This means that a service will be created
only when it is needed for instantiation of a service or an application component that depends on it. only when it is needed for instantiation of a service or an application component that depends on it.
In other words, Angular won't instantiate lazy services unless they are requested directly or In other words, Angular won't instantiate services unless they are requested directly or
indirectly by the application. indirectly by the application.

View file

@ -39,8 +39,8 @@ function myModuleCfgFn($provide) {
</pre> </pre>
Here is an example of two services that depend on each other, as well as on other services that are Here is an example of two services, one of which depends on the other and both
provided by Angular's web framework: of which depend on other services that are provided by the Angular framework:
<pre> <pre>
/** /**

View file

@ -2,10 +2,9 @@
@name Developer Guide: Angular Services @name Developer Guide: Angular Services
@description @description
Services are a feature that angular brings to client-side web apps from the server side, where Services are a feature that Angular brings to client-side web apps from the server side, where
services have been commonly used for a long time. Services in angular apps are substitutable services have been commonly used for a long time. Services in Angular apps are substitutable
objects that are wired together using {@link di dependency injection (DI)}. Services are objects that are wired together using {@link di dependency injection (DI)}.
most often used with {@link di dependency injection}, also a key feature of angular apps.
## Related Topics ## Related Topics

View file

@ -6,9 +6,9 @@ Angular services are singletons that carry out specific tasks common to web apps
{@link api/ng.$http $http service} that provides low level access to the browser's {@link api/ng.$http $http service} that provides low level access to the browser's
`XMLHttpRequest` object. `XMLHttpRequest` object.
To use an angular service, you identify it as a dependency for the dependent (a controller, or To use an Angular service, you identify it as a dependency for the dependent (a controller, or
another service) that depends on the service. Angular's dependency injection subsystem takes care another service) that depends on the service. Angular's dependency injection subsystem takes care
of the rest. The angular injector subsystem is in charge of service instantiation, resolution of of the rest. The Angular injector subsystem is in charge of service instantiation, resolution of
dependencies, and provision of dependencies to factory functions as requested. dependencies, and provision of dependencies to factory functions as requested.
Angular injects dependencies using "constructor" injection (the service is passed in via a factory Angular injects dependencies using "constructor" injection (the service is passed in via a factory
@ -18,7 +18,7 @@ must explicitly define its dependencies by using the `$inject` property. For ex
myController.$inject = ['$location']; myController.$inject = ['$location'];
The angular web framework provides a set of services for common operations. Like other core angular The Angular web framework provides a set of services for common operations. Like other core Angular
variables and identifiers, the built-in services always start with `$` (such as `$http` mentioned variables and identifiers, the built-in services always start with `$` (such as `$http` mentioned
above). You can also create your own custom services. above). You can also create your own custom services.

View file

@ -2,8 +2,8 @@
@name Developer Guide: Templates: Data Binding in Angular @name Developer Guide: Templates: Data Binding in Angular
@description @description
Data-binding in angular web apps is the automatic syncing of data between the model and view Data-binding in Angular web apps is the automatic syncronization of data between the model and view
components. The way that angular implements data-binding lets you treat the model as the components. The way that Angular implements data-binding lets you treat the model as the
single-source-of-truth in your application. The view is a projection of the model at all times. single-source-of-truth in your application. The view is a projection of the model at all times.
When the model changes, the view reflects the change, and vice versa. When the model changes, the view reflects the change, and vice versa.
@ -19,7 +19,7 @@ to write code that constantly syncs the view with the model and the model with t
## Data Binding in Angular Templates ## Data Binding in Angular Templates
<img class="right" src="img/Two_Way_Data_Binding.png"/> <img class="right" src="img/Two_Way_Data_Binding.png"/>
The way angular templates works is different, as illustrated in the diagram. They are different The way Angular templates works is different, as illustrated in the diagram. They are different
because first the template (which is the uncompiled HTML along with any additional markup or because first the template (which is the uncompiled HTML along with any additional markup or
directives) is compiled on the browser, and second, the compilation step produces a live view. We directives) is compiled on the browser, and second, the compilation step produces a live view. We
say live because any changes to the view are immediately reflected in the model, and any changes in say live because any changes to the view are immediately reflected in the model, and any changes in

View file

@ -2,13 +2,13 @@
@name Developer Guide: Understanding Angular Templates @name Developer Guide: Understanding Angular Templates
@description @description
An angular template is the declarative specification that, along with information from the model An Angular template is the declarative specification that, along with information from the model
and controller, becomes the rendered view that a user sees in the browser. It is the static DOM, and controller, becomes the rendered view that a user sees in the browser. It is the static DOM,
containing HTML, CSS, and angular-specific elements and angular-specific element attributes. The containing HTML, CSS, and angular-specific elements and angular-specific element attributes. The
angular elements and attributes direct angular to add behavior and transform the template DOM into Angular elements and attributes direct angular to add behavior and transform the template DOM into
the dynamic view DOM. the dynamic view DOM.
These are the types of angular elements and element attributes you can use in a template: These are the types of Angular elements and element attributes you can use in a template:
* {@link guide/directive Directive} — An attribute or element that * {@link guide/directive Directive} — An attribute or element that
augments an existing DOM element or represents a reusable DOM component - a widget. augments an existing DOM element or represents a reusable DOM component - a widget.
@ -20,8 +20,8 @@ curly brace notation `{{ }}` to bind expressions to elements is built-in angular
Note: In addition to declaring the elements above in templates, you can also access these elements Note: In addition to declaring the elements above in templates, you can also access these elements
in JavaScript code. in JavaScript code.
The following code snippet shows a simple angular template made up of standard HTML tags along with The following code snippet shows a simple Angular template made up of standard HTML tags along with
angular {@link guide/directive directives} and curly-brace bindings Angular {@link guide/directive directives} and curly-brace bindings
with {@link expression expressions}: with {@link expression expressions}:
<pre> <pre>

View file

@ -5,35 +5,47 @@
JavaScript is a dynamically typed language which comes with great power of expression, but it also JavaScript is a dynamically typed language which comes with great power of expression, but it also
come with almost no-help from the compiler. For this reason we feel very strongly that any code come with almost no-help from the compiler. For this reason we feel very strongly that any code
written in JavaScript needs to come with a strong set of tests. We have built many features into written in JavaScript needs to come with a strong set of tests. We have built many features into
angular which makes testing your angular applications easy. So there is no excuse for not do it. Angular which makes testing your Angular applications easy. So there is no excuse for not testing.
# It is all about NOT mixing concerns # It is all about NOT mixing concerns
Unit testing as the name implies is about testing individual units of code. Unit tests try to Unit testing as the name implies is about testing individual units of code. Unit tests try to
answer the question: Did I think about the logic correctly. Does the sort function order the list answer questions such as "Did I think about the logic correctly?" or "Does the sort function order the list
in the right order. In order to answer such question it is very important that we can isolate it. in the right order?"
That is because when we are testing the sort function we don't want to be forced into crating
related pieces such as the DOM elements, or making any XHR calls in getting the data to sort. While In order to answer such question it is very important that we can isolate the unit of code under test.
That is because when we are testing the sort function we don't want to be forced into creating
related pieces such as the DOM elements, or making any XHR calls in getting the data to sort.
While
this may seem obvious it usually is very difficult to be able to call an individual function on a this may seem obvious it usually is very difficult to be able to call an individual function on a
typical project. The reason is that the developers often mix concerns, and they end up with a typical project. The reason is that the developers often mix concerns, and they end up with a
piece of code which does everything. It reads the data from XHR, it sorts it and then it piece of code which does everything. It reads the data from XHR, it sorts it and then it
manipulates the DOM. With angular we try to make it easy for you to do the right thing, and so we manipulates the DOM.
With Angular we try to make it easy for you to do the right thing, and so we
provide dependency injection for your XHR (which you can mock out) and we created abstraction which provide dependency injection for your XHR (which you can mock out) and we created abstraction which
allow you to sort your model without having to resort to manipulating the DOM. So that in the end, allow you to sort your model without having to resort to manipulating the DOM. So that in the end,
it is easy to write a sort function which sorts some data, so that your test can create a data set, it is easy to write a sort function which sorts some data, so that your test can create a data set,
apply the function, and assert that the resulting model is in the correct order. The test does not apply the function, and assert that the resulting model is in the correct order. The test does not
have to wait for XHR, or create the right kind of DOM, or assert that your function has mutated the have to wait for XHR, or create the right kind of DOM, or assert that your function has mutated the
DOM in the right way. Angular is written with testability in mind, but it still requires that you DOM in the right way.
do the right thing. We tried to make the right thing easy, but angular is not magic, which means if
you don't follow these, you may very well end up with an untestable application.
## Dependency Inject ## With great power comes great responsibility
Angular is written with testability in mind, but it still requires that you
do the right thing. We tried to make the right thing easy, but Angular is not magic, which means if
you don't follow these guidelines you may very well end up with an untestable application.
## Dependency Injection
There are several ways in which you can get a hold of a dependency: There are several ways in which you can get a hold of a dependency:
1. You could create it using the `new` operator. 1. You could create it using the `new` operator.
2. You could look for it in a well know place, also known as global singleton. 2. You could look for it in a well known place, also known as global singleton.
3. You could ask a registry (also known as service registry) for it. (But how do you get a hold of 3. You could ask a registry (also known as service registry) for it. (But how do you get a hold of
the registry? Must likely by looking it up in a well know place. See #2) the registry? Must likely by looking it up in a well known place. See #2)
4. You could expect that the it be handed to you. 4. You could expect that it be handed to you.
Out of the list above only the last of is testable. Lets look at why: Out of the list above only the last option is testable. Let's look at why:
### Using the `new` operator ### Using the `new` operator
@ -52,10 +64,10 @@ function MyClass() {
} }
</pre> </pre>
The issue becomes, that in tests, we would very much like to instantiate a `MockXHR` which would The issue becomes that in tests, we would very much like to instantiate a `MockXHR` which would
allow us to return fake data and simulate network failures. By calling `new XHR()` we are allow us to return fake data and simulate network failures. By calling `new XHR()` we are
permanently bound to the actual one, and there is no good way to replace it. Yes there is monkey permanently bound to the actual XHR, and there is no good way to replace it. Yes there is monkey
patching, that is a bad idea for many reasons, which is outside the scope of this document. patching. That is a bad idea for many reasons which are outside the scope of this document.
The class above is hard to test since we have to resort to monkey patching: The class above is hard to test since we have to resort to monkey patching:
<pre> <pre>
@ -69,7 +81,7 @@ XHR = oldXHR; // if you forget this bad things will happen
### Global look-up: ### Global look-up:
Another way to approach the problem is look for the service in a well known location. Another way to approach the problem is to look for the service in a well known location.
<pre> <pre>
function MyClass() { function MyClass() {
@ -83,7 +95,7 @@ function MyClass() {
} }
</pre> </pre>
While no new instance of dependency is being created, it is fundamentally the same as `new`, in While no new instance of the dependency is being created, it is fundamentally the same as `new`, in
that there is no good way to intercept the call to `global.xhr` for testing purposes, other then that there is no good way to intercept the call to `global.xhr` for testing purposes, other then
through monkey patching. The basic issue for testing is that global variable needs to be mutated in through monkey patching. The basic issue for testing is that global variable needs to be mutated in
order to replace it with call to a mock method. For further explanation why this is bad see: {@link order to replace it with call to a mock method. For further explanation why this is bad see: {@link
@ -164,7 +176,7 @@ myClass.doWork();
Notice that no global variables were harmed in the writing of this test. Notice that no global variables were harmed in the writing of this test.
Angular comes with {@link di dependency-injection} built in which makes the right thing Angular comes with {@link di dependency injection} built in which makes the right thing
easy to do, but you still need to do it if you wish to take advantage of the testability story. easy to do, but you still need to do it if you wish to take advantage of the testability story.
## Controllers ## Controllers
@ -197,7 +209,7 @@ function PasswordCtrl() {
} }
</pre> </pre>
The code above is problematic from testability, since it requires your test to have the right kind The code above is problematic from a testability point of view, since it requires your test to have the right kind
of DOM present when the code executes. The test would look like this: of DOM present when the code executes. The test would look like this:
<pre> <pre>
@ -233,7 +245,7 @@ function PasswordCtrl($scope) {
} }
</pre> </pre>
and the tests is straight forward and the test is straight forward
<pre> <pre>
var pc = new PasswordCtrl(); var pc = new PasswordCtrl();
@ -245,7 +257,6 @@ expect(span.strength).toEqual('weak');
Notice that the test is not only much shorter but it is easier to follow what is going on. We say Notice that the test is not only much shorter but it is easier to follow what is going on. We say
that such a test tells a story, rather then asserting random bits which don't seem to be related. that such a test tells a story, rather then asserting random bits which don't seem to be related.
## Filters ## Filters
{@link api/ng.$filter Filters} are functions which transform the data into user readable {@link api/ng.$filter Filters} are functions which transform the data into user readable
format. They are important because they remove the formatting responsibility from the application format. They are important because they remove the formatting responsibility from the application
@ -266,16 +277,20 @@ expect(length('abc')).toEqual(3);
## Directives ## Directives
Directives in angular are responsible for updating the DOM when the state of the model changes. Directives in angular are responsible for updating the DOM when the state of the model changes.
## Mocks ## Mocks
oue oue
## Global State Isolation ## Global State Isolation
oue oue
# Preferred way of Testing # Preferred way of Testing
uo uo
## JavaScriptTestDriver ## JavaScriptTestDriver
ou ou
## Jasmine ## Jasmine
ou ou
## Sample project ## Sample project
uoe uoe

View file

@ -47,7 +47,7 @@ is simply handed the `greeter` at runtime.
This is desirable, but it puts the responsibility of getting hold of the dependency onto the This is desirable, but it puts the responsibility of getting hold of the dependency onto the
code responsible for the construction of `SomeClass`. code responsible for the construction of `SomeClass`.
To manage the responsibility of dependency creation, each angular application has an {@link To manage the responsibility of dependency creation, each Angular application has an {@link
api/angular.injector injector}. The injector is a service locator that is responsible for api/angular.injector injector}. The injector is a service locator that is responsible for
construction and lookup of dependencies. construction and lookup of dependencies.
@ -109,7 +109,7 @@ deal with the injector. This setup does not break the Law of Demeter.
How does the injector know what service needs to be injected? How does the injector know what service needs to be injected?
The application developer needs to provide annotation information, that the injector uses in order The application developer needs to provide annotation information that the injector uses in order
to resolve the dependencies. Throughout Angular certain API functions are invoked using the to resolve the dependencies. Throughout Angular certain API functions are invoked using the
injector, as per the API documentation. The injector needs to know what services to inject into injector, as per the API documentation. The injector needs to know what services to inject into
the function. Below are three equivalent ways of annotating your code with service name the function. Below are three equivalent ways of annotating your code with service name
@ -186,14 +186,13 @@ For this reason the third annotation style is provided as well.
Keep in mind that all of the annotation styles are equivalent and can be used anywhere in Angular Keep in mind that all of the annotation styles are equivalent and can be used anywhere in Angular
where injection is supported. where injection is supported.
# Where can I use DI? # Where can I use DI?
DI is pervasive throughout Angular. It is typically used in controllers and factory methods. DI is pervasive throughout Angular. It is typically used in controllers and factory methods.
## DI in controllers ## DI in controllers
Controllers are classes which are responsible for application behavior. Recommended way of Controllers are classes which are responsible for application behavior. The recommended way of
declaring controllers is: declaring controllers is:
<pre> <pre>
@ -211,7 +210,7 @@ declaring controllers is:
## Factory methods ## Factory methods
Factory methods are responsible for creating most objects in Angular. Examples are directives, Factory methods are responsible for creating most objects in Angular. Examples are directives,
services, and filters. The factory methods are register with the module, and the recommended way services, and filters. The factory methods are registered with the module, and the recommended way
of declaring factories is: of declaring factories is:
<pre> <pre>

View file

@ -110,7 +110,7 @@ Compilation of HTML happens in three phases:
## Reasons behind the compile/link separation ## Reasons behind the compile/link separation
At this point you may wonder why the compile process is broken down to a compile and link phase. At this point you may wonder why the compile process is broken down to a compile and link phase.
To understand this, let's look at a real world example with repeater: To understand this, let's look at a real world example with a repeater:
<pre> <pre>
Hello {{user}}, you have these actions: Hello {{user}}, you have these actions:
@ -296,7 +296,7 @@ makes it injectable following all of the rules of injection annotation.
The directive definition object provides instructions to the {@link api/ng.$compile The directive definition object provides instructions to the {@link api/ng.$compile
compiler}. The attributes are: compiler}. The attributes are:
* `name` - Name of the current scope. Optional defaults to the name at registration. * `name` - Name of the current scope. Optional and defaults to the name at registration.
* `priority` - When there are multiple directives defined on a single DOM element, sometimes it * `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 is necessary to specify the order in which the directives are applied. The `priority` is used
@ -310,7 +310,7 @@ compiler}. The attributes are:
* `scope` - If set to: * `scope` - If set to:
* `true` - then a new scope will be created for this directive. If multiple directives on the * `true` - then a new scope will be created for this directive. If multiple directives on the
same element request new scope, only one new scope is created. The new scope rule does not 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. apply for the root of the template since the root of the template always gets a new scope.
* `{}` (object hash) - then a new 'isolate' scope is created. The 'isolate' scope differs from * `{}` (object hash) - then a new 'isolate' scope is created. The 'isolate' scope differs from
@ -474,7 +474,7 @@ compiler linking function will fail to locate the correct elements for linking.
### Post-linking function ### Post-linking function
Executed after the child elements are linked. Safe to do DOM transformation in here. Executed after the child elements are linked. It is safe to do DOM transformation in the post-linking function.
<a name="Attributes"></a> <a name="Attributes"></a>
## Attributes ## Attributes
@ -584,7 +584,7 @@ isolated scope then it will not be able to bind to anything. For this reason the
is a child of the original scope, before the widget created an isolated scope for its local is a child of the original scope, before the widget created an isolated scope for its local
variables. This makes the transcluded and widget isolated scope siblings. variables. This makes the transcluded and widget isolated scope siblings.
This may seem as unexpected complexity, but it gives the widget user and developer the least This may seem to be unexpected complexity, but it gives the widget user and developer the least
surprise. surprise.
Therefore the final directive definition looks something like this: Therefore the final directive definition looks something like this:
@ -609,7 +609,6 @@ can be built.
Following is an example of building a reusable widget. Following is an example of building a reusable widget.
<doc:example module="zippyModule"> <doc:example module="zippyModule">
<doc:source> <doc:source>
<script> <script>

View file

@ -15,10 +15,9 @@ For example, these are all valid expressions in angular:
## Angular Expressions vs. JS Expressions ## Angular Expressions vs. JS Expressions
It might be tempting to think of angular view expressions as JavaScript expressions, but that is It might be tempting to think of Angular view expressions as JavaScript expressions, but that is
not entirely correct, since angular does not use a JavaScript `eval()` to evaluate expressions. not entirely correct, since Angular does not use a JavaScript `eval()` to evaluate expressions.
You can think of angular expressions as JavaScript expressions with following differences You can think of Angular expressions as JavaScript expressions with following differences:
differences:
* **Attribute Evaluation:** evaluation of all properties are against the scope, doing the * **Attribute Evaluation:** evaluation of all properties are against the scope, doing the
evaluation, unlike in JavaScript where the expressions are evaluated against the global evaluation, unlike in JavaScript where the expressions are evaluated against the global
@ -92,9 +91,9 @@ You can try evaluating different expressions here:
# Property Evaluation # Property Evaluation
Evaluation of all properties takes place against a scope. Unlike JavaScript, where names default Evaluation of all properties takes place against a scope. Unlike JavaScript, where names default
to global window properties, angular expressions have to use {@link api/ng.$window to global window properties, Angular expressions have to use {@link api/ng.$window
`$window`} to refer to the global `window` object. For example, if you want to call `alert()`, which is `$window`} to refer to the global `window` object. For example, if you want to call `alert()`, which is
defined on `window`, in an expression must use `$window.alert()`. This is done intentionally to defined on `window`, in an expression you must use `$window.alert()`. This is done intentionally to
prevent accidental access to the global state (a common source of subtle bugs). prevent accidental access to the global state (a common source of subtle bugs).
<doc:example> <doc:example>
@ -148,7 +147,7 @@ Similarly, invoking a function `a.b.c()` on undefined or null simply returns und
## No Control Flow Statements ## No Control Flow Statements
You cannot write a control flow statement in an expression. The reason behind this is core to the You cannot write a control flow statement in an expression. The reason behind this is core to the
angular philosophy that application logic should be in controllers, not in the view. If you need a Angular philosophy that application logic should be in controllers, not in the view. If you need a
conditional, loop, or to throw from a view expression, delegate to a JavaScript method instead. conditional, loop, or to throw from a view expression, delegate to a JavaScript method instead.
@ -179,9 +178,9 @@ You might be wondering, what is the significance of the $ prefix? It is simply a
angular uses, to differentiate its API names from others. If angular didn't use $, then evaluating angular uses, to differentiate its API names from others. If angular didn't use $, then evaluating
`a.length()` would return undefined because neither a nor angular define such a property. `a.length()` would return undefined because neither a nor angular define such a property.
Consider that in a future version of angular we might choose to add a length method, in which case Consider that in a future version of Angular we might choose to add a length method, in which case
the behavior of the expression would change. Worse yet, you the developer could create a length the behavior of the expression would change. Worse yet, you the developer could create a length
property and then we would have a collision. This problem exists because angular augments existing property and then we would have a collision. This problem exists because Angular augments existing
objects with additional behavior. By prefixing its additions with $ we are reserving our namespace objects with additional behavior. By prefixing its additions with $ we are reserving our namespace
so that angular developers and developers who use angular can develop in harmony without collisions. so that angular developers and developers who use Angular can develop in harmony without collisions.

View file

@ -12,9 +12,9 @@ Server-side validation is still necessary for a secure application.
# Simple form # Simple form
The key directive in understanding two-way data-binding is {@link api/ng.directive:ngModel ngModel}. The key directive in understanding two-way data-binding is {@link api/ng.directive:ngModel ngModel}.
The `ngModel` directive provides the two-way data-binding by synchronizing the model to the view, as well as view to the model. The `ngModel` directive provides the two-way data-binding by synchronizing the model to the view, as well as view to the model.
In addition it provides {@link api/ng.directive:ngModel.NgModelController API} for other directives to augment its behavior. In addition it provides an {@link api/ng.directive:ngModel.NgModelController API} for other directives to augment its behavior.
<doc:example> <doc:example>
<doc:source> <doc:source>
@ -63,7 +63,7 @@ To allow styling of form as well as controls, `ngModel` add these CSS classes:
- `ng-pristine` - `ng-pristine`
- `ng-dirty` - `ng-dirty`
Following example uses the CSS to display validity of each form control. The following example uses the CSS to display validity of each form control.
In the example both `user.name` and `user.email` are required, but are rendered with red background only when they are dirty. In the example both `user.name` and `user.email` are required, but are rendered with red background only when they are dirty.
This ensures that the user is not distracted with an error until after interacting with the control, and failing to satisfy its validity. This ensures that the user is not distracted with an error until after interacting with the control, and failing to satisfy its validity.
@ -190,18 +190,18 @@ The validation can occur in two places:
* **View to Model update** - * **View to Model update** -
In a similar way, whenever a user interacts with a control it calls {@link api/ng.directive:ngModel.NgModelController#$setViewValue NgModelController#$setViewValue}. In a similar way, whenever a user interacts with a control it calls {@link api/ng.directive:ngModel.NgModelController#$setViewValue NgModelController#$setViewValue}.
This in turn pipelines all functions in {@link api/ng.directive:ngModel.NgModelController#$parsers NgModelController#$parsers} array, so that each of these functions has an opportunity to convert the value and change validity state of the form control through {@link api/ng.directive:ngModel.NgModelController#$setValidity NgModelController#$setValidity}. This in turn pipelines all functions in the {@link api/ng.directive:ngModel.NgModelController#$parsers NgModelController#$parsers} array, so that each of these functions has an opportunity to convert the value and change validity state of the form control through {@link api/ng.directive:ngModel.NgModelController#$setValidity NgModelController#$setValidity}.
In the following example we create two directives. In the following example we create two directives.
* The first one is `integer` and it validates whether the input is a valid integer. * The first one is `integer` and it validates whether the input is a valid integer.
For example `1.23` is an invalid value, since it contains a fraction. For example `1.23` is an invalid value, since it contains a fraction.
Note, that we unshift the array instead of pushing. Note that we unshift the array instead of pushing.
This is because we want to be first parser and consume the control string value, as we need to execute the validation function before a conversion to number occurs. This is because we want to be first parser and consume the control string value, as we need to execute the validation function before a conversion to number occurs.
* The second directive is a `smart-float`. * The second directive is a `smart-float`.
It parses both `1.2` and `1,2` into a valid float number `1.2`. It parses both `1.2` and `1,2` into a valid float number `1.2`.
Note that, we can't use input type `number` here as HTML5 browsers would not allow the user to type what it would consider an invalid number such as `1,2`. Note that we can't use input type `number` here as HTML5 browsers would not allow the user to type what it would consider an invalid number such as `1,2`.
<doc:example module="form-example1"> <doc:example module="form-example1">
@ -272,7 +272,7 @@ In the following example we create two directives.
</doc:example> </doc:example>
# Implementing custom form control (using `ngModel`) # Implementing custom form controls (using `ngModel`)
Angular implements all of the basic HTML form controls ({@link api/ng.directive:input input}, {@link api/ng.directive:select select}, {@link api/ng.directive:textarea textarea}), which should be sufficient for most cases. Angular implements all of the basic HTML form controls ({@link api/ng.directive:input input}, {@link api/ng.directive:select select}, {@link api/ng.directive:textarea textarea}), which should be sufficient for most cases.
However, if you need more flexibility, you can write your own form control as a directive. However, if you need more flexibility, you can write your own form control as a directive.

View file

@ -5,12 +5,12 @@
# Overview # Overview
This document describes the Internet Explorer (IE) idiosyncrasies when dealing with custom HTML This document describes the Internet Explorer (IE) idiosyncrasies when dealing with custom HTML
attributes and tags. Read this document if you are planning on deploying your angular application attributes and tags. Read this document if you are planning on deploying your Angular application
on IE v8.0 or earlier. on IE v8.0 or earlier.
# Short Version # Short Version
To make your angular application work on IE please make sure that: To make your Angular application work on IE please make sure that:
1. You polyfill JSON.stringify if necessary (IE7 will need this). You can use 1. You polyfill JSON.stringify if necessary (IE7 will need this). You can use
[JSON2](https://github.com/douglascrockford/JSON-js) or [JSON2](https://github.com/douglascrockford/JSON-js) or

View file

@ -6,7 +6,7 @@ Angular is pure client-side technology, written entirely in JavaScript. It works
long-established technologies of the web (HTML, CSS, and JavaScript) to make the development of long-established technologies of the web (HTML, CSS, and JavaScript) to make the development of
web apps easier and faster than ever before. web apps easier and faster than ever before.
One important way that angular simplifies web development is by increasing the level of abstraction One important way that Angular simplifies web development is by increasing the level of abstraction
between the developer and most low-level web app development tasks. Angular automatically takes between the developer and most low-level web app development tasks. Angular automatically takes
care of many of these tasks, including: care of many of these tasks, including:
@ -14,10 +14,10 @@ care of many of these tasks, including:
* Setting Up Listeners and Notifiers * Setting Up Listeners and Notifiers
* Input Validation * Input Validation
Because angular handles much of the work involved in these tasks, developers can concentrate more Because Angular handles much of the work involved in these tasks, developers can concentrate more
on application logic and less on repetitive, error-prone, lower-level coding. on application logic and less on repetitive, error-prone, lower-level coding.
At the same time that angular simplifies the development of web apps, it brings relatively At the same time that Angular simplifies the development of web apps, it brings relatively
sophisticated techniques to the client-side, including: sophisticated techniques to the client-side, including:
* Separation of data, application logic, and presentation components * Separation of data, application logic, and presentation components
@ -31,12 +31,12 @@ These techniques have been for the most part absent from the client-side for far
## Single-page / Round-trip Applications ## Single-page / Round-trip Applications
You can use angular to develop both single-page and round-trip apps, but angular is designed You can use Angular to develop both single-page and round-trip apps, but Angular is designed
primarily for developing single-page apps. Angular supports browser history, forward and back primarily for developing single-page apps. Angular supports browser history, forward and back
buttons, and bookmarking in single-page apps. buttons, and bookmarking in single-page apps.
You normally wouldn't want to load angular with every page change, as would be the case with using You normally wouldn't want to load Angular with every page change, as would be the case with using
angular in a round-trip app. However, it would make sense to do so if you were adding a subset of Angular in a round-trip app. However, it would make sense to do so if you were adding a subset of
angular's features (for example, templates to leverage angular's data-binding feature) to an Angular's features (for example, templates to leverage angular's data-binding feature) to an
existing round-trip app. You might follow this course of action if you were migrating an older app existing round-trip app. You might follow this course of action if you were migrating an older app
to a single-page angular app. to a single-page Angular app.

View file

@ -194,7 +194,7 @@ and thus script loaders can take advantage of this property and parallelize the
# Unit Testing # Unit Testing
In its simplest form a unit-test is a way of instantiating a subset of the application in test and In its simplest form a unit test is a way of instantiating a subset of the application in test and
then applying a stimulus to it. It is important to realize that each module can only be loaded then applying a stimulus to it. It is important to realize that each module can only be loaded
once per injector. Typically an app has only one injector. But in tests, each test has its own once per injector. Typically an app has only one injector. But in tests, each test has its own
injector, which means that the modules are loaded multiple times per VM. Properly structured injector, which means that the modules are loaded multiple times per VM. Properly structured
@ -222,8 +222,8 @@ In all of these examples we are going to assume this module definition:
Let's write some tests: Let's write some tests:
<pre> <pre>
describe('myApp', function() { describe('myApp', function() {
// load the application relevant modules then load a special // load the relevant application modules then load a special
// test module which overrides the $window with mock version, // test module which overrides the $window with a mock version,
// so that calling window.alert() will not block the test // so that calling window.alert() will not block the test
// runner with a real alert box. This is an example of overriding // runner with a real alert box. This is an example of overriding
// configuration information in tests. // configuration information in tests.

View file

@ -16,7 +16,7 @@ declarative language for static documents. It does not contain much in the way o
applications, and as a result building web applications is an exercise in *what do I have to do, so applications, and as a result building web applications is an exercise in *what do I have to do, so
that I trick the browser in to doing what I want.* that I trick the browser in to doing what I want.*
Impedance mismatch between dynamic applications and static documents are often solved as: The impedance mismatch between dynamic applications and static documents is often solved as:
* **library** - a collection of functions which are useful when writing web apps. Your code is * **library** - a collection of functions which are useful when writing web apps. Your code is
in charge and it calls into the library when it sees fit. E.g., `jQuery`. in charge and it calls into the library when it sees fit. E.g., `jQuery`.
@ -111,7 +111,7 @@ concepts which the application developer may face:
Try out the Live Preview above, and then let's walk through the example and describe what's going Try out the Live Preview above, and then let's walk through the example and describe what's going
on. on.
In the `<html>` tag, we specify that it is an angular In the `<html>` tag, we specify that it is an Angular
application with the `ng-app` directive. The `ng-app` will cause Angular to {@link application with the `ng-app` directive. The `ng-app` will cause Angular to {@link
bootstrap auto initialize} your application. bootstrap auto initialize} your application.
@ -121,7 +121,7 @@ We load Angular using the `<script>` tag:
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/?.?.?/angular.min.js"></script> <script src="https://ajax.googleapis.com/ajax/libs/angularjs/?.?.?/angular.min.js"></script>
From the `ng-model` attribute of the `<input>` tags, angular automatically sets up two-way data From the `ng-model` attribute of the `<input>` tags, Angular automatically sets up two-way data
binding, and we also demonstrate some easy input validation: binding, and we also demonstrate some easy input validation:
Quantity: <input type="integer" min="0" ng-model="qty" required > Quantity: <input type="integer" min="0" ng-model="qty" required >
@ -129,7 +129,7 @@ binding, and we also demonstrate some easy input validation:
These input widgets look normal enough, but consider these points: These input widgets look normal enough, but consider these points:
* When this page loaded, angular bound the names of the input widgets (`qty` and `cost`) to * When this page loaded, Angular bound the names of the input widgets (`qty` and `cost`) to
variables of the same name. Think of those variables as the "Model" component of the variables of the same name. Think of those variables as the "Model" component of the
Model-View-Controller design pattern. Model-View-Controller design pattern.
* Note that the HTML widget {@link api/ng.directive:input input} * Note that the HTML widget {@link api/ng.directive:input input}
@ -193,7 +193,7 @@ Angular frees you from the following pain:
code. Angular eliminates almost all of this boilerplate, leaving code that describes the code. Angular eliminates almost all of this boilerplate, leaving code that describes the
overall flow of the application rather than all of the implementation details. overall flow of the application rather than all of the implementation details.
* **Writing tons of initialization code just to get started:** Typically you need to write a lot * **Writing tons of initialization code just to get started:** Typically you need to write a lot
of plumbing just to get a basic "Hello World" AJAX app working. With angular you can bootstrap of plumbing just to get a basic "Hello World" AJAX app working. With Angular you can bootstrap
your app easily using services, which are auto-injected into your application in a {@link your app easily using services, which are auto-injected into your application in a {@link
http://code.google.com/p/google-guice/ Guice}-like dependency-injection style. This allows you http://code.google.com/p/google-guice/ Guice}-like dependency-injection style. This allows you
to get started developing features quickly. As a bonus, you get full control over the to get started developing features quickly. As a bonus, you get full control over the

View file

@ -81,7 +81,7 @@ Logically the rendering of `{{greeting}}` involves:
You can think of the scope and its properties as the data which is used to render the view. The You can think of the scope and its properties as the data which is used to render the view. The
scope is the single source-of-truth for all things view related. scope is the single source-of-truth for all things view related.
From testability, the separation of the controller and the view is desirable, because it allows us From a testability point of view, the separation of the controller and the view is desirable, because it allows us
to test the behavior without being distracted by the rendering details. to test the behavior without being distracted by the rendering details.
<pre> <pre>
@ -151,7 +151,7 @@ This example illustrates scopes in application, and prototypical inheritance of
</file> </file>
</example> </example>
Notice that the Angular automatically places `ng-scope` class on elements where scopes are Notice that Angular automatically places `ng-scope` class on elements where scopes are
attached. The `<style>` definition in this example highlights in red the new scope locations. The attached. The `<style>` definition in this example highlights in red the new scope locations. The
child scopes are necessary because the repeater evaluates `{{employee.name}}` expression, but child scopes are necessary because the repeater evaluates `{{employee.name}}` expression, but
depending on which scope the expression is evaluated it produces different result. Similarly the depending on which scope the expression is evaluated it produces different result. Similarly the
@ -166,7 +166,7 @@ purposes. (It is unlikely that one would need to retrieve scopes in this way ins
application.) The location where the root scope is attached to the DOM is defined by the location application.) The location where the root scope is attached to the DOM is defined by the location
of {@link api/ng.directive:ngApp `ng-app`} directive. Typically of {@link api/ng.directive:ngApp `ng-app`} directive. Typically
`ng-app` is placed an the `<html>` element, but it can be placed on other elements as well, if, `ng-app` is placed an the `<html>` element, but it can be placed on other elements as well, if,
for example, only a portion of the view needs to be controlled by angular. for example, only a portion of the view needs to be controlled by Angular.
To examine the scope in the debugger: To examine the scope in the debugger:
@ -218,7 +218,7 @@ api/ng.$rootScope.Scope#$emit emitted} to scope parents.
## Scope Life Cycle ## Scope Life Cycle
The normal flow of browser receiving an event is that it executes a corresponding JavaScript The normal flow of a browser receiving an event is that it executes a corresponding JavaScript
callback. Once the callback completes the browser re-renders the DOM and returns to waiting for callback. Once the callback completes the browser re-renders the DOM and returns to waiting for
more events. more events.

View file

@ -5,8 +5,8 @@
<ul doc-tutorial-nav="1"></ul> <ul doc-tutorial-nav="1"></ul>
In order to illustrate how angular enhances standard HTML, you will create a purely *static* HTML In order to illustrate how Angular enhances standard HTML, you will create a purely *static* HTML
page and then examine how we can turn this HTML code into a template that angular will use to page and then examine how we can turn this HTML code into a template that Angular will use to
dynamically display the same result with any set of data. dynamically display the same result with any set of data.
In this step you will add some basic information about two cell phones to an HTML page. In this step you will add some basic information about two cell phones to an HTML page.

View file

@ -46,7 +46,7 @@ history (back and forward navigation) and bookmarks.
### A Note About DI, Injector and Providers ### A Note About DI, Injector and Providers
As you {@link tutorial/step_05 noticed}, {@link guide/di dependency injection} is the core feature of As you {@link tutorial/step_05 noticed}, {@link guide/di dependency injection} (DI) is the core feature of
AngularJS, so it's important for you to understand a thing or two about how it works. AngularJS, so it's important for you to understand a thing or two about how it works.
When the application bootstraps, Angular creates an injector that will be used for all DI stuff in When the application bootstraps, Angular creates an injector that will be used for all DI stuff in