Rewrite of the overview section of the dev guide

This commit is contained in:
Kenneth R. Culp 2011-02-09 11:07:42 -08:00 committed by Igor Minar
parent 55ce859998
commit fe743e31f8
5 changed files with 437 additions and 268 deletions

View file

@ -1,126 +1,153 @@
@workInProgress
@ngdoc overview
@name Developer Guide: Overview
@description
# What is angular?
Angular teaches your old browser new tricks. It is what HTML would have been if it had been
designed for building web applications.
Take a simple example of user input as shown below. If you were using just HTML and JavaScript to
implement this form, you would need to define listeners, DOM updates, and complex input validators
in order to update and format the result. In angular you can achieve the effect with zero lines
of JavaScript code using a declarative approach. Click on the source tab of the example below to
view the angular implementation of this form.
* <a href="#H1_1">What Is Angular?</a>
* <a href="#H1_3">The Angular Philosophy</a>
* <a href="#H1_2">Anatomy Of An Angular App</a>
* <a href="#H1_4">Why You Want Angular</a>
* <a href="#H1_5">Angular's Ancestors</a>
* <a href="#H1_6">Watch a Presentation About Angular</a>
<a name="H1_1"></a>
# What Is Angular?
The short answer: angular is a new, powerful, client-side technology that makes it much easier for
you to create dynamic web sites and complex web apps, all without leaving the comfort of your HTML
/ JavaScript home.
The long answer: it kind of depends on where you're coming from...
* If you're a web designer, you might perceive angular to be a sweet {@link guide.template
templating} system, that doesn't get in your way and provides you with lots of nice built-ins that
make it easier to do what you want to do.
* If you're a web developer, you might be thrilled that angular functions as an excellent web
framework, one that assists you all the way through the development cycle.
* If you want to go deeper, you can immerse yourself in angular's extensible HTML {@link
guide.compiler compiler} that runs in your browser. This compiler teaches your browser new tricks.
So then, angular's not just a templating system, but you can create fantastic templates with it;
angular's not just a web framework, but it has a very nice one; and angular's not just an
extensible HTML compiler, but it has one of those too. Let's put it this way: angular includes
these parts along with some others; it evolved naturally from earlier occurrences of these forms;
and thus angular is something far greater than the sum of its parts. It sounds like... it's alive!
## An Intro By Way of Example
Let's say that you are a web designer, and you've spent many thous — erm, hundreds of hours
designing web sites. But at this point, the thought of doing DOM updates, writing listeners, and
writing input validators, all to do something as simple as implementing a form!? You either don't
want to go there in the first place or you've been there and the thrill is gone.
You could even be muttering to yourself as you hack another callback, "This is like building my own
bike from scratch every time I want to ride to the store." But let's say a clever friend, who keeps
tabs on these sorts of things, told you to check out angular.
So now here you are checking out angular, and here is a simple example. Note that it features only
the templating aspect of angular, but this should suffice for now to quickly demonstrates how much
easier life can be with angular:
<doc:example>
<doc:source>
QTY: <input name="qty" value="1" ng:validate="integer:0" ng:required/>
*
Cost: <input name="cost" value="19.95" ng:validate="number" ng:required/>
=
{{qty * cost | currency}}
</doc:source>
<doc:scenario>
it('should show of angular binding', function(){
expect(binding('qty * cost')).toEqual('$19.95');
input('qty').enter('2');
input('cost').enter('5.00');
expect(binding('qty * cost')).toEqual('$10.00');
});
</doc:scenario>
<doc:source>
<h2>Bigg Bike Shop</h2>
<hr>
<b>Invoice:</b>
<br/>
<br/>
<table>
<tr><td> </td><td> </td>
<tr><td>Quantity</td><td>Cost</td></tr>
<tr>
<td><input name="qty" value="1" ng:validate="integer:0" ng:required/></td>
<td><input name="cost" value="199.95" ng:validate="number" ng:required/></td>
</tr>
</table>
<hr>
<b>Total:</b> {{qty * cost | currency}}
<hr>
</doc:source>
<!--
<doc:scenario>
it('should show of angular binding', function(){
expect(binding('qty * cost')).toEqual('$19.95');
input('qty').enter('2');
input('cost').enter('5.00');
expect(binding('qty * cost')).toEqual('$10.00');
});
</doc:scenario>
-->
</doc:example>
Angular is to AJAX apps as Ruby on Rails is to round trip apps.
Go ahead, try out the Live Preview above. "Well I _declare_! It's a fully functioning form, with
an instantly updating display, and input validation." Speaking of being declarative, let's walk
through the example and look at the angular-related lines to see what's going on around here.
# Angular frees you from:
* **Registering callbacks:** Registering callbacks clutters your code, and it makes it hard to see
the forest from the trees. Removing common boilerplate code such as callbacks is advantageous
because it leaves the JavaScript with a more succinct version of your code, better describing
what your application does.
* **Manipulating HTML DOM programatically:** Manipulating HTML DOM is a cornerstone of AJAX
applications, but it is very cumbersome and error-prone. By declaratively describing how the UI
should change as your application state changes, you are freed from low level DOM manipulation
activities. Most applications written with angular never have to programatically manipulate
the DOM.
* **Marshaling data to and from the UI:** CRUD operations make up the majority of most AJAX
applications. The flow of marshaling data from the server to an internal object to a HTML form,
validating the form, displaying validation errors, returning to an internal model and then back
to the server creates a lot of boilerplate code. angular eliminates almost all of this
boilerplate. leaving code that is richer and describes the overall flow of the application
rather than implementation details.
* **Writing tons of initialization code just to get started:** Typically you need to write a lot
of plumbing and initialization code 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 GUICE-like dependency-injection style. This allows you to get started
developing features quickly. As a bonus, you get full control over the initialization process
in automated tests.
In line __2__ of the example, we let the browswer know about the angular namespace:
2 <html xmlns:ng="http://angularjs.org">
This ensures angular runs nicely in all major browsers.
In line __3__ we do two angular setup tasks inside a `<script>` tag:
1. We pull in `angular.js`.
2. The angular {@link angular.directive.ng:autobind ng:autobind} directive tells angular to {@link
guide.compiler compile} and manage the whole HTML document.
3 <script src="file:///Users/krculp/angular.js/build/angular.min.js" ng:autobind></script>
Lines __14__ and __15__ set up one side of angular's very cool two-way data binding, as well as
demonstrate some easy input validation:
14 Quantity: <input name="qty" value="1" ng:validate="integer:0" ng:required/>
15 Cost: <input name="cost" value="199.95" ng:validate="number" ng:required/>
These input widgets look normal enough, but consider these points:
* Remember the `ng:autobind` directive from line 3? 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" part of the Model-View-Controller design pattern.
* Note the angular directives, {@link angular.widget.@ng:validate ng:validate} and {@link
ngular.widget.@ng:required ng:required}. You may have noticed that when you enter invalid data or
leave the the input fields blank, the borders turn a plainly irritated red color, and the display
value disappears. These `ng:` directives make it easier to implement field validators than coding
them in JavaScript, no? Yes.
And finally, the mysterious line #__19__:
19 Total: {{qty * cost | currency}}
What's with the curly braces? Those curly braces are your friend. This notation, `{{ _expression_
}}`, is a bit of built-in angular {@link angular.markup markup}, a shortcut that you use to display
data. The expression within curly braces gets transformed by the angular compiler into an angular
directive ({@link angular.directive.ng:bind ng:bind}). The expression itself can be a combination
of both an expression and a {@link angular.filter filter}: `{{ expression | filter }}`.
In our example above, we're saying, "Bind the data we got from the input widgets to the display,
multiply them together, and format the resulting number into something that looks like money."
# angular is/has:
* **An HTML Compiler:** angular is an HTML compiler in the browser. It allows you to give meaning
to any HTML element, attribute, or text and create new primitives as building blocks for your
application.
* **Declarative:** Declarative means that you describe what the page looks like rather than
instructing how to draw the page. HTML is great at declaring static documents. Angular extends
the declarative nature of HTML beyond static documents to define dynamic applications.
* **Declarative Templates:** In angular, you write HTML to declare the view and UI templates for
your application. You can express many common application constructs without using any
JavaScript at all.
* **Bidirectional Data Binding:** Allows your application to have a single source of truth
(your model), where the HTML is a projection of the internal state of your application, which
you can provide to the user in a declarative way.
* **Built-in Services:** angular provides many standard AJAX operations to get you going quickly,
and dependency-injection allows you to swap them out as needed. Common services include:
Dependency Inject, History Management, URL Router, AJAX/XHR requests, and data caching,
to name a few.
* **Very testable:** Testing difficulty is dramatically affected by the way you structure your
code. With angular, testability is baked in.
<a name="H1_3"></a>
# The Angular Philosophy
# angular is NOT a:
* **Library:** You don't call its functions.
* **Framework:** It does not call your functions.
* **DOM Manipulation Library:** It does not provide a way to manipulate DOM, but does provide
primitives to create UI projections of your data.
* **Widget Library:** There are lots of existing widget libraries that you can integrate with
angular.
Angular is built around the belief that declarative code is better than imperative when it comes to
building UIs and wiring software components together, while imperative code is clearly the way to
go for expressing business logic.
# Not just another templating system
At the highest level, angular looks like a just another templating system, but there are few
important reasons why angular is different and makes it a very good fit for application
development.
Angular:
* **Uses HTML/CSS syntax:** This makes it easy to read and can be edited with existing HTML/CSS
authoring tools.
* **Extends HTML vocabulary:** Angular allows you to create new HTML tags, which expand into
dynamic UI components.
* **Executes in the browser:** Removes the round trip to the server for many operations and
creates instant feedback for users.
* **Bidirectional data binding:** The model is the single source of truth. Programmatic changes
to the model are automatically reflected in the view. Any changes by the user to the view are
automatically reflected in the model.
* **Services:** These allow for a reusable way of injecting dependencies into an application.
* **MVC:** Clean separation between model-view-controller, which aids in understanding,
maintenance, and testing of large systems.
# The angular philosophy
Angular is built around the belief that declarative code is preferred over imperative when it
comes to building UIs and connecting the pieces together.
As an example, if you wanted to add a new label to your application, you could do so by simply
adding text to the HTML template, saving the code, and refreshing your browser:
Not to put too fine a point on it, but if you wanted to add a new label to your application, you
could do it by simply adding text to the HTML template, saving the code, and refreshing your
browser (this here is declarative):
<pre>
<span class="label">Hello</span>
</pre>
In programmatic systems you would have to write and run code like this:
Or, as In programmatic systems (like {@link http://code.google.com/webtoolkit/ GWT}), you would
have to write the code and then run the code like this:
<pre>
var label = new Label();
@ -129,38 +156,182 @@ label.setClass('label');
parent.addChild(label);
</pre>
## Benefits:
That looks like, let's see, do some math, factor out the `<pre>`s, carry the one, ummm... a little
bit of markup versus four times as much code.
* Compile-free: Change your template and logic code and reload the browser to see it run
immediately. In contrast, programmatic serverside views often need to be compiled and executed
to be viewed, which takes time. This dramatically increases the speed of your development cycle.
* Declarative templates are easier to understand and change than programmatic instructions.
* Declarative templates can be edited in existing HTML editors such as DreamWeaver, Eclipse,
TextMate, Vim, etc.
* Declarative templates can be edited by web designers without the need to work with web
developers.
More Angular Philosophy:
HTML is missing certain features, which angular adds via its compiler, thereby "teaching" the
browser these new tricks:
* It is a very good idea to decouple DOM manipulation from app logic. This dramatically improves
the testability of the code.
* It is a really, _really_ good idea to regard app testing as equal in importance to app writing.
Testing difficulty is dramatically affected by the way the code is structured.
* It is an excellent idea to decouple the client side of an app from the server side. This allows
development work to progress in parallel, and allows for reuse of both sides.
* It is very helpful indeed if the framework guides developers through the entire journey of
building an app: from designing the UI, through writing the business logic, to testing.
* It is always good to make common tasks trivial and difficult tasks possible.
* Dynamic behavior
* Componentizing HTML snippets into reusable components
* Dynamically include other HTML templates
* Two-way data binding
* Rich validation in forms
* Model-View-Controller modularization
Now that we're homing in on what angular is, perhaps now would be a good time to list a few things
what angular isn't:
# Watch a presentation about angular
* It's not a Library. You don't just call its functions, although it does provide you with some
utility APIs.
* It's not a DOM Manipulation Library. angular uses jQuery to manipulate the DOM behind the scenes,
rather than give you functions to manipulate the DOM with yourself.
* It's not a Widget Library. There are lots of existing widget libraries that you can integrate
with angular.
* It's not "Just Another Templating System". A part of angular is a templating system. The
templating subsystem of angular is different from the traditional approach for these reasons:
* It Uses HTML/CSS syntax: This makes it easy to read and can be edited with existing HTML/CSS
authoring tools.
* It Extends HTML vocabulary: Angular allows you to create new HTML tags, which expand into
dynamic UI components.
* It Executes in the browser: Removes the round trip to the server for many operations and
creates instant feedback for users as well as developers.
* It Has Bidirectional data binding: The model is the single source of truth. Programmatic
changes to the model are automatically reflected in the view. Any changes by the user to the view
are automatically reflected in the model.
<a name="H1_2"></a>
# Anatomy Of An Angular App
This section describes the parts of an angular app in more detail.
## Templates
{@link guide.template Templates} are the part of angular that makes it easy and fun to create the
UI for your web apps. With angular's templates you can create a dynamic UI using only HTML and
CSS, but now you can add your own elements, attributes, and markup. The angular compiler reads the
"angularized" HTML when your page loads, and follows the instructions in there to generate a
dynamic page for you. This is the View part of MVC. "But wait there's more": since the compiler is
extensible, you can build your own declarative language on top of HTML!
## Application Logic and Behavior
Application Logic and Behavior, which you define in JavaScript, is the C in MVC. With angular you
write the logic (the controllers) for your app, but because angular takes care of reflecting the
state of the model in the view, you don't have to write listeners or DOM manipulators. This feature
makes your application logic very easy to write, test, maintain, and understand.
## Data
In an angular app, all of your data is referenced from inside of a {@link angular.scope scope}.
The scope is the data Model, the M in the MVC pattern. A scope is a JavaScript object that has
watcher functions that keep tabs on the data that is referenced from that scope. The data could be
one or more Javascript objects, arrays, or primitives, it doesn't matter. What matters is that
these are all referenced by the scope.
This "scope thing" is how angular takes care of keeping your data model and your UI in sync.
Whenever something occurs to change the state of the scope, angular immediately reflects that
change in the UI, and vice versa.
In addition to the three components described above (the MVC bits), angular comes with a set of
{@link angular.service Services} that are very helpful for building web apps. The services include
the following features:
* You can extend and add application-specific behavior to services.
* Services include Dependency-Injection, XHR, caching, URL routing, and browser abstraction.
The following illustration shows the parts of an angular application and how they work together:
<img class="left" src="img/angular_parts.png" border="0" />
<a name="H1_4"></a>
# Why You Want Angular
Angular frees you from the following pain:
* **Registering callbacks:** Registering callbacks clutters your code, making it hard to see the
forest for the trees. Removing common boilerplate code such as callbacks is a good thing. It vastly
reduces the amount of JavaScript coding _you_ have to do, and it makes it easier to see what your
application does.
* **Manipulating HTML DOM programatically:** Manipulating HTML DOM is a cornerstone of AJAX
applications, but it's cumbersome and error-prone. By declaratively describing how the UI should
change as your application state changes, you are freed from low level DOM manipulation tasks. Most
applications written with angular never have to programatically manipulate the DOM, although you
can if you want to, knock yourself out.
* **Marshaling data to and from the UI:** CRUD operations make up the majority of AJAX
applications. The flow of marshaling data from the server to an internal object to an HTML form,
allowing users to modify the form, validating the form, displaying validation errors, returning to
an internal model, and then back to the server (gah!) creates a lot of boilerplate 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.
* **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 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 to
get started developing features quickly. As a bonus, you get full control over the initialization
process in automated tests.
<a name="H1_5"></a>
# Angular's Ancestors
Where does angular come from? What events led to the inevitability of the appearance of something
like angular?
## First There Was HTML
HTML was initially designed long, long ago, in the great year of 1989, with the intention to create
a markup language for sharing scientific documents over the network. Yes, yes, certainly there was
SGML even before that, but it was so difficult that even esteemed scientists balked at using it.
Thankfully, Tim Berners-Lee saved all of us from that pain with his much friendlier HTML.
`<HTML><BODY>Thank You, TB-L!</BODY></HTML>`.
## Then There Was JavaScript
Fast forward to 1995: JavaScript was invented. This was done with the best of intentions! But in
practice it initially served mainly to annoy Internet users with cheap effects that "enhanced"
static HTML documents.
Fast forward to the mid 2000s, when a new breed of back-then-considered-rich web applications
started to appear on the web. These were built with HTML, JavaScript, and CSS, and featured less
annoying and more impressive effects. Can you recall the first time you saw apps like Gmail, or
Google Maps, and you couldn't believe everything that was going on in the browser?
## And JavaScript Prevailed
As of this writing, in 2011, people are building still richer and more interactive web applications
that often rival their desktop counterparts. And yet they are essentially still working with
technology and programming primitives that were used decades ago for the creation of static
documents with cheap graphic effects. At the same time, the web is HUGE now, and we
can't just abandon the technologies it was built with. Applets, Flash and Silverlight tried it, and
in some ways succeeded. Yet many would argue that in reality they failed, because they tried to
work _around_ the web instead of working _with_ it.
## And Then There Was Angular
Angular recognizes the strengths of the existing "static" web technologies, as well as their
deficiencies. At the same time, angular is learning from the failures of other technologies that
tried, or are trying, to work around the web.
For these reasons angular plays to the strengths of established web technologies, instead of
bypassing them. Angular sets out the goal of increasing the abstraction and programming primitives
that developers use to build web applications, so as to better reflect the needs of modern web
applications and their developers.
<a name="H1_6"></a>
# Watch a Presentation About Angular
Here is an early presentation on angular, but note that substantial development has occurred since
the talk was given in July of 2010.
<object width="480" height="385">
<param name="movie" value="http://www.youtube.com/v/elvcgVSynRg&amp;hl=en_US&amp;fs=1"></param>
<param name="allowFullScreen" value="true"></param>
<param name="allowscriptaccess" value="always"></param>
<embed src="http://www.youtube.com/v/elvcgVSynRg&amp;hl=en_US&amp;fs=1"
type="application/x-shockwave-flash" allowscriptaccess="always"
allowfullscreen="true" width="480" height="385"></embed>
<param name="movie" value="http://www.youtube.com/v/elvcgVSynRg&amp;hl=en_US&amp;fs=1"></param>
<param name="allowFullScreen" value="true"></param>
<param name="allowscriptaccess" value="always"></param>
<embed src="http://www.youtube.com/v/elvcgVSynRg&amp;hl=en_US&amp;fs=1"
type="application/x-shockwave-flash" allowscriptaccess="always"
allowfullscreen="true" width="480" height="385"></embed>
</object>
{@link https://docs.google.com/present/edit?id=0Abz6S2TvsDWSZDQ0OWdjaF8yNTRnODczazdmZg&hl=en&authkey=CO-b7oID Presentation}
{@link
https://docs.google.com/present/edit?id=0Abz6S2TvsDWSZDQ0OWdjaF8yNTRnODczazdmZg&hl=en&authkey=CO-b7oID
Presentation}
|
{@link https://docs.google.com/document/edit?id=1ZHVhqC0apbzPRQcgnb1Ye-bAUbNJ-IlFMyPBPCZ2cYU&hl=en&authkey=CInnwLYO Source}
{@link
https://docs.google.com/document/edit?id=1ZHVhqC0apbzPRQcgnb1Ye-bAUbNJ-IlFMyPBPCZ2cYU&hl=en&authkey=CInnwLYO
Source}

Binary file not shown.

Before

Width:  |  Height:  |  Size: 53 KiB

After

Width:  |  Height:  |  Size: 57 KiB

File diff suppressed because it is too large Load diff