Compare commits

...

1047 Commits

Author SHA1 Message Date
Martin Probst 3ccec13aa7 feat(Angular.js): add externs file for Closure Compiler
This adds an (incomplete) externs file for use with the Closure Compiler. Users
can pass this as -extern to the compiler pass to get type checking and protect
their AngularJS use against property renaming in advanced compilation mode.
2013-10-30 14:59:33 -07:00
Daniel Lamb 43d49013d1 revert(validate-commit-msg): fix incorrect comment
Revert d5b62465f0 since it was not valid.

Closes #3952
2013-10-21 16:27:04 +01:00
Pete Bacon Darwin 116fac0562 docs(guide/controller): improve guidance and examples
Remove mention of global controller functions
Convert larger examples to runnable demos
Remove mention of pre-1.0 controllers, in particular discussion of
controller inheritance.

TODO: Probably could do with updating to explain the "controller as" syntax
at some point.

Closes: #4373
2013-10-11 12:59:39 +01:00
Felix c3024254b6 docs(guide/controller): use .controller syntax
Use the recommended `module.controller` syntax rather than global
functions to define controllers in the examples.
2013-10-11 12:58:22 +01:00
Pete Bacon Darwin 770353df19 docs($provide): improve docs and examples further
Improve the "tracking" service example by adding a configuration option.
Get better formatting of the generated code samples using <pre> tags.
Move the detailed explanations into each function's documentation block.
Improve the overview and list the constituent functions by significance.

Closes #4302
2013-10-10 18:22:52 +01:00
Tim Ruffles 85b7d24357 docs($provide): improve examples and explanations
$provide's example seems awkward. Replace with more real-world example,
using an injected service, where the service defined has a good reason to
be a singleton.

There's quite a lot of confusion around $provide:
http://stackoverflow.com/search?q=angularjs+service+vs+factory
Tests for example at: http://jsbin.com/EMabAv/1/edit?js,output
2013-10-10 18:22:51 +01:00
Marko Bonaci 8469779a8e docs(tutorial/step11): correct Jasmine Matcher link
Link http://pivotal.github.com/jasmine/jsdoc/symbols/jasmine.Matchers.html
is no longer valid.

Closes #4329
2013-10-09 11:30:47 +01:00
Brian Ford 3374e35953 docs(ngValue): add docs for ngValue directive
Closes #4267
2013-10-07 14:42:54 +01:00
Dave Peticolas 90ff8a98d8 docs(ngModel): fix grammar and improve clarity
Closes #4291

Conflicts:
	src/ng/directive/input.js
2013-10-07 14:41:08 +01:00
Joe Hanink a4dc21ebf5 docs(angular.bind): clarify that bind is partial application
The `angular.bind` function reflects the definition of "partial application", which
reduces a function's arity rather than transforming a function with n args into a
chain of n functions, each having a single arg.

curry : f(x,y,z) -> f(x)(y)(z)
partial application : f(x,y,z) -> f(x)(y,z)

Closes #4239
2013-10-03 23:46:24 +01:00
mtaran-google ec93f94cc9 docs(guide/directive): fix indentation in example code
Closes #4241
2013-10-03 23:45:36 +01:00
gdennie 7665497a53 docs(guide/directive): clarify use of binding to scopes
The use of 'angular' as sample text is confusing to the newbie in that they are forced
to confirm that the text 'angular' is not a keyword or otherwise referring to a system
component. This is changed to a more obvious sample text.

The most common form of `ngBind` is moved to the top of the list.

Closes #4237
2013-10-03 23:44:54 +01:00
Pete Bacon Darwin 2acadc4216 docs(rootScope): improve grammar and clarity 2013-10-03 23:18:45 +01:00
paolo-delmundo c7658d9457 fix($sanitize): sanitize DOCTYPE declarations correctly
HTML to be sanitized that contains a DOCTYPE declaration were causing
the HTML parser to throw an error.  Now the parser correctly removes
the declarations when sanitizing HTML.

Closes #3931
2013-10-03 08:43:06 +01:00
Uri Goldshtein b92c650e05 docs(angular.copy): add an example with the two possible arguments
Closes #4179
2013-09-30 22:16:30 +01:00
Richard Sentino f7a0f9d841 docs(tutorial/step0): fix minor typo
Closes #4154
2013-09-30 21:42:37 +01:00
Uri Goldshtein b17d40b4a5 docs($timeout): add a $timeout example
The original example is by gxlcl.

Closes #4180
2013-09-28 15:26:36 +01:00
Thomas Tuts d745df7e5f docs(guide/overview): fix typo
Closes #4188
2013-09-28 15:05:43 +01:00
joscarsson 53b444419c docs(guide/e2e-testing): select also uses ng-model (like input)
This is specified for input fields, but not for selects. This change specifies it also for select().
2013-09-27 16:24:17 -07:00
David Bennett 9a21050b43 docs(angular.Module): fix controller and directive method parameters 2013-09-27 16:11:42 -07:00
Dave Peticolas 8473b9d558 docs(ngCsp): fix grammar 2013-09-27 13:14:23 -07:00
Dave Peticolas 679d418a50 docs(dblClick): fix grammar 2013-09-27 13:07:01 -07:00
Dave Peticolas 16d247b386 docs(ngDisabled): clarify 2013-09-27 13:06:13 -07:00
Misha Moroshko 4767d34ae8 docs(docs.css): prevent <code> elements from wrapping
Closes #4114
2013-09-25 22:39:37 +01:00
Dave Peticolas 5efc2ed5ac docs(ngHref): fix formatting and clarify
Closes #4106
2013-09-25 22:33:13 +01:00
lorint f9bf194439 docs(jqLite): fix typo
Closes #4105
2013-09-25 22:31:19 +01:00
gdennie 3c4460b513 docs(guide/$location): provide a title for section about replace()
Closes #4104
2013-09-25 22:30:10 +01:00
gdennie a98931de0e docs(guide/$location): clarify $location service role
Clean up confusing use of the term URL to refer to $location as well as 'URL in the browser'.

Closes #4103
2013-09-25 22:27:43 +01:00
Mr.Raindrop 7e5154e755 docs($http): fix adding default header to get request example
Initially, `$httpProvider.defaults.headers.get` is `undefined`, so
`$httpProvider.defaults.headers.get['My-Header']='value'` will throw an
error.

Closes #4101
2013-09-25 22:27:33 +01:00
janhartigan ec6b1cfaba docs(guide/e2e-testing): Fix typo
Closes #4100
2013-09-25 22:27:06 +01:00
Pete Bacon Darwin 8d8801f1ae fix(ngScenario): fix error message description 2013-09-25 12:43:03 +01:00
Boris Serdyuk 301647bf1b refactor(angular.toJson): use charAt instead of regexp
Provides a performance improvement when serializing to JSON strings.

Closes #4093
2013-09-23 11:16:33 +01:00
Pete Bacon Darwin 1c03a1b9c0 docs(ngModelController): clarify issue with isolated scope directive
See #4043
2013-09-19 21:09:20 +01:00
ts-web fd797cdb7e docs(input): fix spelling error and reword for clarity 2013-09-19 21:09:20 +01:00
Dave Peticolas ed1dbf2554 doc(ngApp): fix grammar 2013-09-19 20:17:49 +01:00
Jared Forsyth 022cb3dc4e docs($exceptionHandler): add an example of overriding the handler
Closes #3816
2013-09-19 14:51:50 +01:00
Maarten Stolte 4f107acfcf docs(guide/i18n): change non-existent de-ge to de-de
The de-ge locale does not exist

Closes #4053
2013-09-19 11:27:20 +01:00
Dave Peticolas f363bcb437 docs(ngForm): fix grammar and improve explanation
Closes #4050
2013-09-19 10:41:30 +01:00
Ash 7b2259f32c docs(guide/$location): describe workaround for collocated apps
When using Angular in the root of a domain with HTML5 URLs
where there are links to external paths within the same directory,
the `otherwise` route handler will catch these external files.
This can be fixed by prefixing '.' onto the links to URLs that should
be handled by angular routing.

Original Issue: #3520
Example of Fix: http://fiddle.jshell.net/fgHf6/3/

Closes #3555
2013-09-18 14:34:39 +01:00
Zachary Friedman 9e88fa18b9 docs(tutorial/step_03): add info about karma-ng-scenario plug-in
The existing documentation for this step could have people find themselves
unable to run the `e2e-test.sh` script. This note added regarding
`karma-ng-scenario` will minimize their confusion and allow people to run
the script.

Closes #4033
2013-09-18 12:45:05 +01:00
Hubert SABLONNIÈRE 094580c3da fix(scenario): include "not " in error messages if test is inverted
Closes #3840
2013-09-18 12:34:25 +01:00
James cc4d08c5f0 docs(input): clarify that contenteditable is an HTML5 attribute
Closes #3841
2013-09-17 11:44:04 +01:00
Jesse Palmer d0ae241afd docs(orderBy): fix typo in orderBy.js documentation
Closes #3838
2013-09-16 22:29:25 +01:00
Dave Peticolas e1f103a8e4 doc(api): fix grammar in a directive description
- Add missing words.
- Simplify text.
2013-09-16 16:36:19 +01:00
Dave Peticolas d17aa84be1 docs(api): fix grammar in ngClick description
- Add missing word 'directive'.
- Add missing word 'an'.
2013-09-16 16:33:51 +01:00
Ben Tesser e87c88914f docs($browser): add jsdoc tags and fix typo 2013-09-13 21:37:51 +01:00
Dean Sofer b5d48ee1f0 docs(ngController): rephrased the description for clarity 2013-09-13 14:27:26 +01:00
Pete Bacon Darwin 1c010b33aa docs($http): add examples when calling $http outside $apply
Closes #3996
2013-09-13 14:20:14 +01:00
Dang Nguyen Anh Khoa 16c7ab1ba0 docs($http): explain why $http may not make the request immediately
I came across this issue today and after researching has found out this thread on so:
http://stackoverflow.com/questions/17039998/angular-not-making-http-requests-immediately.

It took me quite sometimes to figure out this so I hope the addition in documentation could save somebody else some times and frustration.
2013-09-13 14:20:14 +01:00
Gowtam Lal 9ef5d8f318 fix(ngOptions): ignore object properties which start with $ 2013-09-13 13:22:36 +01:00
brakon 6a634e309b docs(guide/e2e_testing): clarify that .enter searches by ng-model 2013-09-13 12:34:40 +01:00
Woody Peterson 13f58447e2 test($browser): correct false positive in ApplicationSpec.js
Previously, the check that Application should return a new $window and
$document had the arguments reversed in the first call to navigateTo;
thus, the subsequent check of inequality of $window and $document in the
next navigateTo call would always pass.

This corrects the argument order, which makes this test not succeptible
to false positives.
2013-09-11 22:21:12 +01:00
cjmling bc72211e7b docs(tutorial/step-10): fix incorrect link to step-8 tests
Closes #3972
2013-09-11 20:50:26 +01:00
Paxton Hare 230e124ddb docs(ngModel): provide link for best practices.
Closes #3973
2013-09-11 20:42:15 +01:00
Randi Hillerøe 10016ab3fd docs(guide/concepts): remove div-clear-tags that break the formatting
Closes #3974
2013-09-11 20:37:44 +01:00
Butch Peters 69dc003a0b docs(Attributes): add missing documentation for $observe method
- Add proper ngdoc annotations to existing $observe documentation
- Add link to directive guide for usage example of $observe
- Add note about $observe function parameter signature

Closes #3957
2013-09-11 12:11:57 +01:00
naorye ae2fd55575 docs($q): clarify what happens when rejected
Closes #3943
2013-09-10 22:09:01 +01:00
jakub-bochenski f102fb75b6 docs(angular.copy): clarify corner cases
The behaviour when null or undefined was passed was not clear.
The exception thrown when source == destination was not documented.

Closes #3946
2013-09-10 22:07:22 +01:00
Anthony Tran 8a7240ddfd docs(forms.ngdoc): fix spacing in example
Closes #3930
2013-09-09 17:31:45 +01:00
Richard ac70ec0340 docs(README): add dashboard link
Closes #3934
2013-09-09 12:26:41 +01:00
Pete Bacon Darwin dbd90a4d78 docs(mock.inject): fix typo 2013-09-09 08:44:25 +01:00
JasonM23 5b1f9b3c2b docs(mock.inject): document underscore wrapping syntax
Add a summary describing the ignored underscore syntax sugar helper,
with a simple use case example.

Closes #3621
2013-09-05 14:35:25 +01:00
Alexander Kaidalov 08a07f2d30 docs(tutorial): fix markup for tutorial_03.png diagram
Closes #3707
2013-09-05 14:11:52 +01:00
Alexander Kaidalov b1143c9481 docs(tutorial): fix markup for tutorial_04.png diagram 2013-09-05 14:08:58 +01:00
Pete Bacon Darwin 73e1d0054c docs(tutorial): clarify use of inject() in step 9
Closes #3718
2013-09-05 13:58:34 +01:00
Pete Bacon Darwin 33ab261817 docs(booleanAttrs): improve parameter docs for boolean attributes 2013-09-05 13:29:21 +01:00
Nick Donohue 230ff0576a docs(css_styling_guide): add ng-scope and ng-binding classes
I noticed angular was adding these css classes to elements and believe they
should be listed in the documentation at this page. The ng-scope class is
mentioned in the developer guide, hence the link there, and the ng-binding
class is not mentioned anywhere else in the documentation or the guide that
I found.

Closes #3728
2013-09-05 13:07:10 +01:00
Pete Bacon Darwin e3371d7c53 docs(angular.bootstrap): clarify modules parameter
It was not clear what you could pass to specify modules to load in the
`module` parameter of this function. The `modules` parameter takes an
array.

The main case is to provide a String, which is the name of a "predefined"
angular module.
The side cases are to provide a Function (or an annotated function in the
form of an Array), which will be invoked by the injector as a run block.

It is not possible to "define" new modules via this parameter.

Closes #3692
2013-09-05 12:19:18 +01:00
Calvin Fernandez 9b2b93d9bd docs(bootstrap.ngdoc): clarify bootstrap example
Clear up confusion about module declaration when using manual bootstrap.
2013-09-05 10:24:22 +01:00
Pete Bacon Darwin d7fb721b4d docs(): parameter for html5Mode is boolean 2013-09-05 10:02:07 +01:00
Ben Lesh e7cfa5c2bf docs($anchorScroll): provide an example of basic usage.
Per a request made by Peter Bacon Darwin here:  http://www.benlesh.com/2013/02/angular-js-scrolling-to-element-by-id.html?showComment=1370941217879#c8718313084813008967
2013-09-05 08:34:35 +01:00
jankuca 2a3212a0a3 fix($http): allow empty responses to be cached
Closes #3809
2013-09-02 11:48:14 +02:00
Igor Minar 7a08a76875 chore(build): add jenkins_build.sh file
cherry-pick from the master branch with the promises-aplus tests
removed.
2013-08-30 23:36:17 +02:00
Brian Ford 22a09dddc6 chore: upgrade grunt packages to match master 2013-08-28 14:59:26 -07:00
phanboy4 8c72549cc2 docs(guide): update description of $inject mechanism to be a little clearer 2013-08-28 13:43:28 -07:00
Brian Ford bba5214930 docs(overview): improve grammar 2013-08-22 17:40:50 -07:00
Igor Minar fb194b9488 chore(release): start new 1.0.9 iteration
Marc is working on the code name :-)
2013-08-22 11:23:17 -07:00
Igor Minar 56817e9faa chore(release): cut the 1.0.8 bubble-burst release 2013-08-22 11:20:23 -07:00
Igor Minar e87fb8a8e1 chore(grunt): ensure that grunt uses zip for compression 2013-08-22 11:19:53 -07:00
Igor Minar 5be0fc40ed docs(changelog): release notes for 1.0.8 bubble-burst 2013-08-22 11:07:45 -07:00
Igor Minar a98337b359 docs(CHANGELOG): update changelog 2013-08-22 11:07:41 -07:00
Igor Minar 143d016899 docs(CHANGELOG): release notes for 1.2.0-rc1 spooky-giraffe 2013-08-22 11:07:36 -07:00
ghodss 3d70e55d72 docs(guide): warn about module creation versus retrieval
Updated Module documentation to include the suggestion of the top-rated comment: "This documentation should warn that "angular.module('myModule', [])" always creates a new module, but "angular.module('myModule')" always retrieves an existing reference."
2013-08-22 10:59:29 -07:00
Igor Minar dbcc44dc80 revert: feat(ngForm): Supports expression in form names
This reverts commit 4407e81c61.

No features or breaking changes in the stable branch please.
2013-08-22 10:22:17 -07:00
Igor Minar db87fd52ca chore(changelog.js): pickup breaking changes f/ chore/refactor commits 2013-08-22 10:07:41 -07:00
Marcel Morgan 792509e987 docs(guide): grammatical corrections to Form and Control definitions 2013-08-22 09:15:50 -07:00
Igor Minar 166e0d63d0 revert: fix($compile): correct controller instantiation...
fix($compile): correct controller for async directives

This reverts commit 51d32243fe
as well as commit   9c51d50318

Changing ordering of events in stable branch is not a good idea.
2013-08-21 01:27:58 -07:00
Igor Minar 0d7f19bb62 revert: fix($compile): always instantiate controllers...
fix($compile): always instantiate controllers in parent->child order

This reverts commit 683fd713c4.

It turns out that there is some existing code that relies on the
incorrect timing. Rather than breaking these apps that depend on
stable releases, we are going to keep this changeo only in master
and the apps will need to migrate to the correc timing during the
1.2 upgrade.
2013-08-21 01:21:02 -07:00
Michał Gołębiowski 607045d592 fix(package.json): add a repository field
The `npm install` command complains about the missing repository field.

Closes #3674
2013-08-20 23:56:38 -07:00
Chirayu Krishnappa 51d32243fe fix($compile): correct controller instantiation for async directives
This fixes regression introduced by #3514 (9c51d503) - this commit is being
reverted here and a better fix is included.

The regression caused the controller to be instantiated before the isolate scope
was initialized.

Closes #3493
Closes #3482
Closes #3537
Closes #3540
2013-08-20 18:51:07 -07:00
Reto Aebersold 1c1a1bc9ed style(docs): replace CRLF by LF in svg header logo 2013-08-16 20:06:35 -07:00
Brian Ford 553fdb318f fix(grunt): fix regex in grunt util to handle pre-release versions
NOTE: this also includes a temporary work-around for Bower
2013-08-15 12:43:05 -07:00
Rob Dodson 607ed4ee46 docs($cookies): add info about angular-cookies.js
per the [top comment here](http://docs.angularjs.org/api/ngCookies.$cookies#comment-912064775)

updating documentation so it matches [$resource](http://docs.angularjs.org/api/ngResource.$resource)
and instructs the user to include the `angular-cookies.js` and load `ngCookies`.

Closes #3607
2013-08-15 10:25:00 -07:00
ItsLeeOwen ec1cece270 fix(orderBy): remove redundant if statement
Removed unnecessary additional conditional statement.
2013-08-14 17:01:58 -07:00
Vojta Jina 4656e386fb chore: fix Travis build
Specify hostname/port for connect server to avoid
https://github.com/joyent/libuv/issues/826

Conflicts:
	Gruntfile.js
2013-08-14 16:12:37 -07:00
Vojta Jina f29f2f99b1 chore: disable npm install on Travis
Grunt is configured to run `npm install` before every task. That is convenient when switching a branch for example.

On Travis, this makes no sense and is causing tons of NPM warnings (eg. packages not defining repository field etc).
2013-08-14 16:12:37 -07:00
Vojta Jina cc27f08588 chore: update Node.js on Travis 2013-08-14 16:12:37 -07:00
Vojta Jina 99fe398b59 chore: update Karma to v0.10 2013-08-14 16:12:36 -07:00
Vojta Jina cb89e02432 chore(sauce): use tunnel-identifier and ready-file only on Travis
When running locally, there's not TRAVIS_JOB_NUMBER env variable defined and it screws
the Sauce Connect (it uses a tunnel with empty name), this makes it work locally without defining
TRAVIS_JOB_NUMBER env variable.

Also, if you run the sauce_connect_setup.sh locally, without having SAUCE_CONNECT_READY_FILE, it
does not pass the `--ready-file` argument to avoid Sauce Connect blowing up.
2013-08-14 16:12:36 -07:00
Andy Gurden ac69392cd7 fix($timeout): clean deferreds immediately after callback exec/cancel
Make sure $timeout callbacks are forgotten about immediately after
execution or cancellation.

Previously when passing invokeApply=false, the cleanup used $q and so
would be pending until the next $digest was triggered. This does not
make a large functional difference, but can be very visible when
looking at memory consumption of an app or debugging around the
$$asyncQueue - these callbacks can have a big retaining tree.
2013-08-14 16:04:48 -07:00
Vojta Jina a5fb372e1e fix(mocks.$timeout): forward delay argument
The $timeout decorator was not forwarding the delay argument to `browser.defer.flush(delay)`.
2013-08-14 16:04:48 -07:00
ebeal da720712f3 fix(tutorial): fix broken link caused by bad line break 2013-08-14 15:46:48 -07:00
Mikk Kirstein 0cb3dc8782 docs($http): added return to interceptors success callback 2013-08-14 14:19:10 -07:00
Igor Minar dfd95f0115 revert: docs($interpolate): add example for the provider
This reverts commit 1a01e80b9c.

This example is bogus, breaks docs.angularjs.org and karma e2e tests
2013-08-14 14:08:18 -07:00
David Bennett 7636670a77 docs(input): add missing ngChange directive for email type
All other input types already have it.
2013-08-13 10:17:44 -07:00
Siddique Hameed fe6247a7f8 docs(guide/unit-testing): add expression example
* Improved developer guide, directive unit testing documentation code with scope expression
* Removed documentation block with nothing on it
2013-08-12 16:23:39 -07:00
Vojta Jina 2b90ef1694 test(matchers): update toThrow matcher 2013-08-12 16:23:39 -07:00
Chirayu Krishnappa 099138fb9a fix($parse): move global getter out of parse.js 2013-08-12 16:23:39 -07:00
Igor Minar cbe31d8dfd fix($location): default to / for the url base if no base[href]
With the recent refactoring of $location service we changed this behavior
resulting in a regression.

Previously we thought that html5 mode always required base[href]
to be set in order for urls to resolve properly. It turns out that
base[href] is problematic because it makes anchor urls (#foo) to
always resolve to the base url, which is almost always incorrect
and results in all anchors links and other anchor urls (e.g. svg
references) to be broken.

For this reason, we should now start recommending that people just
deploy to root context (/) and not set the base[href] when using
the html5 mode (push/pop history state).

If it's impossible to deploy to the root context then either all
urls in the app must be absolute or base[href] must be set with the
caveat that anchor urls in such app won't work.

Closes #2762
2013-08-12 16:23:38 -07:00
Vineet Kumar 06b0930b6a fix(ngCloak): hide element even when CSS 'display' is set
Previously an element like
<div class="foo ng-cloak">...</div>
would still be annoyingly visible if it matched a CSS rule like
.foo { display: inline-block; }, overriding ng-cloak's display: none.
2013-08-12 16:23:38 -07:00
Sebastian Müller 7b7be341b6 refactor(core): use native String.prototype.trim if available 2013-08-12 16:23:38 -07:00
Lucas Galfasó 751c77f87b fix(i18n): Do not transform arrays into objects
Do not trasnform arrays into objects when generating the locale objects
Add unit test for this check
2013-08-12 16:23:38 -07:00
Ben Holley 634ac03c5e style(sanitize): fix typo in variable names 2013-08-12 16:23:38 -07:00
Vojta Jina 8cab53c64d chore(package.json): fix name to work with latest NPM 2013-08-12 16:23:38 -07:00
Igor Minar edef295b11 fix(grunt): cache version number
caching the version number speeds up the build and preserves resources.

this also fixed EMFILE error that now occurs on some macs.
2013-08-12 16:23:38 -07:00
Jeff Cross 64e447354e fix(dump): Prevented window.dump from being overridden by karma-jasmine.
In commit 6820322db562382fac903be35831275948825317 of Karma-Jasmine, the
dependency on angular.dump was removed. This caused two undesirable side
effects in the angular.js project. 1) Tests for presence of mock dump were failing,
and 2) the default window.dump was not outputting valuable angular-aware info. This
simple fix adds window.dump in testabilityPatch, to preprocess dumped input prior
to passing it to the global dump method.
2013-08-12 16:23:38 -07:00
Brenton da1f7c762d fix(equals): {} and [] should not be considered equivalent
angular.equals was returning inconsistent values for the comparison between
{} and []:

    angular.equals({}, []) // true
    angular.equals([], {}]) // false

Since these object are not of the same type, they should not be considered
equivalent.
2013-08-12 16:23:38 -07:00
Roland 89366bdbf9 docs(guide): remove superfluous }); 2013-08-12 16:23:37 -07:00
Igor Minar 78efa0e36c fix($compile): don't check attr.specified on non-ie7
the specified attribute is depricated and creates warnings in Firefox

Closes #3231
Closes #2160
2013-08-12 16:23:37 -07:00
Matias Niemelä 3a8b3db174 chore(.gitignore): ignore npm-debug.log file 2013-08-12 16:23:37 -07:00
Emmanuel 1a01e80b9c docs($interpolate): add example for the provider 2013-08-12 16:23:37 -07:00
Pete Bacon Darwin d59027c40e fix($q): call reject() even if $exceptionHandler rethrows
Normally $exceptionHandler doesn't throw an exception.  It is normally
used just for logging and so on.  But if an application developer
implemented a version that did throw an exception then $q would never
have called reject() when converting an exception thrown inside a `then`
handler into a rejected promise.
2013-08-12 16:23:37 -07:00
jankuca c197c2aa27 chore(bower): add a .bowerrc file 2013-08-12 16:23:37 -07:00
Eric Hagman 01cd34957e fix(jqLite): return array from multi select in val() 2013-08-12 12:00:47 -07:00
OpherV 864517e5a2 docs($compile): update directive type signature
To avoid "Argument type Array is not assignable to parameter type function" validation error  When using the minifcation-safe array style

(eg .directive('myDirective', ['$http','$timeout','$compile', function($http,$timeout $compile).... )

Closes #3392
2013-08-09 10:34:26 -07:00
Niall Smart 1dd5d2ec1f docs(ngModel): validators should return undefined for invalid values.
Closes #3525
2013-08-09 10:24:48 -07:00
Santi Albo 6da835f4bc docs(httpBackend): update documentation for expect methods
`expect` methods can receive an Object as the data parameter, which was
undocumented.
2013-08-09 10:10:45 -07:00
Andy Hitchman 5cca077e4a fix(angular.copy): change angular.copy to correcly clone RegExp
angular.copy previously copied RegExp as an empty object. Change detects
RegExp instance and clones into new RegExp. This change is based on a previous
fix to allow Date to be copied.

Closes #3473
Closes #3474
2013-08-09 00:17:34 -07:00
Igor Minar e290aa8c13 docs(ngModel): clarify docs for NgModelController#
Closes #3498
2013-08-08 23:08:08 -07:00
jankuca 9c51d50318 fix($compile): always instantiate controllers before pre-link fns run
Controllers should be always instantiated after compile fn runs, but before
pre-link fn runs. This way, controllers are available to pre-link fns that
request them.

Previously this was broken for async directives (directives with templateUrl).

Closes #3493
Closes #3482
Closes #3514
2013-08-08 22:58:51 -07:00
Matias Niemelä 1c3a46adda chore(ngdoc): wrap all pages inside of a container tag for easy styling 2013-08-07 22:11:45 +01:00
Matthew Windwer 4407e81c61 feat(ngForm): Supports expression in form names
<form name="ctrl.form"> form controller will accessible
as $scope.ctrl.form instead of $scope['ctrl.form']

BREAKING CHANGE:
If you have form names that will evaluate as an expression:

<form name="ctrl.form">

And if you are accessing the form from your controller:

  Before:

  function($scope) {
    $scope['ctrl.form'] // form controller instance
  }

  After:

  function($scope) {
    $scope.ctrl.form // form controller instance
  }

This makes it possible to access a form from a controller
using the new "controller as" syntax. Supporting the previous
behavior offers no benefit.
2013-08-07 13:59:41 -07:00
neilmcgibbon ad76e77fce fix(input): fix the email regex to accept TLDs up to 6 characters long
The input field email regex does't not match long domain extensions. This commit extends the email regexp to take a 6 character TLD.

Example 6-character TLDs include .museum and .travel - (e.g. allabout.travel).
2013-08-07 14:18:22 -04:00
Pawel Kozlowski ac5b9055f6 fix(jqLite): forgive unregistration of a non-registered handler 2013-08-07 19:09:04 +02:00
Michael Stewart c18074a310 docs(compile): fix minor spelling mistake
Closes: #3468
2013-08-06 16:31:11 +01:00
Mark Campbell ed703d8e2c docs(guide/controller): fix wording in list of 'Do not use'
Wording has been changed in two of the examples to read naturally.
For example:

From: 'Do not use controllers for to run stateless or stateful code
shared across controllers'

To: 'Do not use controllers for sharing stateless or stateful code
across controllers'

Closes #3454
2013-08-03 22:06:03 +01:00
Igor Minar 9c53d0769e revert: fix(location): fix parameter handling on search()
This reverts commit 90532f5e3c.

The commit contains references to minErr that are not available
in the stable branch.
2013-08-01 09:34:56 -07:00
Misko Hevery 90532f5e3c fix(location): fix parameter handling on search() 2013-07-31 17:10:10 -07:00
Brenton 2bc04d23fb docs(header): replace logo.png with logo.svg
The current logo looks awful on high-density displays.  SVG is a
better choice because it can scale to any resolution without
increasing file size.

Amending #2775 to add support for IE 8 by falling back to existing PNG
with img.onerror

Using relative URLs as directed by @btford and @petebacondarwin.

(commit by Brenton Simpson - @appsforartists)

Closes #2874

Conflicts:

	docs/src/templates/css/docs.css
	docs/src/templates/index.html
2013-07-31 12:06:04 -07:00
Roland 7f6da764e1 docs(tutorial): mention the controller along the scope 2013-07-27 17:14:30 +01:00
Roland 6926ef8f67 docs(tutorial): add formatting
the string literal {{query}} was missing as it was not enclosed into ``
2013-07-27 16:07:51 +01:00
Roland bba2b7cfce docs(tutorial): add that the test also creates a controller 2013-07-27 15:53:35 +01:00
Pawel Kozlowski dc1e55ce1a fix(form): pick the right attribute name for ngForm
Closes #2997
2013-07-24 14:41:54 -07:00
Paul Meskers 408e868237 fix(numberFilter): always convert scientific notation to decimal
Previously, the number filter would format small and large numbers
as scientific notation. It now uses toFixed() to ensure that all
requested digits are shown.
2013-07-24 12:06:19 -07:00
Pavel Vasek 97abb12473 fix($location): prevent infinite digest error due to IE bug
If an app uses HTML5 mode and we open an html5 url on IE8 or 9 which
don't support location href, we use location.replace to reload the page
with the hashbang equivalent of the url but this fails with infinite
digest. This is because location.replace doesn't update location.href
synchronously on IE8 and 9.

Closes #2802, #3305, #1417
2013-07-24 10:38:29 -07:00
Braden Shepherdson d26bffbc3f docs(bootstrap): Note that ngScenario requires ngApp
ngScenario expects an ngApp directive to be used, and doesn't work for
manually bootstrapped apps. The failure mode is to hang on navigation.

Trying to make this wont-fix bug less obscure by documenting it.
Eventually Protractor will replace ngScenario and fix this.
2013-07-23 20:35:03 +01:00
Spencer 2f3bd9dae7 docs(cacheFactory): correct typos 2013-07-23 20:16:58 +01:00
Richard John 256e5dff55 docs(index): add seed app link to menu item 2013-07-23 20:11:03 +01:00
Igor Minar acb6b75fe9 chore(dump): remove dead code
This code is not being used any more and the test is now failing
due to Karma changes. Karma used to expose window.dump but that
changed recently and that's why our build is now failing.

I'm removing the code and test, but we still need to figure out
how to route window.dump through angular.mock.dump, but that will
have to be a separate commit.
2013-07-22 14:01:38 -07:00
Igor Minar 683fd713c4 fix($compile): always instantiate controllers in parent->child order
Previously it was possible to get into a situation where child controller
was being instantiated before parent which resulted in an error.

Closes #2738
2013-07-22 11:32:50 -07:00
Jérémy 3591ae0103 docs(input): fix example
The input [number] error spans did not show on the example, as they were
relying on an non-existing property (myForm.list.$error) vs the working
property (myForm.input.$error)
2013-07-21 21:24:53 +02:00
Vineet Kumar 5fedfd79a5 docs(ngController): remove obsolete mention of scope as this in controller
Controllers are now (since angular 1.0) instantiated as regular constructorsand the scope
is injectable as $scope rather than being referenced as `this` in controller methods.
2013-07-21 20:30:40 +02:00
David Sanders bdde40e755 docs($window): improve style and clarify wording 2013-07-21 20:24:49 +02:00
Pete Bacon Darwin 88c4963328 docs(jqLite): document "$destroy" event 2013-07-18 19:53:13 +01:00
Matias Niemelä 67a81eff42 chore(ngdocs): fix improve button overlap 2013-07-18 18:56:08 +01:00
Spencer add43e91dc docs($templateCache): add examples of usage 2013-07-17 16:41:09 +01:00
Bruno Coelho b3c7a6d566 docs(dateFilter): fix typos
Fix closing parenthesis, quotes around string literal and remove
trailing whitespace.

Closes #3250
2013-07-17 11:28:01 +01:00
James deBoer 424bd49ede test(utils): Adds a missing test for snake_case 2013-07-16 11:18:11 -07:00
Matias Niemelä 6a58404507 chore(gitignore): add libpeerconnection.log
Google chrome (when tested using karma) spits out a log file called libpeerconnection.log
2013-07-15 09:28:54 -07:00
Matias Niemelä d4ce8362b1 chore(ngdocs): remove autofocus for the filtering search 2013-07-15 14:57:47 +01:00
sdesmond caa12dbc57 docs(di): promote registering controllers on modules 2013-07-14 16:23:04 +02:00
David 1122b3c14d style(ngMock): add missing whitespace 2013-07-14 16:06:38 +02:00
Ben Ripkens a357649da5 fix(angular.equals): add support for regular expressions
Regular expression objects didn't used to be considered to be equal when using
'angular.equals'. Dirty checking therefore failed to recognize a
property modification.

Closes #2685

Conflicts:

	test/AngularSpec.js
2013-07-13 22:35:17 -07:00
Greg Thornton 332a3c7984 feat(Angular.js): skip JSON.stringify for undefined
Return early in `angular.toJson` if the object to be stringified is `undefined`.
IE8 stringifies `undefined` to `'undefined'` whereas other browsers return
`undefined`. This normalizes behavior and passes currently broken unit tests
in IE8.
2013-07-12 20:49:50 +02:00
Pete Bacon Darwin fcd761b9d7 fix(sanitize): match URI schemes case-insensitively
According to RFC 3986 (http://tools.ietf.org/html/rfc3986#section-3.1)
schemes such as http or mailto are case-insensitive. So links such as
http://server/ and HTTP://server/ are valid and equivalent.

Closes #3210
2013-07-12 09:32:23 +01:00
Wesley Cho b0d5f062e3 fix(ngSubmit): expose $event to ngSubmit callback 2013-07-11 17:27:36 -07:00
Brian Ford 2c0753225a revert: feat(ngDocs): add links to source for API
This reverts commit 61fb5863df.
2013-07-11 15:32:33 -07:00
Mikk Kirstein 3b898664ee fix(ngValue): made ngValue to write value attribute to element 2013-07-11 14:59:38 -07:00
Julien Bouquillon 61fb5863df feat(ngDocs): add links to source for API
- add tests
 - the link points to the gruntUtil.getVersion().number tree on github
2013-07-11 14:40:06 -07:00
Paulo Scardine a4ec297925 fix(scope): watches can be safely unregistered inside watch handlers
Closes #2915
2013-07-11 22:07:15 +01:00
Brian Ford 93d7e60d43 chore(build): add check for merge conflicts, ddescribe, and iit 2013-07-11 11:59:38 -07:00
Igor Minar 338264b5f6 test(ngPattern): fix disabled test 2013-07-11 11:58:47 -07:00
Igor Minar 19b51caa2c test(ngList): remove disabled test
this test fails and we don't have intentions on making it pass since
we never made a commitment to implement this feature.
2013-07-11 11:12:17 -07:00
Igor Minar 8c08b4373c docs(ngList): fix example and add e2e test 2013-07-11 09:23:18 -07:00
Igor Minar 0b38882a91 style(input): remove ws 2013-07-11 09:23:18 -07:00
sdesmond 3364d69a3b docs(guide): clarify example 2013-07-10 22:58:43 +02:00
sdesmond e6c9bfa4a9 docs(guide): example filter does not conditionally assign a color 2013-07-10 22:55:03 +02:00
Robert Fauver 7a3e182e9c docs(guide/di): fix typo 2013-07-10 22:30:53 +02:00
Tay Ray Chuan 2471f6b01c docs(contribute): improve git instructions 2013-07-10 22:23:12 +02:00
Lefteris Paraskevas 1fefafd09f docs(overview): fix typo
Removed repeated "the" in the sentence: The input invalidates itself by turning red when you enter invalid data or leave "the" the input fields blank (Line 137).
2013-07-10 22:12:27 +02:00
Mark Striemer 8a63dc3151 docs(ngMock): correct verifyNoOutstandingExpectation example 2013-07-10 20:32:53 +02:00
Marco Vito Moscaritolo 403008816c docs(angular.identity): fix missing 'angular' in identity function 2013-07-09 14:32:59 +01:00
Pete Bacon Darwin 62d552ffe2 docs(ngModelController): provide a more intuitive example
The example directive, using contenteditable was not showing required
even if you cleared the content from it.

Closes #3156
2013-07-08 14:53:15 +01:00
Pete Bacon Darwin bcaa4217bc docs(numberFilter): fix explanation of default fraction size
The default fraction size for the number filter is actually computed
from the `NUMBER_FORMATS.PATTERNS.maxFrac` value in the current locale.

Closes #3157
2013-07-08 11:23:37 +01:00
tgkokk 0823f6dfab docs(guide/e2e-testing): fix typos 2013-07-07 20:32:06 +01:00
basarat 87bb554aec docs(input): ng-model doesn't work well with isolated scope directive
Closes #3123
2013-07-04 00:35:52 +01:00
Andrew O'Brien 36447cb2b5 docs(guide/directive): make directive controller minification-safe
It is best to emphasize that the "controller" property needs to be min safe

Closes #3125
2013-07-04 00:29:10 +01:00
Anders Hessellund Jensen 3b2c6f09cb fix($compile): empty normalized href should pass sanitation check
Sometimes IE returns an empty string for its normalized href on a tags.
This should pass the sanitation check in $compile.

Closes #2219, #2593
2013-07-04 00:13:04 +01:00
Joao Sa 63414b9653 fix(jqLite): prepend array in correct order
Match jQuery behavior when prepending array into empty element
2013-07-03 20:25:28 +01:00
exex zian 5f24bb0267 docs(tutorial/step9): formatted Unicode character line
Add tick and cross mark corresponding to their respective unicodes.
2013-07-02 22:50:52 -07:00
Vojta Jina 52519d45b9 chore(travis): speed up the build
- parallelize the tasks
- cache requests (e2e tests)

This reduces the time from ~18min to ~12min.

It makes the output little messy. We could buffer output of each task and display it once it's fully finished, nicely. I think giving instant feedback is better.
2013-07-02 15:12:03 -07:00
Niall Smart 78728df099 docs(guide/location): fix example code - hashPrefix is a method 2013-07-02 10:01:51 +01:00
Vojta Jina 732db27cd6 chore: add karma-script-launcher plugin
This plugin is shipped as a default one with Karma. It's specified as a peer dependency.

I assume, there's an old version of NPM on the CI server, which does not support peerDependencies and therefore it didn't get installed.

This will make the dependency explicit.
2013-07-01 10:15:56 -07:00
Itamar Rogel 3cad63fbd8 docs($cacheFactory): show that you can access existing caches 2013-07-01 12:03:10 +01:00
Spencer Applegate d2be5939dc docs(Angular.js): explain that toJson strips $... properties
In Angular.toJson, any properties with a leading '$' character will be
stripped from the resulting string since angular uses this notation
internally for services.  There have been complaints of not knowing
about this functionality until it breaks within their code.
2013-07-01 11:36:17 +01:00
Vojta Jina 9a77d03047 chore: set up Sauce Labs with Travis
This should not affect the Jenkins build at all.

Now, the Travis build uses Chrome on Sauce Labs, which in theory gives us opportunity to use any
browser/platform that Sauce Labs offers.
2013-06-28 16:36:30 -07:00
Vojta Jina 8efcec67cc chore: clean up angularFiles.js 2013-06-28 16:35:05 -07:00
Vojta Jina 4fbd4bbd8d chore: update karma to 0.9.4
And also add shared config to make karma configs a bit simpler.
2013-06-28 16:30:48 -07:00
Vojta Jina 2fae296cbc chore: remove jstd leftovers 2013-06-28 16:29:09 -07:00
Igor Minar cef8466419 docs(misc/faq): remove obsolte t-shirt instructions 2013-06-28 11:27:55 -07:00
Andrew Peterson 083159ebbe docs(ngBind): clarify some of the writing 2013-06-27 21:20:56 +01:00
Andrew Peterson 32e440cffc docs(ngPluralize): improve wording 2013-06-27 21:15:33 +01:00
Adam 89c8c93b9a docs(guide/e2e-testing): clarify description of input(name) selector
The description of the input selector made it seem that you were selecting
an input element based upon it's name attribute. In reality, you are
selecting an element by the string in the ng-model attribute.
2013-06-27 20:46:09 +01:00
Pete Bacon Darwin 296074f548 docs(ngMock/$httpBackend): fix testing example
Closes #3075
2013-06-27 20:38:15 +01:00
Nelson Blaha 2ccfaffa74 docs(tutorial): add experiment showing reverse sort 2013-06-27 19:36:46 +01:00
Jeffrey Palmer 192672a162 docs(guide/controller): fix an error in the scope inheritance example
The chained scope creation example at the bottom of this document was using the childCtrl to create the babyScope, instead of the childScope.
2013-06-25 23:54:33 +01:00
Domenic Denicola 7f4e658d3d docs(guide/expression): remove reference to NullPointerException 2013-06-25 21:13:56 +01:00
Pete Bacon Darwin ff57695855 refactor(angular.bootstrap): rename internal function 2013-06-20 15:23:04 +01:00
NimaVaziri ae8deb1246 docs(cookbook/helloworld): display "World" if no name is entered 2013-06-20 14:40:07 +01:00
Pete Bacon Darwin b9dcb35e9b fix(Angular.js): don't crash on invalid query parameters 2013-06-20 14:32:05 +01:00
Caio Cunha 25d9f5a804 fix($http): ensure case-insens. header overriding
If user send content-type header, both content-type and default
Content-Type headers were sent. Now default header overriding is
case-insensitive.
2013-06-19 22:43:19 +01:00
sarkasm 1b234cb7af docs(directive): fix typo 2013-06-19 11:51:18 +01:00
gdi2290 d219442945 docs(tutorial): add missing 'node' command and <code> tags 2013-06-18 22:05:43 +01:00
John Bohn 2b33be47cb docs(tutorial/step_07): add commas make tutorial read more clearly 2013-06-18 21:57:21 +01:00
Ore Landau 499baced12 docs(loader): fix typo and minor semantic error 2013-06-18 21:23:00 +01:00
Ore Landau 7aa9fecab8 docs(guide/di): fix headings hierarchy 2013-06-13 22:51:11 +01:00
Misha Moroshko 9b6c82d804 docs(select): fix typos in ngOptions 2013-06-13 22:48:03 +01:00
Ore Landau c3117b7544 docs($q): fix a few issues 2013-06-13 22:42:26 +01:00
Jad Naous 67744384e8 docs(guide/e2e-testing): fix verb tense 2013-06-13 22:37:33 +01:00
Ore Landau 17c401d09a docs(tutorial/step_05): apply more useful link to services 2013-06-13 21:15:32 +01:00
Dean Sofer 488aea15f4 docs(FormController): add methods for FormController 2013-06-12 21:49:52 +01:00
Dean Peterson 43df853ee3 docs(ngModelController): improve $parsers/$formatters with example 2013-06-12 21:23:16 +01:00
Ore Landau 28d5dcb578 docs(ngClass): fix minor typo. 2013-06-12 20:47:59 +01:00
Pete Bacon Darwin 7eb15c46a2 docs(guide/bootstrap): clarify manual bootstrapping 2013-06-12 20:42:12 +01:00
Pete Bacon Darwin 1fac36e2cb docs(ngRoute): clarify when gets updated 2013-06-11 22:35:47 +01:00
Pete Bacon Darwin 4b6c87b6e7 docs(ngSubmit): clarify that there must be no action attribute 2013-06-11 21:30:10 +01:00
Igor Minar ce6c2b2072 chore(docs): fix memory leak in example embed code
we need to sever the link between the main root scope and the example
root scope - this is only needed because we are embedding one app
in the other.
2013-06-10 13:10:38 -07:00
Igor Minar 3e94a2c54d docs(faq): update customink order info 2013-06-10 11:39:26 -07:00
Jared Forsyth b1e488f5d7 docs(guide/unit-testing): fix typo 2013-06-04 22:28:58 +01:00
Jared Forsyth 03d867160f docs(guide/injecting_controllers): add a hint in example
Add a hint to tell the user that they need to click 3 times before an alert is shown.
2013-06-04 22:25:38 +01:00
Marcin Wosinek 9870e65c5f docs(ngTransclude): fix outdated scope definition in example 2013-06-04 22:14:15 +01:00
Pete Bacon Darwin aa839b9ff0 docs(guide/unit-testing): fix controller test example 2013-06-04 22:10:27 +01:00
Robbie Ferrero fdb66aa237 docs(Angular.js): clarify ngApp usage 2013-06-04 22:01:26 +01:00
Robb Shecter e0ca5fdd51 docs(angular-mocks): fix typo in example
fromJSON() should be fromJson()
2013-06-04 21:54:05 +01:00
Alan Klement 681c1c53e4 docs(sanitize): add @description section 2013-06-04 21:50:38 +01:00
Siddique Hameed 631c4863d8 docs(index): make menu links relative
Before the Develop drop down menu items were hard coded with an absolute url,
which meant that they did not work correctly on local or ci server builds.
2013-06-04 21:08:56 +01:00
Luc Morin 944bda12c7 docs(ngClass): clarify the use of object map 2013-06-04 21:01:43 +01:00
Ehsan Ghandhari bc36c4dea4 docs(guide/concepts): add comment as a type of directive 2013-06-04 20:54:03 +01:00
Robb Shecter 722766958b docs(guide/understanding_model): improve example consistency 2013-06-04 20:50:35 +01:00
Manuel Kiessling 73fd3ca2eb docs(guide/compiler): fix some minor language errors 2013-06-04 20:38:27 +01:00
Alex Young efe8ad51ed docs(guide/di): fix some small grammatical issues 2013-06-04 20:31:06 +01:00
Jens Rantil d5b62465f0 docs(validate-commit-msg): fix incorrect comment
If you `cd` into the repo, `validate-commit-msg.js` will be in the root
of it.
2013-06-04 20:24:27 +01:00
Luc Morin bc76e7255b docs(input): provide explanation of how ngModel will affect the local scope 2013-06-04 20:16:37 +01:00
Eduardo Garcia 8dd23ad2f2 docs(guide): format snippets of code in plain text 2013-06-04 20:07:09 +01:00
adamshaylor bce75d7c68 docs(overview.ngdoc): clarify wording 2013-06-04 20:02:18 +01:00
Michał Gołębiowski 815053e403 fix(jqLite): correctly monkey-patch core jQuery methods
When real jQuery is present, Angular monkey patch it to fire `$destroy` event.

This commit fixes two issues in the jQuery patch:
- passing a selector to the $.fn.remove method (only fire `$destroy` on the matched elements)
- using `$.fn.html` without parameters as a getter (do not fire `$destroy`)
2013-05-23 11:45:57 -07:00
Igor Minar 6173abe20b docs(changelog): fix changelog formatting 2013-05-22 21:48:37 -07:00
Igor Minar 6fcf0afa35 docs(changelog): add note about animation breaking change 2013-05-22 21:48:37 -07:00
Eddie Monge 05521e276f style(docs/template): add in missing semicolons 2013-05-22 22:56:51 +01:00
Jens Rantil 38ffbbd7dd docs(guide/directive): clarify directive priority
Fixes #2644.
2013-05-22 21:10:03 +01:00
Igor Minar 47e1878e4c chore(release): start 1.1.8 bubble-burst iteration 2013-05-22 01:14:09 -07:00
Igor Minar dc6f149973 chore(release): cut the 1.0.7 monochromatic-rainbow release 2013-05-22 01:05:53 -07:00
Igor Minar 420f6bfccb docs(CHANGELOG.md): release notes for 1.1.5 and 1.0.7 releases 2013-05-22 01:03:55 -07:00
Anatoly Shikolay ae33e11694 style(*): fix up semicolon and var usage
Conflicts:

	src/ng/animation.js
	src/ng/animator.js
	src/ng/http.js
2013-05-21 14:41:22 -07:00
Lucas Galfasó 4d8b0282b4 test(parse): Test for the parsing not invoking twice to get self
New tests to not call twice a function to get self
2013-05-21 14:41:22 -07:00
Igor Minar 00845fca88 docs(changelog): fix the 1.0.6 header 2013-05-21 14:41:22 -07:00
Joakim Blomskøld 84fe86c7fd docs(Angular.js): add missing @returns to extend() 2013-05-21 21:39:53 +01:00
Matias Niemelä 5e1ed9d5d2 docs(tutorial): fix the float issue with the improve docs button 2013-05-21 14:09:42 +01:00
Ben Ripkens 2ba668732a docs(ngScenario): provide examples for element(...).query(fn)
element(selector, label).query(fn) is a very useful function, yet barely
explained. The developer guide should show how this function can be used
to conditionally execute behavior and assertions.
2013-05-21 13:36:35 +01:00
Jens Rantil 2cb73b71d1 doc($compile): clarify compile function return value
If a compile function (within a directive) returns a function, it is a
post-link function.

Closes: #2713
2013-05-21 13:18:59 +01:00
Jens Rantil 16a2ce2b13 docs(guide/type): remove empty "Type" page in guide
Closes #1316
2013-05-21 13:13:28 +01:00
Igor Minar 18e87a7544 chore(version.js): remove unused/obsolete script 2013-05-21 03:43:10 -07:00
Igor Minar f81431dd72 chore(package.json): kill version.yaml in favor of package.json
all versioning info is now in package.json and that's where the build scripts read it from
2013-05-20 16:48:21 -07:00
Dan Kohn 04bdb9f813 chore(package.json): use devDependencies instead of dependencies 2013-05-20 16:46:11 -07:00
Daniel Tse 1cfe281a76 docs(filters): fix minor typographical error
Fix a typographical error "it's" -> "its" in the dateFilter
documentation
2013-05-20 15:37:14 +01:00
David Holmes 6165bd7d1e doc(guide/compiler): fix grammatical error
"The compilation process happens into two phases." should be "The compilation process happens in two phases."
2013-05-20 10:24:29 +01:00
Misha Moroshko 0135564ad9 doc(filter): remove invalid character 2013-05-20 10:21:28 +01:00
Pete Bacon Darwin 6847cbeff8 docs(guide::testing): fix link to angular-seed 2013-05-18 22:17:28 +01:00
Chris M 84daf33c03 docs(ngMock::$log): improve the $log.*.logs descriptions
Because ngDoc generation only takes the last segment of a property name,
each $log.[error|warn|log...].logs property has the same name and is
confusing in the docs.
This commit helps this by adding a link to the $log.* method and also an
appropriate usage example.
2013-05-18 22:14:20 +01:00
Joakim Blomskøld 86cbdb893a doc(ngModel): $setViewValue calls all parsers, not formatters 2013-05-18 21:18:15 +01:00
Ben Ripkens 11ee680d38 docs(guide): add API documentation for ngScenario matchers
Matchers are briefly mentioned in the e2e test guide, but there is no
documentation for the available matchers.
2013-05-18 21:01:57 +01:00
Andrew Vida 4c5b382b69 docs(tutorial): update test config file name 2013-05-18 20:29:34 +01:00
Jeremy Wilken 39f4a776d6 doc(guide:$location): fix example for two way databinding.
When you are watching the $location.path(), it has to be wrapped in a
function since it is not attached to the scope and if you pass a string
to $scope.$watch it is evaluated against the $scope.
2013-05-17 19:17:28 +01:00
Matt Haggard a250116694 doc(guide): add links to angular-seed examples
The examples in the angular-seed project are better than nothing,
which is what we currently have here!
2013-05-16 22:03:23 +01:00
Dean Sofer 9a73d71f47 docs(ngCsp): add more informative details
Transferred from https://github.com/angular/angular.js/wiki/Using-AngularJS-in-a-Chrome-Extension-environment
2013-05-16 21:28:05 +01:00
jamesBrennan 73aaca05f8 docs(guide:understanding_controllers): remove outdated info
Remove the outdated info in this document related to this API change
https://github.com/angular/angular.js/blob/master/src/ng/rootScope.js#L166
2013-05-15 21:33:30 +01:00
Siddique Hameed a993112098 docs($timeout): minor cleanup
Added a comma separator in the statement
Removed the word the from the statement
Used whose instead of who's in the following statement
Italicized false in the statement
Used a comma separator in the statement
2013-05-14 21:22:04 +01:00
Chirayu Krishnappa 9145d5ec3e fix($browser): should use first value for a cookie.
With this change, $browser.cookies()["foo"] will behave like
docCookies.getItem("foo") where docCookies is defined at
https://developer.mozilla.org/en-US/docs/DOM/document.cookie

This fixes the issue where, if there's a value for the XSRF-TOKEN cookie
value with the path /, then that value is used for all applications in
the domain even if they set path specific values for XSRF-TOKEN.

Closes #2635
2013-05-11 09:28:14 -07:00
willtj efc863844c docs($scope): clarify documentation for $broadcast 2013-05-10 21:24:38 +01:00
veselinn cc260e7864 docs(guide): fix a typo 2013-05-10 20:52:44 +01:00
Lucas Galfasó 42ce8f7f55 fix(ngPluralize): handle the empty string as a valid override
Fix the check for overrides so it is able to handle the empty string

Closes #2575
2013-05-10 20:04:59 +01:00
Alfred Nutile 661390aef3 docs(guide): fix typo on model name 2013-05-10 14:58:15 +01:00
Pete Bacon Darwin ed4a70e765 docs(Angular.js): move forEach docs to correct position 2013-05-09 22:15:22 +01:00
Pete Bacon Darwin 1866968310 docs(tutorial): add comment about injection annotation
Closes: #1163
2013-05-09 13:58:02 +01:00
Igor Minar 5fbf98ec23 chore(docs): use done() in gen-docs.js 2013-05-09 05:23:39 -07:00
Igor Minar 5d2bb2c1b9 test(sortedHtml): ignore bogus rowspan=1 and colspan=1 in IE 2013-05-09 05:23:39 -07:00
Igor Minar 9039ddbb56 test(sortedHtml): fix comment support in sortedHtml helper 2013-05-09 05:23:39 -07:00
Igor Minar 8f8510fc22 style($compile): clarify argument name 2013-05-09 05:23:39 -07:00
Pete Bacon Darwin 1e99ea6a51 docs($window): fix example 2013-05-09 13:02:30 +01:00
R. Merkert 016e1e675e fix(angular): do not copy $$hashKey in copy/extend functions.
Copying the $$hashKey as part of copy/extend operations makes little
sense since hashkey is used primarily as an object id, especially in
the context of the ngRepeat directive. This change maintains the
existing $$hashKey of an object that is being copied into (likewise for
extend).
It is not uncommon to take an item in a collection, copy it,
and then append it to the collection. By copying the $$hashKey, this
leads to duplicate object errors with the current ngRepeat.

Closes #1875
2013-05-08 13:04:08 +01:00
Illniyar 1240641f76 feat($cookieStore): $cookieStore.get now parses blank string as blank string
closes #1918
2013-05-08 10:07:24 +01:00
Chad Smith f1a34f0908 fix(select): ensure empty option is not lost in IE9
Fix a check inside render for select elements with ngOptions, which
compares the selected property of an element with it's desired state.
Ensure the placeholder, if available, is explicitly selected if the model
value can not be found in the option list.
Without these fixes it's up to the browser implementation to decide which
option to choose. In most browsers, this has the effect of displaying the
first item in the list. In IE9 however, this causes the select to display
nothing.

Closes #2150, #1826
2013-05-07 21:29:44 +01:00
Pete Bacon Darwin 01bda54e05 fix(dateFilter): correctly format ISODates on Android<=2.1
In older Android browsers, `undefined` does not act like `0` in some
arithmetic operations. This leads to dates being formatted with `NaN`
strings in the dateFilter because the implementation of the `dateGetter`
function allows offset to be an optional parameter.
The fix is to convert offset to 0 if it is undefined.

Closes #2277, #2275
2013-05-07 11:44:46 +01:00
Hamish Macpherson bc04afe183 doc(input): fix small typo in code example 2013-05-07 09:48:59 +01:00
quazzie ac086ae616 fix($location): back-button should fire $locationChangeStart
Before $locationChangeStart event is not broadcast when pressing the back-button on the browser.

Closes #2109
2013-05-01 14:51:05 +01:00
Siddique Hameed f75a2b093f docs(injector): fix typo
Closes: #2551
2013-05-01 13:15:17 +01:00
Chris Nicola 4dba7b0203 docs(guide:directive): add directive controller usage
Specifically adding a directive controller to the example definition
and how to use declare injectables to avoid minification errors.
2013-04-30 10:53:17 +01:00
Robin Böhm d3cd3c0a9b style($injector): add a comment to explain the distinction with isArray 2013-04-30 10:40:19 +01:00
Eugene Wolfson e351874a0a docs($provide): fix parentheses in example 2013-04-30 10:17:01 +01:00
Lucas Galfasó dcdf4fc78b fix(parse): fix context access and double function call
Fix a context duplication and invocation to a previous context when
doing an access modifier function on the result of a function
Currently, when doing `foo().bar()`, `foo` is called twice, the first
time to get the context and the second one for `bar` to get the
underlying object. Then the call to `bar` is called using the second
instance as self
This is equivalent to doing:
```
var instance1 = foo();
var instance2 = foo();
instance2.bar.apply(instance1);
```

Closes #2496
2013-04-29 23:02:51 +01:00
Matias Niemelä cf38d8c55b feat(ngdocs): support for HTML table generation from docs code 2013-04-29 17:47:53 -04:00
gockxml b0233a33a1 fix(jqLite): correct implementation of mouseenter/mouseleave event
Implement mouseenter/mouseleave event referring to
http://www.quirksmode.org/js/events_mouse.html#link8 and jQuery source
code(not dependent on jQuery).
The old implementation is wrong. When moving mouse from a parent element
into a child element, it would trigger mouseleave event, which should not.
And the old test about mouseenter/mouseleave is wrong too. It just
triggers mouseover and mouseout events, cannot describe the process of mouse
moving from one element to another element, which is important for
mouseenter/mouseleave.

Closes #2131, #1811
2013-04-29 18:28:29 +01:00
Oren Avissar c3235db9ee test(browser/compile): fix calls to Jasmine fail()
The fail() function in Jasmine expects an Error object parameter.
Also, there is no global alias for fail() so it must be accessed using
`this.fail(new Error())`.
2013-04-29 16:57:33 +01:00
Robin Böhm 738113bac8 refact(ngClass): improve performance through bitwise operations
Change modulo % 2 operations to bitwise & 1
Read about this in Nicholas C. Zakas book "High Performance JavaScript"(ISBN: 978-0-596-80279-0)
Use the Fast Parts --> Bitwise Operators --> Page 156++
Proven at http://jsperf.com/modulo-vs-bitwise/11
2013-04-29 10:19:32 +01:00
Jamie R. Rytlewski 6613ee40e6 docs($q): fix typo 2013-04-28 18:45:01 +01:00
Anton ce6035d953 docs(contribute): add Java as dependency
Current build process leverages closure jar for javascript minification.
If Java is not installed and included in the PATH the build will fail.
2013-04-28 18:37:45 +01:00
Paulo Ávila 2bc4793ee8 docs(filter): improve syntax for usage in templates 2013-04-24 21:57:48 +01:00
Jeff Pickelman 9c6e34bfc1 docs(di): fix typos and grammar 2013-04-24 20:52:59 +02:00
Timothy Ahong 4e65ff31a8 docs(guide:unit-testing): add an example unit test for directives 2013-04-23 13:23:16 +01:00
Pete Bacon Darwin 15461c7883 docs(compiler): don't drag selected content
In the example with draggable, the mouseDown handler needs to start with an event.preventDefault(). Otherwise the following bug occurs:
1) Select the text of the draggable span by clicking outside the span and dragging the mouse to the left or right through the span. Release the mouse button.
2) Now click on the span's inner text, and start to Drag it. The browser's default functionality that drags highlighted text so that it can be pasted into something else (say a document in a text editor) is invoked.
3) Release the mouse button. Now suddenly, you'll be dragging the span. But you won't be able to place it down on the page. It'll just follow the mouse around until the page is refreshed.

Closes: #2465
2013-04-22 13:38:49 +01:00
Keir Mierle de5352cfcf docs(compiler): fix variable scope in drag sample
Note that without this fix, if you add a second draggable element, the
two instances clobber each other since there is only one set of
startx/starty/x/y variables.
Here is an example: http://plnkr.co/edit/aGrLXcIo2SuaePuAdfmQ?p=preview.
On the surface it looks like it would be fine because you only have one
mouse but in practice the start position jumps when you start dragging.
Here it is fixed: http://plnkr.co/edit/VuvPasuumtCeiVRisYKQ?p=preview
2013-04-22 12:52:43 +01:00
Keir Mierle ae26ed994e docs(forms): fix formatting 2013-04-22 12:38:58 +01:00
Ron Yang 94745f6274 docs(forms): fix typo 2013-04-22 12:35:05 +01:00
Paulo Ávila dbfa0d88bb docs(guide): minor grammatical change 2013-04-21 20:06:29 +02:00
Pete Bacon Darwin cf3b5cb2fc chore(ngDoc): fix a typo with IE warning 2013-04-19 22:08:07 +01:00
Merrick Christensen 192a225854 docs(concepts): fix spelling error 2013-04-19 14:44:44 +01:00
Jared Beck 3508f76719 docs(overview): correct the input validation example
The documentation says that the input should be red if you enter
invalid values or leave it blank. Because the type="integer" is not
supported this does not happen in practice.  This fix changes the
input type to number and adds an ng-pattern to ensure that the number
is an integer.
2013-04-19 14:40:39 +01:00
leesei a7d081fac0 docs(input): fix typo on max attribute 2013-04-19 13:43:37 +01:00
Shyam Seshadri ee774f6e5b docs(select): fix attribute documentation
Select documentation was still referring to binding to name, when it should be ng-model instead. Fixed it.
2013-04-19 13:37:04 +01:00
Michal Reichert 80f34598f8 docs(ngBind): fix typo 2013-04-19 11:58:52 +01:00
Pete Bacon Darwin 7e168c8ad2 fix(i18n): escape all chars above \u007f in locale files
Modify the script that writes the locales so all characters above \u007f are escaped
Includes the updated locale files after running the closureI18nExtractor.

Closes #2417
2013-04-17 22:16:57 +01:00
Mark Dalgleish 3ebc2c2442 fix(ngModel): use paste/cut events in IE to support context menu
In IE the model is not updated when the input value is modified using the context
menu, e.g. pasting from the clipboard, or cutting all or part of the current value.
To capture these changes, we bind to the proprietary 'paste' and 'cut' events.

Closes #1462
2013-04-17 21:50:07 +01:00
es128 631d86f723 doc(ngClassEven): make consistent with ngClassOdd 2013-04-17 14:52:24 +01:00
@fbiville 3ac97f2b3d docs(directive guide) typo in compile/link section
The code snippet shows `{{action.description}}`, the explanation referred to it as `{{action.descriptions}}`.
2013-04-17 14:49:55 +01:00
@fbiville ed55346be7 docs(injector): fix typo in inlining example
The actual invoke call in the documentation was referring to the non-existent tempFn instead of tmpFn
2013-04-17 14:46:53 +01:00
Timothy Ahong e31ec1f7ed docs(guide.unit-testing): fix typo 2013-04-16 21:06:10 +01:00
Francesc Rosàs 70e4fd2865 docs($q): fix incorrect @returns tag for $q.when() 2013-04-16 13:38:11 +01:00
Pete Bacon Darwin 7898490779 fix(ngClass): should remove classes when object is the same but property has changed
If you wire up ngClass directly to an object on the scope, e.g. ng-class="myClasses",
where scope.myClasses = { 'classA': true, 'classB': false },
there was a bug that changing scope.myClasses.classA = false, was not being picked
up and classA was not being removed from the element's CSS classes.

This fix uses angular.equals for the comparison and ensures that oldVal is a copy of
(rather than a reference to) the newVal.
2013-04-16 13:22:37 +01:00
Pete Bacon Darwin 0893e83c92 fix(Grunt): also remove \r chars when joining files 2013-04-16 13:14:09 +01:00
Pete Bacon Darwin ef334d0070 docs(tutorial): testacular renamed to karma
Replaced instances of 'Testacular' with 'Karma' to reflect name change of test runner.
Replaced instances of 'http://vojtajina.github.com/testacular' with 'http://karma-runner.github.io/' to reflect dedicated page for Karma Test Runner.
Added location of config file needed to start the Karma server. This is still labeled 'testacular.conf.js' and needs file name to be updated in the phone example repo.
2013-04-15 12:30:33 +01:00
Pete Bacon Darwin 9f08d03978 docs(rootScope): fix typo 2013-04-15 11:46:21 +01:00
Laurent 3ca6c4bfb9 docs(rootScope): Fix various typos 2013-04-15 11:46:21 +01:00
Laurent cfea2095ca docs(Angular.js): fix typo 2013-04-15 11:46:21 +01:00
Pete Bacon Darwin 171bec3b0e doc(overview): add link to angular demo slides to overview 2013-04-15 11:23:00 +01:00
brandonjp 93891ad2e9 docs(ngController): fix docs link to api/ng.$route 2013-04-13 18:26:07 +02:00
Seunghoon Yeon eece726651 docs(module): fix typo 2013-04-13 18:17:04 +02:00
uberspeck dc6665caed docs(faq): added note to FAQ re: legacy IE support 2013-04-12 16:00:53 -07:00
Dave Geddes 5b592cbaf4 chore(Grunt) update grunt-contrib-copy
grunt-contrib-copy@0.4.1 has the cleaner summary output by default
2013-04-11 16:31:05 -07:00
Lee Leathers 348138d7cd style(exceptionHandler): add ws 2013-04-11 15:32:32 -07:00
Lee Leathers 6a34a4ebeb chore(NPM): Add license info 2013-04-11 15:32:31 -07:00
Prathan Thananart 5ca247c749 docs(guide): Update $locationProvider docs.
Default hashPrefix setting is not `'!'`, it's actually `""`.
Source: https://github.com/angular/angular.js/blob/master/src/ng/location.js#L472
2013-04-11 15:29:24 -07:00
kamagatos b16bffbf76 docs(guide/i18n): fix a typo 2013-04-11 15:22:25 -07:00
Christoph Burgdorf b2aec3706d docs(jqLite): clarified that children/parent do not support selectors 2013-04-11 15:11:51 -07:00
Matt Haggard d577c5def1 docs: fix typos 2013-04-11 15:05:16 -07:00
玉黍 a4dd14952e set ng-app as personalLog 2013-04-11 15:00:54 -07:00
Brent Morrow 8879b3733e docs(ngApp): fixed typo
Use this directive to auto-bootstrap **an** application.
2013-04-11 14:59:30 -07:00
Brent Morrow 35b02226ca docs(guide/concepts): fix typo
An event is a user **interaction**, timer event, or network event (response from a server).
2013-04-11 14:57:03 -07:00
Brent Morrow 814feaa2ab docs(guide/concepts): wording change
... or when working with --> a <-- third-party library callbacks.
... or when working with third-party library callbacks.
2013-04-11 14:55:31 -07:00
{Qingping,Dave} Hou aa2e66dcaf docs(guide): Added $ sign to controller example 2013-04-11 14:33:21 -07:00
urenmj 7b7b12e477 docs(dev-guide): Fixed a typo. 2013-04-11 14:19:18 -07:00
Artur Ostrega 187cd0a058 docs(http): spelling, grammar, capitalization, etc.
Conflicts:
	src/ng/http.js
2013-04-11 14:09:12 -07:00
Brent Morrow 0c690af2fe docs(guide/concepts): wording change 2013-04-11 14:07:59 -07:00
Brent Morrow 40ecd2d8e5 docs(guide/expression): wording changes 2013-04-11 14:05:08 -07:00
Luc Morin 484286d536 docs(guide/directives): give more details about directive declaration 2013-04-11 14:02:06 -07:00
Colin Kahn d56b62dcda docs(guide/filters): document multiple arguments syntax
Add example of using a filter with that accepts multiple arguments.
2013-04-11 13:55:47 -07:00
Brent Morrow b94125ac14 docs(angular-mocks): fix wording 2013-04-11 13:52:02 -07:00
Brent Morrow 3f34319398 docs($inject): wording change 2013-04-11 13:48:31 -07:00
David Sanders ba076a29b9 docs($compile): improve docs 2013-04-11 13:06:56 -07:00
Brian Campbell 13000c7350 docs(guide): updates for legacy IE7 support
- note re: id="ng-app" to bootstrap/IE partials
- added doctype/xmlns to markup
- add cond comment re: json2/3 to markup
2013-04-11 13:00:41 -07:00
Igor Minar fd2649fc65 chore(release): start 1.0.7 monochromatic-rainbow iteration 2013-04-11 12:55:32 -07:00
Chad Whitacre 437b09c155 docs($http): fix a typo 2013-04-11 12:50:26 -07:00
Takashi Matsuo b2b015a53b chore(docs): Fixed incomplete merge 2013-04-11 10:28:10 -07:00
Heath Matlock 5bea4c5692 docs(concespts): correct spelling and remove unnecessary word 2013-04-06 23:08:52 +02:00
Igor Minar 1b527b7acf docs(changelog): add release notes for 1.1.4 and 1.0.6 2013-04-04 12:15:42 -07:00
Igor Minar 4b8629b6b8 chore(release): cut 1.0.6 universal-irreversibility release 2013-04-04 10:48:05 -07:00
Misko Hevery ed81d19ce9 chore(docs): correct few unclosed elements
Conflicts:

	src/ng/filter/filter.js
2013-04-04 09:46:46 -07:00
Felipe Lahti 3497bf2d82 docs(guide): add missing closing div tag 2013-04-04 09:43:47 -07:00
Felipe Lahti afcf03fd2c docs(guide): fix typo in DI. angualar -> angular 2013-04-04 09:43:35 -07:00
Gert Goet 582612b000 docs(mocks): fix typos
Conflicts:

	src/ngMock/angular-mocks.js
2013-04-04 09:43:16 -07:00
Srinivas Kusunam 7bf32ccadb docs(directive): fix typo 2013-04-04 09:42:12 -07:00
Matthew McComb f5c18861b6 docs(controller): improve $controller function doc readability
Improved $controller function doc readability.
2013-04-04 09:42:01 -07:00
Misko Hevery 4acd75b904 fix(mock): prevent NPE when module definition outside of it. 2013-04-04 09:30:07 -07:00
James deBoer cd6dd22b19 Update forms.ngdoc
docs(forms): Fixed a typo. render -> $render
2013-04-04 09:29:51 -07:00
Chirayu Krishnappa 139c532019 chore($ngLocale): refactor slurper & parse extended datetime symbols 2013-04-04 09:28:23 -07:00
Chirayu Krishnappa e5b57bf01c chore($ngLocale): generate ngLocale files from the Closure code (includes datetimesymbolsext.js) 2013-04-04 09:00:36 -07:00
Mark Chapman 5ecd6d4e0a refactor(ngRepeat): make use of declared variable
Rename unused arrayLength variable to arrayBound and use it inside loop
2013-04-04 08:59:19 -07:00
Igor Minar 03bbe9aab1 docs($resource): improve installation section 2013-04-04 08:57:14 -07:00
Ciro Nunes 0ef9d54ccd docs($resource): Added an installation section. 2013-04-04 08:54:45 -07:00
Igor Minar 6ade77efa2 chore(karma): upgrade karma to 0.8.4
we needed this upgrade to disable animations in scenario runner
(karma ships with its own copy of angular-scenario.js which
got update in 0.8.4)
2013-04-03 18:22:31 -07:00
Vojta Jina 91fa865bf2 chore: use Karma 2013-04-03 18:22:03 -07:00
Igor Minar 10ae76673c docs(ngSwitch): improve the @usage example 2013-04-01 21:35:02 -07:00
Arlen Christian Mart Cuss 9497757842 chore(select): Fix ngOptions regexp capture comment.
Off-by-one error.
2013-03-20 11:45:42 -07:00
Javier Mendiara Cañardo bb5abe0e9c chore(Angular): remove superfluous fromCharCode function
Remove fromCharCode function as it was used only in two inner
functions in the code, and its functionality is achieved in several
other places by using String.fromCharCode

Breaks fromCharCode closure function, String.fromCharCode should be
used instead
2013-03-20 11:41:14 -07:00
Bruno Coelho 76c0ddfc0b docs(filter): Using indefinite article
This doc was using both definite article and indefinite article at the same time.
2013-03-20 11:41:14 -07:00
Arlen Christian Mart Cuss 36b888e781 docs(directive): Fix entity confusion in example. 2013-03-20 11:41:14 -07:00
Manuel Braun a476972e2e fix($location): parse FirefoxOS packaged app urls
FirefoxOS uses special URLs like
app://{d0419af1-8b42-41c5-96f4-ef4179e52315}/index.html for packaged Apps.

Closes #2112
2013-03-15 21:19:58 -07:00
Jamie Mason 866d3fb573 $routeChangeSuccess documentation
I hope this helps someone, I ran into some issues when following the API as described - handlers of this event receive 3 arguments, not 2.

Although this is mentioned [elsewhere](http://docs.angularjs.org/api/ng.$rootScope.Scope#$on) it's not clear when viewing the docs for this behaviour in isolation. 

The first argument is an Event Object, not the current route. The previous route argument can also be omitted on occasions.
2013-03-15 21:02:14 -07:00
Shyam Seshadri 70cf0a389f feat(docs): Add Improve this doc link in each doc page, which links to the edit mode of that file in github 2013-03-15 20:56:22 -07:00
Sujeet Pillai 7d4ccea579 fix(timezone): correct timezone date filter for 1/2 hour offsets 2013-03-14 22:18:20 -07:00
Shyam Seshadri 654dd1d5e8 Fix failing test in IE 10 2013-03-14 22:04:06 -07:00
Arlen Christian Mart Cuss bf114f6ee3 docs($injector): correct misuse of $inject
$inject was used where $injector was appropriate; confusing and
misleading.
2013-03-12 13:00:46 -07:00
Igor Minar 5727eaf767 chore(Gruntfile): run webserver on 0.0.0.0
... so that we can access it from local VMs.

The security risk of doing this is very low since only the current
working directory is being made accessible to everyone. There is also
an option to run a local firewall, which is a better way to secure the
developer's machine anyway.
2013-03-11 15:27:35 -07:00
Thibault Leruitte 346e98330c fix($location): correctly rewrite html5 url to hashbang url
In situations where path() matched basepath and we needed to
convert from html5 url to hashbang url, the $location service
considered the url to be already rewritten, which resulted in
an error.
2013-03-11 15:27:31 -07:00
Christian Vuerings 2b1f10266a docs(ngCloak): update the CSS rule with data-ng-cloak 2013-03-08 17:26:07 -08:00
Chirayu Krishnappa fc7970fdf0 chore($ngLocale): Generate ngLocale files from the Closure code. 2013-03-08 17:00:03 -08:00
Jason Morrison 65957e99ba docs($injector): remove extranneous 'the' from injector docs 2013-03-08 23:49:03 +01:00
Niel de la Rouviere 7f9a94f8bc docs(directive): minor typo fix
Changed "obeject" to "object"
2013-03-08 23:30:00 +01:00
Igor Minar cb560e2441 test($route): add tests for matching 'otherwise' routes 2013-03-08 12:01:09 -08:00
Igor Minar 55856565c2 fix($route): make nextRoute.$route private
the `nextRoute` object available in `$routeChangeStart` handler
accidentaly leaked  property which pointed to the route definition
currently being matched.

this was done just for the internal needs of the `$route` implementation
and was never documented as public api.

Some confusion arouse around why the $route property was not always
available on the `nextRoute` object (see #1907). The right thing for us
to do is to prefix the property with $$ for now and refactor the code
to remove the property completely in the future. Application developers
should use the `nextRoute` object itself rather than its `$route` property.
The main diff is that nextRoute inherits from the object referenced by $route.

BREAKING CHANGE: in $routeChangeStart event, nextRoute.$route property is gone.

Use the nextRoute object instead of nextRoute.$route.

Closes #1907
2013-03-08 12:01:05 -08:00
Julie 13968343d4 feat(angular.bootstrap): support deferred bootstrap
This features enables tools like Batarang and test runners to
hook into angular's bootstrap process and sneak in more modules
into the DI registry which can replace or augment DI services for
the purpose of instrumentation or mocking out heavy dependencies.

If window.name contains prefix NG_DEFER_BOOTSTRAP! when
angular.bootstrap is called, the bootstrap process will be paused
until angular.resumeBootstrap is called.

angular.resumeBootstrap takes an optional array of modules that
should be added to the original list of modules that the app was
about to be bootstrapped with.

Conflicts:

	src/Angular.js
2013-03-06 16:25:21 -08:00
Dave Geddes 4c428121b9 docs(contribute): add note about running command line as admin on win 2013-03-06 14:55:42 -08:00
Igor Minar 4816f7ee5c chore(Grunt): include dot files in the final zip 2013-03-06 14:23:05 -08:00
Dave Geddes ce53fbde50 chore(Grunt): don't remove root dir from zip 2013-03-06 13:20:54 -08:00
Igor Minar 1516a69cd2 docs($http): add more info about transform function 2013-03-06 11:20:49 -08:00
Dave Geddes 7a77fdae4f chore(Grunt): switch from Rake to Grunt
Migrates the Angular project from Rake to Grunt.

Benefits:
- Drops Ruby dependency
- Lowers barrier to entry for contributions from JavaScript ninjas
- Simplifies the Angular project setup and build process
- Adopts industry-standard tools specific to JavaScript projects
- Support building angular.js on Windows platform (really?!? why?!?)

BREAKING CHANGE: Rake is completely replaced by Grunt. Below are the deprecated Rake tasks and their Grunt equivalents:

rake --> grunt
rake package --> grunt package
rake init --> N/A
rake clean --> grunt clean
rake concat_scenario --> grunt build:scenario
rake concat --> grunt build
rake concat_scenario --> grunt build:scenario
rake minify --> grunt minify
rake version --> grunt write:version
rake docs --> grunt docs
rake webserver --> grunt webserver
rake test --> grunt test
rake test:unit --> grunt test:unit
rake test:<jqlite|jquery|modules|e2e> --> grunt test:<jqlite|jquery|modules|end2end|e2e>
rake test[Firefox+Safari] --> grunt test --browsers Firefox,Safari
rake test[Safari] --> grunt test --browsers Safari
rake autotest --> grunt autotest

NOTES:
* For convenience grunt test:e2e starts a webserver for you, while grunt test:end2end doesn't.
  Use grunt test:end2end if you already have the webserver running.
* Removes duplicate entry for Describe.js in the angularScenario section of angularFiles.js
* Updates docs/src/gen-docs.js to use #done intead of the deprecated #end
* Uses grunt-contrib-connect instead of lib/nodeserver (removed)
* Removes nodeserver.sh, travis now uses grunt webserver
* Built and minified files are identical to Rake's output, with the exception of one less
  character for git revisions (using --short) and a couple minor whitespace differences

Closes #199

Conflicts:

	Rakefile
2013-03-05 23:35:13 -08:00
Andrew McLeod b13da18e11 fix($http): don't encode URL query substring "null" to "+"
Fixes issue in encodeUriQuery used by $http and $resource that
treats null as a string and replaces the characters "null" with "+".
2013-02-26 17:29:08 -08:00
Matt Ginzton f98f8a3892 docs(ngMock): fix minor typo in comment
Change "constroctor" to "constructor".
2013-02-25 23:55:54 -08:00
danilsomsikov 77c4a7fd66 fix($compile): compile replace directives in external template
Passing DOMNode#childNodes to compileNodes when compiling remote
template, so that directives with replace:true can be compiled.
The previous version used jqLite#contents which returned collection
that was not updated during the compilation.

Closes #1859
2013-02-25 21:45:44 -08:00
Igor Minar e281413919 chore(sortedHtml): print attributes with empty value
I had to also fix some tests as they started failing on IE8.

We should figure out why these extra attributes are set in IE8,
but I'm too tired of IE to worry about it now. Since I'm
not introducing this issue just making it visible, I'm going
to commit this as is.
2013-02-25 21:45:39 -08:00
Vineet Kumar 2007ddd3f8 docs(guide/directives): update obsolete doc reference
Replace an obsolete reference to a nonexistent "Creating Widgets"
section with a real link to "Creating Components".
2013-02-25 14:51:59 -08:00
Pawel Kozlowski d8922fe3e9 docs(dateFilter): properly specify range for the Z format modifier
Closes #1533
2013-02-25 13:51:38 -08:00
Igor Minar 6c611df8f0 fix($compile): whitelist file:// in url sanitization 2013-02-25 10:02:50 -08:00
Steven Davidson 6be24df5bc chore(nodeserver): fix log message for 301 response 2013-02-23 23:44:46 -08:00
Igor Minar 4759aacba9 fix($compile): handle elements with no childNodes property
see the test for more details
2013-02-23 23:40:03 -08:00
Igor Minar 802bfc259c chore(release): start 1.0.6 universal-irreversibility iteration 2013-02-23 21:11:14 -08:00
Igor Minar 64db8d166e docs(changelog): fix release notes 2013-02-20 15:44:09 -08:00
Igor Minar d2a769e196 chore(release): cut the 1.0.5 flatulent-propulsion release 2013-02-20 12:58:02 -08:00
Igor Minar 68a8c8907d docs(changelog): add release notes for 1.0.5 and 1.1.3 2013-02-20 12:57:08 -08:00
Igor Minar 701d61080a chore(matchers): fix hasBeenCalledOnceWith matcher
the error message was wrong and misleading
2013-02-20 08:44:53 -08:00
Igor Minar a8cc449706 fix($compile): sanitize values bound to a[href] 2013-02-20 00:40:51 -08:00
Per Rovegård 2aa212b19c fix(ngClass): keep track of old ngClass value manually
ngClassWatchAction, when called as a $watch function, gets the wrong old
value after it has been invoked previously due to observation of the
interpolated class attribute. As a result it doesn't remove classes
properly. Keeping track of the old value manually seems to fix this.

Closes #1637
2013-02-18 20:35:40 -08:00
Pete Bacon Darwin 1f23cfe9c7 fix(compile): should not leak memory when there are top level empty text nodes
The change to prevent <span> elements being wrapped around empty text nodes caused these empty text nodes to have scopes and controllers attached, through jqLite.data() calls, which led to memory leaks and errors in IE8.
Now we exclude all but document nodes and elements from having jqLite.data() set both in the compiler and in ng-view.

Fixes: #1968 and #1876
2013-02-18 13:04:24 +00:00
Will Moore 0fa8e47fb5 fix($httpBackend): patch for Firefox bug w/ CORS and response headers
A workaround for https://bugzilla.mozilla.org/show_bug.cgi?id=608735
In FF getAllResponseHeaders() returns null if the request is the result of CORS.

Tried to format the code so that when a FF patch is released and gains enough
traction it can easily be selected and deleted. Heavily inspired by jQuery's
patch for the same bug. This patch falls short of passing through custom headers
but covers all of the "simple response headers" in the spec at
http://www.w3.org/TR/cors/

This commit should get reverted once Firefox 21 gets out.

Closes #1468

Conflicts:
	src/ng/httpBackend.js
2013-02-14 16:52:02 -08:00
Igor Minar 8043784fd7 fix(a): workaround IE bug affecting mailto urls
Apparently there is a really weird bug in IE6-8 that causes anchor textContent
to be reset with href content when both contain @ symbol.

Inserting a bogus comment node into all anchor elements in IE works around this
browser bug.

I'm fixing the issue via directive because that way we'll fix it for jQuery as
well.

I fixed an e2e test too because it was incorrect.

Closes #1949
2013-02-14 16:43:28 -08:00
Igor Minar 526a6b31e5 fix(*): don't use instanceof to detect arrays
this breaks when multiple javascript contexts are involved - like in node-webkit

see original PR: #1966

Closes #1966
2013-02-14 16:40:58 -08:00
Cedric Soulas 14fd064a62 docs($resource): fix bad indentation producing a code block 2013-02-14 15:45:37 -08:00
Ewen Cumming 3178afbf0c docs($rootScope): rearrange event listener docs 2013-02-14 15:42:51 -08:00
deboer ce3b616432 fix(ngSwitch): make ngSwitch compatible with controller BC module
add a $scope to the ngSwitch's controller to fool the controller
BC (backwards compatibility) module used by DFA.
2013-02-14 15:38:20 -08:00
Vineet Kumar 54a761905d docs($q): fix a few typos 2013-02-14 15:19:49 -08:00
Dylan Pyle aa531d7bd1 docs(guide): fix some invalid javascript in directive documentation
Use double quotes to maintain consistency with other HTML
2013-02-14 15:15:06 -08:00
Daniel Luz d7e9ae1215 fix($rootScope): minor typo fixes 2013-02-14 14:43:32 -08:00
Daniel Luz 6cf9ede88e docs($parse): document function argument types, fix minor typo 2013-02-14 14:43:32 -08:00
Trotter Cashion 6092291bd7 chore(reakefile): auto install npm packages 2013-02-14 14:43:31 -08:00
Shyam Seshadri 3d0f11212f fix(compiler): Allow startingTag method to handle text / comment nodes 2013-02-14 14:43:31 -08:00
Fredrik Bonander 6194e002e2 fix(resource): Update RegExp to allow urlParams with out leading slash
Will allow reoucese to be loaded from a relative path
Example:
var R = $resource(':path');
R.get({ path : 'data.json' });

Example usage:
Load resources in applications not using webserver, ie local webapp in
on a tablet.
2013-02-14 14:43:31 -08:00
Kury Kruitbosch 75545d4d1c fix(numberFilter): fix formatting when "0" passed as fractionSize
When checking to add decimal and trialing 0s number filter used to check
trueness of fractionSize. "0" evaluating to true causes "123" to return "123."
2013-02-14 13:46:07 -08:00
Jesse Cooke d67eb2f2db docs(guide): Fix typos in concepts/model,view. 2013-02-14 13:09:40 -08:00
Igor Minar 6b8153ff0f chore(Rakefile): parallelize the build on Travis
now that the forking issue is solved we can run regular build there

https://github.com/travis-ci/travis-ci/issues/845
2013-02-14 12:52:20 -08:00
Cedric Soulas fb132732f1 docs($resource): fix missing punctuation 2013-02-14 12:14:13 -08:00
Igor Minar 336b157497 test(angular.copy): add tests for scenarios when target is missing 2013-02-11 22:10:58 -08:00
Igor Minar d16975a9de revert: refactor(angular.copy): use slice(0) to clone arrays
This reverts commit a5b3bcf41c.

slice(0) doesn't perform deep copy of the array so its unsuitable
for our purposes.
2013-02-11 22:01:15 -08:00
Igor Minar 87f6b36bab chore(docs): improve docs parser type
previously we barfed on function type definition with optional arguments
like {function(number=)}

this fixes it

I also added a bunch of code that helps to debug incorrectly parsed docs.
2013-02-11 14:08:27 -08:00
Igor Minar 43fccf5617 refactor(angular.copy): use array.length=0 to empty arrays 2013-02-11 14:07:57 -08:00
Igor Minar a5b3bcf41c refactor(angular.copy): use slice(0) to clone arrays
slice(0) is way faster on most browsers
2013-02-11 14:07:10 -08:00
Igor Minar 8801d9c286 fix(angular.forEach): correctly iterate over objects with length prop
Should handle JQLite, jQuery, NodeList and other objects like arrays
but not other generic objects or instances of user defined types
with length property.

Closes #1840
2013-02-11 12:46:13 -08:00
radu a8e114f351 docs($q): fix typos 2013-02-07 04:16:49 -08:00
Julie 9a3a9b46e5 fix(scenario): include error messages in XML output
Fix the XML output of scenario tests so that it properly includes error
messages from failing specs.
2013-02-07 04:10:17 -08:00
Enrique Paredes 934204ec18 fix($compile): rename $compileNote to compileNode
Directives was observing different instances of Attributes than the one
that interpolation was registered with because we failed to realize
that the compile node and link node were the same (one of them
was a wrapper rather than raw node)

Closes #1941
2013-02-07 02:49:18 -08:00
Fredrik Bonander 7cb8f8fb44 fix($cookies): set cookies on Safari&IE when base[href] is undefined
Safari and IE don't like being told to store cookies with path set to
undefined. This change ensures that if base[href] (from which cookie path
is derived) is undefined then the cookie path defaults to ''.

The test verifies that the cookie is set instead of checking that cookie has correct path,
this is due to that cookie meta information is not avabile once the cookie is set.

Closes #1190, #1191
2013-02-07 02:36:52 -08:00
Philip Roberts 8d34bf2fea fix(date): invert timezone sign and always display sign
This commit fixes #1261 and #1532. This covers
two separate issues:

- Positive timezones were being formatted without
a leading `+` resulting in a formatting string
like: "HH:MM:ssZ" giving "12:13:141000" instead
of "12:13:14+1000". Fixed by checking if timezone
is > 0 and adding a leading "+".

- Timezone output signs were inverted.
mock.TzDate expects the timezone _offset_ as it's
first argument, _not_ the timezone. This means
that a mock.TzDate with a positive offset should
result in a date string with a negative timezone,
and vice-versa.

Closes #1261, #1532
2013-02-07 01:47:19 -08:00
Igor Minar 8801e69dba docs(guide): remove stale info about filters changing DOM
as of v0.10.6 this is not the case any more
2013-02-06 14:15:43 -08:00
Thomas Schultz f4afa398a1 docs(tutorial): remove extra back-tick character 2013-02-06 22:22:55 +01:00
theotheo 32063278bd docs(module): fix code example 2013-02-06 21:36:21 +01:00
radu 92208d2f85 docs(ngApp): fix typo 2013-02-05 22:14:43 +01:00
Igor Minar ab7c74b4b9 docs(contributing): add CLA anchor for deeplinking 2013-02-04 09:38:55 -08:00
PowerKiKi e283abe171 docs(ngClass): fix typo in description 2013-02-04 10:37:19 +00:00
Brian Ford d7620f68bb feat(Scope): expose transcluded and isolate scope info for batarang
test($compile): add test for exposing transclude and isolate scope info to batarang
2013-01-30 10:44:35 -05:00
Dean Sofer 971d97e2ec docs($cookies): added example to $cookies api docs
Better than nothing.
2013-01-29 16:17:12 -08:00
radu 559d5efc04 docs(nextUid): fix typo
Update src/Angular.js

removed redundant 'the' from nextUid()'s ngdoc
2013-01-29 15:50:03 -08:00
radu 85042820fb docs(tutorial): fix typo
Update docs/content/tutorial/step_00.ngdoc

removed redundant verb
2013-01-29 15:47:43 -08:00
Fred Sauer 24a2eec815 docs(Scope): fix argument docs for $on 2013-01-29 15:39:10 -08:00
metaweta d987a79ab1 test(ngBindHtml): prevent variable name leak
Add "var" so element is local instead of global

Strict mode doesn't allow undeclared global vars, and these really should be local anyway.
2013-01-29 15:35:03 -08:00
metaweta eba09353e6 refactor(Angular.js): prevent Error variable name leak in tests
Remove var Error = window.Error

window.Error is a read-only property in Apps Script.

Igor says, "we should just delete that line instead. I think it was
misko's attempt to get better closure minification, but it turns out
that it's actually hurting us after gzip (I verified it)."
2013-01-29 15:35:03 -08:00
Igor Minar 297660c9a3 chore(release): start 1.0.5 flatulent-propulsion iteration 2013-01-29 15:34:04 -08:00
Fred Sauer 8343c05fd8 docs(a): escape sample code in ng a directive 2013-01-26 23:03:40 +01:00
Igor Minar 7c3d064786 fix(docs): properly generate angular.js urls in doc examples 2013-01-24 11:36:42 -08:00
Igor Minar c2ccc1cbdf docs(date): add missing doc about TZ behavior 2013-01-24 10:51:47 -08:00
Igor Minar 04e080660a docs(changelog): correct 1.0.4 release notes 2013-01-24 09:50:51 -08:00
Vineet Kumar f3cca88384 docs($injector): clarify $inject property description
Section heading about `$inject` property refers to it as `$injector` property.
2013-01-24 00:18:48 -05:00
Igor Minar 978bbd2d49 chore(release): update the CDN version 2013-01-23 12:07:01 -08:00
Igor Minar 652feebd86 chore(release): cut the 1.0.4 bewildering-hair release 2013-01-23 10:57:51 -08:00
Igor Minar 16ccbc4f61 docs(changelog): release notes for 1.1.2 and 1.0.4 2013-01-23 10:57:51 -08:00
Igor Minar 072d45fd01 chore(changelog.js): improve the changelog script 2013-01-23 10:57:51 -08:00
pavelgj 4439e39319 fix(ngResource): correct leading slash removal.
Fixed an issues with ngResource param substitution where it was incorrectly removing leading slash when param was followed by a non-slash character.
Ex:
'/:foo/:bar.baz/:aux'

params = {
  foo: 'aaa',
  bar: undefined,
  aux: undefined
}

The above params were incorrectly producing '/aaa.baz' but now it results in '/aaa/.baz'.
2013-01-22 11:32:27 -08:00
Miško Hevery b49c3a1a1e docs(q): added testing information 2013-01-22 11:32:27 -08:00
Igor Minar c7addd4886 fix(angular.equals): relax the comparison for undefined properties
in 5ae63fd3 the comparison was made consistent but strict, so that

angular.equals({}, {foo: undefined}) // always returns false

this turns out to cause issues for data that is being roundtripped via network
and serialized via JSON because JSON.stringify serializes {foo: undefined} as {}.

Since angular.equals() behaved like this before the 5ae63fd3 in 50% of the cases,
changing the behavior in this way should not introduce any significant issues.

Closes #1648
2013-01-22 07:35:06 -08:00
Igor Minar 6df60aff52 chore(Rakefile): skip build parallelization on Travis
Due to a infrastructure change on Travis starting JVMs in forked
processes doesn't currently work. Since we don't really care that
much about the build speed on Travis, I'm going to disable it there.

Related issue: https://github.com/travis-ci/travis-ci/issues/845
2013-01-21 07:50:24 -08:00
sergiopantoja e7a080d6e6 docs(jqLite): fix typo 2013-01-20 18:59:43 +01:00
Will Moore 661a728764 docs(contribute): adding npm install to step-by-step
npm install is listed in the dependencies section of the contribute guide but
is missing from the step-by-step. This adds it as step 4.
2013-01-18 21:33:58 -08:00
danilsomsikov 89303fd2dc fix(ngSwitch): don't leak when destroyed while not attached
The leak can occur when ngSwich is used inside ngRepeat or any other
directive which is destroyed while its transcluded content (which
includes ngSwitch) is not attached to the DOM.

Refactor ngSwitch to use controller instead of storing data on compile
node. This means that we don't need to clean up the jq data cache.
Controller reference is released when the linking fn is released.

Closes #1621
2013-01-18 00:03:42 -08:00
Fred Sauer 1f8be1ca66 docs(exceptionHandler): document testing
Update src/ng/exceptionHandler.js

Here's an iniitla attempt at documenting how one might write a
test using $exceptionHandlerProvider. The key take-away is the use
of this pattern:

it(...

 module(...
   $exceptionHandlerProvider.mode('log');
 });

 inject(...
 );

});
2013-01-17 23:11:02 -08:00
Matthew Browne cbc2024092 docs(rootScope): correct code examples 2013-01-17 23:11:02 -08:00
Amir H. Hajizamani f0ff7023c3 docs(cookbook): change prototype methods to scope methods in Buzz
As explained in 'Understanding the Controller Component', Controllers
written for new (post 1.0 RC) versions of Angular need to add methods to
the scope directly, not the function's prototype. Correcting this
example should remove any ambiguity, especially for beginners.
2013-01-18 00:56:52 -05:00
Amir H. Hajizamani 6e8728a364 docs(guide): change prototype methods to scope methods in DI examples
As explained in 'Understanding the Controller Component', Controllers
written for new (post 1.0 RC) versions of Angular need to add methods to
the scope directly, not the function's prototype. Correcting this
example should remove any ambiguity, especially for beginners.
2013-01-18 00:56:52 -05:00
Fred Sauer f179a63dd4 docs(ngMock.$httpBackend): fix variable declaration 2013-01-18 00:15:20 -05:00
Shai Reznik 3a71c1e595 doc(guide): Fix examples of $location.html5mode 2013-01-17 23:46:19 -05:00
Shai Reznik ef7a61a67e doc(guide): Fixed typos at the unit tests guide 2013-01-17 23:46:19 -05:00
Igor Minar a6b2ee785b fix(angular.equals): consistently compare undefined object props
previously:

a = {};
b = {x:undefined};
angular.equals(a, b) == angular.equals(b, a) // returns false.

both should return false because these objects are not equal.

unlike in implemented in #1695 the comparison should be stricter
and return false not true. if we need to relax this in the future
we can always do so.

Closes #1648
2013-01-17 17:49:07 -08:00
Daniel Demmel d5a1336e6b docs: recommend using Google CDN 2013-01-17 16:53:32 -08:00
Matt Rohrer d4312b731a docs(guide): minor grammar fixes 2013-01-17 19:36:14 -05:00
Martin Probst 66f051386e feat($compile): support modifying the DOM structure in postlink fn
Support modifying the DOM structure in the post link function of a directive
by creating a defensive copy of the node list, as opposed to a live DOM list.
This is useful for directives to actually replace their entire DOM fragment,
e.g. with the HTML fragment generated by a 3rd party component (Closure, Bootstrap ...).
Fix the indentation of the compileNodes function (was one too little).
2013-01-17 12:57:36 -08:00
Igor Minar 8b3f9684e0 style($compile): fix indentation 2013-01-17 12:55:21 -08:00
Gergely Imreh 331f32deac chore(Rakefile): force 32bit JVM mode only when java supports it
Some Java installs don't have '-d32' flag (e.g. OpenJDK which is standard
for some Linux systems), and the closure_compile fails because of forcing
that flag. Test, and only run in faster 32bit mode if supported, or
else just run with no flag (default mode).
2013-01-17 10:44:39 -08:00
Igor Minar bb80c96754 chore(docs): use done() instead of end() in gen-docs.js 2013-01-17 00:52:19 -08:00
Pete Bacon Darwin 0d8e19c26f fix($compile): do not wrap empty root text nodes in spans
Closes #1059
2013-01-17 00:28:56 -08:00
Pete Bacon Darwin ed2fd2d0ca fix(ngRepeat): correctly apply $last if repeating over object
If the $last property is calculated from the original collectionLength
on an object and properties starting with $ were filtered out, then $last
is never applied and $middle is applied erroniously.

Closes #1789
2013-01-17 00:25:07 -08:00
James deBoer 7c60151cb8 chore(Rakefile): remove a duplicate file in angularFiles.js 2013-01-16 23:45:13 -08:00
James deBoer 965308a32c chore(Rakefile): generate version.json
Changes 'rake version' to output a version.json file which
contains the structured version info which can be used in other tools.
2013-01-16 23:41:51 -08:00
Igor Minar 92c612a9de fix(scenario): don't trigger input events on IE9
input.enter() should trigger 'change' rather than 'input' event on IE9 because
input events on IE9 are broken and angular doesn't rely on them
2013-01-16 23:30:16 -08:00
Kanwei Li a7b53abcad docs(CHANGELOG): fix typo 2013-01-16 23:29:11 -08:00
Martin Probst d575e1f613 fix($route): support route params not separated with slashes.
Commit 773ac4a broke support for route parameters that are not seperated
from other route parts by slashes, which this change fixes. It also adds
some documentation about path parameters to the when() method and
escapes all regular expression special characters in the URL, not just
some.
2013-01-16 09:42:35 -08:00
Igor Minar 2ba458387d fix($compile): safely create transclude comment nodes
Closes #1740
2013-01-14 21:59:23 -08:00
Lucas Galfasó 98489a1d0c doc(directive): Fix typos in dialog widget
Fixes #1799
2013-01-13 10:09:22 +00:00
Igor Minar 51d501aab2 chore(*): remove obsolete files 2013-01-09 21:29:13 -08:00
naomiblack 841bdf1c07 Update docs/content/misc/faq.ngdoc
Updated the canonical video to a recent one. Fixed a typo.
2013-01-09 09:50:27 +00:00
Pete Bacon Darwin 86cac55c7c fix(jqLite): children() should only return elements
The jQuery implementation of children only returns child nodes of the given element that are elements themselves. The previous jqLite implementation was returning all nodes except those that are text nodes. Use jQLite.contents() to get all the child nodes.

The jQuery implementation of contents returns [] if the object has no child nodes.  The previous jqLite implementation was returning undefined, causing a stack overflow in test/testabilityPatch.js when it tried to `cleanup()` a window object.

The testabilityPatch was incorrectly using children() rather than contents() inside cleanup() to iterate down through all the child nodes of the element to clean up.
2013-01-09 09:42:05 +00:00
Keyamoon c0995399d4 fix(jqLite): make next() ignore non-element nodes
next() is supposed to return the next sibling *element* so it
should ignore text nodes. To achieve this, nextElementSibling()
should be used instead of nextSibling().
2013-01-08 14:54:56 -08:00
Igor Minar de6cc287e5 fix($injector): remove bogus fn arg
getService fn takes only one argument, removing the second one.

Closes #1711
2013-01-08 14:36:36 -08:00
Igor Minar afd6771163 refactor($browser): remove faulty 20+ cookies warning
the warning is defunct (and the test is incorrect) so obviously nobody is using
it and it just takes up space.

also the browser behavior varies (ff and chrome allow up to 150 cookies, safari
even more), so it's not very useful.

Closes #1712
2013-01-08 14:27:51 -08:00
Igor Minar 4cda028609 revert: fix(a): prevent Opera from incorrectly navigating on link click
This reverts commit c81d8176cc.

This commit causes several issues (#1651, #1674, #1662) and doesn't even
contain a test that proves that anything on Opera got actually fixed.

If the original Opera resurfaces, we'll fix it properly.
2013-01-08 11:51:17 -08:00
kim lokoy 8ecce7642b docs(guide): fix typos in unit test guide 2013-01-07 21:00:13 +01:00
Pawel Kozlowski d1d5761232 docs(forms): fix code example for a custom form control
Closes #1021
2013-01-05 23:04:33 +01:00
naomiblack 759cba1a8d docs(faq): add info on logo reuse and how to get t-shirts and stickers 2013-01-04 19:22:00 +01:00
Jonathan Card 23cd40a8ec docs(form): minor form doc and example fixes
Form documentation fixes:
- Fix broken form example in docs
- A few small other corrections in form docs.
2013-01-04 17:25:24 +01:00
Per Rovegård f3188c1d09 docs($http): clarify documentation on error status codes
Modify the documentation for $http to correspond to what Angular
considers a success status code.

Closes #1693
2013-01-03 20:47:55 +01:00
Matt Hardy 2f4967f100 docs(guide): change example controller to properly call greet method on greeter 2012-12-31 13:21:29 +01:00
Murilo da Silva 4fe4e7457c docs(anchorScroll): correct word "location" 2012-12-19 21:14:09 +01:00
John Fletcher d4e7274d4b docs(guide): minor English corrections to the Directive guide 2012-12-19 20:55:22 +01:00
Miško Hevery cffa015554 docs(directive): old syntax 2012-12-18 20:39:17 -08:00
Pawel Kozlowski 1104c7d75b docs(ngView): fix code example (change template to templateUrl)
Closes #1715
2012-12-18 17:56:04 +01:00
Gonzalo Ruiz de Villa 4c6b4447db fix($route): correctly extract $routeParams from urls
Routes like '/bar/foovalue/barvalue' matching '/bar/:foo/:bar'
now are well mapped in $routeParams to:
{bar:'barvalue', foo:'foovalue'}

Closes: #1501
Signed-off-by: Gonzalo Ruiz de Villa <gonzaloruizdevilla@gmail.com>
2012-12-14 01:16:07 +01:00
ggoodman 741a37b338 feat(docs): Add angularjs tag to plunks and make private
This is a minor edit to allow Plunks created by way of the docs.angularjs.org site to be appropriately tagged as `angularjs`.
Also, make these generated Plunks private by default.
2012-12-12 21:00:41 +00:00
Peter Evjan 1157c5d341 docs(README.md): add missing 'you' and a comma 2012-12-11 19:33:28 +01:00
Romain Neutron e48adebfb7 docs(guide): fix injector service code example
Fix syntax and update code to the latest API
2012-12-10 23:50:12 +01:00
Juha Syrjälä 0a61dcb486 docs($resource): document port number escaping and fix typo 2012-12-09 17:49:42 +01:00
Eric Case 4b51eaadf8 docs(tutorial): typo fix commandx -> command 2012-12-08 11:39:56 +01:00
Eric Case e2457ca16d docs($q): typo fix - programing -> programming 2012-12-07 21:00:25 +01:00
János Rusiczki bd62790080 doc(concepts): Fix typo in $render() function 2012-12-07 10:19:08 +00:00
Jeremy Tymes 53fdcafa44 docs($http): fix link typo in $http doc
Should be $httpBackend instead of $httpBacked

Closes #1516
2012-12-06 21:50:21 +01:00
Fred Sauer af6f2483be docs(mocks): update src/ngMock/angular-mocks.js documentation
Clarify how to use `$exceptionHandlerProvider.mode('log')` in tests
2012-12-06 21:50:21 +01:00
Fred Sauer d8522aa349 docs(mocks): fix documentation bug: angular.mock.debug 2012-12-06 21:50:20 +01:00
Igor Minar bae3121683 chore(bootstrap-prettify): update urls to code.angularjs.org
Closes #1599
2012-12-05 02:55:19 +01:00
_pants 54c0d464b0 fix(select): support optgroup + select[multiple] combo
Closes #1553
2012-12-05 02:21:31 +01:00
Sudhir Jonathan cf89e8653c fix($injector): provider can now be defined in the array format
`injector.instantiate` is now called for arrays too, instead of only for functions.

Closes #1452
2012-12-01 19:09:36 +01:00
Sudhir Jonathan 0c3500f532 fix($resource): HTTP method should be case-insensitive
Perform call `angular.uppercase` on all given action methods.

Closes #1403
2012-11-30 23:23:34 +01:00
Cezar Berea c12f525df4 refactor($resource): fix indentation and move a method definition
Moved Resource.bind out of the actions forEach
2012-11-30 22:47:25 +01:00
Igor Minar e7ba830691 fix(Scope): ensure that a scope is destroyed only once
Due to bd524fc4 calling $destroy() on a scope mupltiple times cases NPE.

Closes #1627
2012-11-30 13:09:50 +01:00
Daniel Luz 4eb0716711 docs(directive): correct expression, fix typo and re-wrap lines 2012-11-29 20:22:41 +01:00
Johannes Hansen ed90f3b7ea fix(docs): add missing </div> tag to sourceEdit directive template 2012-11-29 20:22:40 +01:00
Igor Minar 14b19ecf5e docs(menu): fix the navbar drop down links 2012-11-28 23:56:21 +01:00
Igor Minar 644432a14c chore(release): start 1.0.4 bewildering-hair iteration 2012-11-28 15:51:23 +01:00
Igor Minar a03e370a09 chore(release): cut the 1.0.3 bouncy-thunder release 2012-11-27 01:44:46 +01:00
Igor Minar 23677d3ddb docs(CHANGELOG): release notes for 1.0.3 and 1.1.1 releases 2012-11-27 01:44:46 +01:00
Rado Kirov fc781560a3 fix($location): reset $location.$$replace with every watch call
Closes #1111
2012-11-26 23:24:39 +01:00
Vojta Jina c9199ee663 docs: load angular from CDN only on production
So that when running the docs locally, eg. during e2e testing, we use the latest build version of angular, rather than the stable one from CDN.

This fixes e2e tests running with Testacular.
2012-11-26 21:33:45 +01:00
Igor Minar 6f18adedef fix(ngClassOdd/ngClassEven): support shrinking/reordering in repeaters
We need to watch $index in addition to cssClasses because only then
we can correctly respond to shrinking or reordered repeaters.

Closes #1076
2012-11-26 21:33:45 +01:00
Igor Minar 6ad894cd58 style(jqLite): better variable names
selector => cssClasses
2012-11-26 21:33:45 +01:00
Igor Minar cde2f1a868 fix(ngRepeat): support mostly-stable repeating for primitives
I'm reverting changes that were originally done to ngRepeat to fix #933,
because these are now not necessary after the previous changes to keep
ngModel always synced with the DOM.
2012-11-26 21:33:45 +01:00
Igor Minar 6a831495de fix(ngModel): sync ngModel state with scope state
In cases when we reuse elements in a repeater but associate
them with a new scope (see #933 - repeating over array of
primitives) it's possible for the internal ngModel state and
the scope state to get out of sync. This change ensure that
the two are always sync-ed up even in cases where we
reassociate an element with a different (but similar) scope.

In the case of repeating over array of primitives it's still
possible to run into issue if we iterate over primitives and
use form controls or similar widgets without ngModel - oh well,
we'd likely need a special repeater for primitives to deal
with this properly, even then there might be cornercases.

Closes #933
2012-11-26 21:33:45 +01:00
Igor Minar 6e2c38f54d test(ngRepeat): clean up and improve tests 2012-11-26 20:39:10 +01:00
Igor Minar 00e7e31418 fix(ngRepeat): attempt to simplify and improve existing fix for #933
I'm keeping this in for future reference. The issue with this solution
is that if we shift() the first item in the array, the whole repeater
DOM will be rebuilt from scratch, we need to do better than that.
2012-11-26 20:39:00 +01:00
Igor Minar ff4b3e20c1 test(ngRepeat): add test for issue #1076 2012-11-26 20:38:51 +01:00
Igor Minar 269fb43b36 fix(jqLite): fire $destroy event via triggerHandler
in jQuery 1.8.x the data() data structure is changed and events are
not accessible via data().events. Since all we need is to trigger
all event handlers, we can do so via triggerHandler() api instead of
mocking with the internal jQuery data structures.

This fix was originally proposed by PeteAppleton via PR #1512.

Closes #1512
2012-11-26 16:03:43 +01:00
Igor Minar 7530654328 feat(jqLite): add triggerHandler()
we need triggerHandler() to become jQuery 1.8.x compatible.

this is not fully featured triggerHandler() implementation - it doesn't
bother creating new DOM events and passing them into the event handlers.

this is intentional, we don't need access to the native DOM event for our
own purposes and creating these event objects is really tricky.
2012-11-26 16:03:39 +01:00
Iristyle c7bd464384 docs(CONTRIBUTING.md): add contrib info file for GitHub 2012-11-25 21:00:56 +01:00
Vojta Jina ef1874d1f3 fix(Scope): allow removing a listener during event 2012-11-25 11:41:32 +01:00
Kevin Western c6d8205fdd docs(README.md): fix "API Docs" link
use direct link to api docs
2012-11-25 01:24:03 +01:00
Dean Sofer 55150a669a docs(api): add ngRequired to input/select/textarea directives
Closes #1202
2012-11-25 01:19:47 +01:00
Jeremy Tymes 1eb9e22d45 fix($cacheFactory): return undefined when removing non-existent entry
Instead of throwning an exception, remove should return undefined when
cache entry to be removed doesn't exist.

Closes #1497
2012-11-24 21:58:17 +01:00
Adrian Gheorghe c0de8fb737 fix($resource): prevent default params to be shared between actions
Having a $resource defined as:

var R = $resource('/Path', {}, {
  get: {method: 'GET', params: {objId: '1'}},
  perform: {method: 'GET'}
});

was causing both actions to call the same URI (if called in this order):

R.get({}); // => /Path?objId=1
R.perform({}); // => /Path?objId=1
2012-11-24 21:29:16 +01:00
Kris Jenkins 557e3894d7 docs(): Fix a couple of typos in the documentation 2012-11-22 08:28:49 +01:00
Dave Clayton 38a9695413 docs(guide/concepts): some typo/grammar fixes 2012-11-22 08:28:49 +01:00
John Hume 293e0336b0 docs(guide/directive): fix typo 2012-11-22 08:28:49 +01:00
Uri Goldshtein 1f5bc0a1cd docs($q): fix missing bracket in the example 2012-11-22 08:28:49 +01:00
Igor Minar 1fe666192b fix($rootScope): workaround for Chrome's memleak
Under certain circumstances chrome fails to GC scopes
because of buggy optimizations and caching. Nulling out
references to (not from!) other scopes helps Chrome to
realize that this object should be GC-ed.

This is really just a workaround as the real problem needs
to be fixed in Chrome.

See discusstion at:
https://github.com/angular/angular.js/issues/1313#issuecomment-10378451

And chrome bug at:
https://code.google.com/p/v8/issues/detail?id=2073

Closes #1313
2012-11-14 19:53:29 +01:00
Igor Minar 29541e735d revert($resource): support custom headers per action
This reverts commit b936e52874.

This commit introduces a feature and should haven't been merged
into the stable branch.
2012-11-11 12:07:26 +01:00
Igor Minar f5b567d44b chore(validate-commit-msg): recognize 'revert' as valid commit type 2012-11-11 12:06:05 +01:00
Haralan Dobrev 5ee3bbee90 docs(angular.module): improve angular.Module#run docs 2012-11-11 11:40:52 +01:00
Jamison Dance 80927c5811 docs(guide): fix run-on sentence in modules guide 2012-11-11 11:35:20 +01:00
Jamison Dance ca8b344e20 docs(tutorial): change module name in step-7 2012-11-11 11:35:15 +01:00
Wes Alvaro 3dab93874d docs($timeout): set return type to Promise instead of *.
The cancel function accepts a Promise, but the timeout function
fails to specify returning a Promise.
2012-11-11 11:32:00 +01:00
Josh Adams 7550f90a57 docs(ngList): fix typo 2012-11-11 11:25:40 +01:00
Josh Adams d78fea87d1 docs(encodeUriSegment): fix typo 2012-11-11 11:23:46 +01:00
Tim Macfarlane 27cee7db0a docs(guide/directive): fix names in scope '='; easier to grok 2012-11-11 11:20:57 +01:00
Christian Vuerings 60acba3840 docs(ngHide): Fix typo and make it more in line with ngShow 2012-11-11 10:37:59 +01:00
Igor Minar 51bed36370 chore(docs): fix docs-scenario.html 2012-11-08 22:18:34 +01:00
Igor Minar 6d940213ac chore(docs): remove obsolete gae files 2012-11-08 22:18:34 +01:00
Miško Hevery 494b527fa7 docs(directive): fix typo 2012-11-05 19:35:31 -08:00
Sudhir Jonathan 8ce84cb2ea chore(testacular): use local testacular version
Making testacular a dependency to avoid having to install it globally.
(Causes npm issues on some machines)
2012-10-31 17:00:00 -07:00
Sudhir Jonathan d981c2a3ec fix(select): select option with a label of 0 is not shown
Bug caused by the use of the `||` operator to replace all non-truthy
values with an empty string. Changed to replace only `undefined` values.

Closes #1401
2012-10-31 15:03:48 -07:00
Igor Minar 537e20065a chore(validate-commit-msg): allow '/' in scope 2012-10-31 14:48:24 -07:00
Fred Sauer 97578b4dae docs(guide/location): fix table formatting
Fix table formatting so headings are bold, rows are separated by lines, and rows have :hover style
2012-10-31 14:48:18 -07:00
Tim Macfarlane fa12564607 docs(module): fix typo in example
fixed example app, `simpleAppModule` should have been `myAppModule`.
2012-10-31 14:22:12 -07:00
sqwishy trick 54bcb9ae25 chore(injector): fix typo in injector documentation 2012-10-31 14:19:52 -07:00
Adam Macejak ad7ce0d402 fix(scenario-runner): support data-ng and x-ng based attributes
Prefixed attributes like data-ng-model and x-ng-model were not being
found by the Selector. It was only looking at ng: and ng- prefixed
attributes.
Added a few tests as well to ensure the aforementioned prefixed
attributes are being matched properly.

Closes #1020
2012-10-31 14:10:26 -07:00
Daniel Luz 085e0ea8ef docs(contribute): fix task name for continuous testing 2012-10-31 13:13:33 -07:00
Igor Minar bb52c4e8d3 fix(docs): correctly generate filenames for plunkr/fiddle
previously examples like $http where broken because we would strip part of the
filename (http-hello.html -> http)

we really want to strip only the id suffix that we append to disambiguate
common filenames (like index.html) which appear in many examples.
2012-10-31 13:06:22 -07:00
Shyam Seshadri 295af335c1 feat(docs): add plunkr support
Add option to edit source in Angular Docs in Plunkr in addition to JsFiddle
2012-10-31 13:06:16 -07:00
Daniel Luz 2c2e18c37a fix(doc): typo on FAQ
Closes #1493
2012-10-31 10:26:00 -07:00
Igor Minar adfb75e3c6 fix($compile): don't look for class directives in empty string
if className is undefined or empty string, don't bother looking for directives in there
2012-10-29 19:39:34 -07:00
Igor Minar 9bff5c60df fix($compile): compilation should not recurse into empty nodes
if a node doesn't have children then don't try to compile these non-existent children
2012-10-29 19:39:21 -07:00
Igor Minar 3ba008d4b2 style($compile): better fn names for debugging 2012-10-29 19:38:57 -07:00
Igor Minar 4e45a2f8e2 refactor($compile): simplify nodeLinkFn 2012-10-29 19:38:29 -07:00
Igor Minar 4dbd8452eb fix($compile): prevent double attr interpolation w/ templateUrl
This fixes the issue that caused two attr interpolation observers
to be registered for the same attribute as a result of isolate
scope definition with attr (@) property for this attribute.

Duplicate observers would then fight with each other updating the
model.

The issue occured only when this directive was used in a repeater
because that's when we clone the template node which caused the
two observers to point to two different sets of $attr instances.

Closes #1166, #836
2012-10-29 19:38:03 -07:00
Braden Shepherdson 45a8db9c08 fix(currency): Handle not-quite-zero values
IEEE 754 floating point sometimes results in values that are very small,
rather than zero. One example is 1.0 + 1.07 - 2.07, which returns
4.440892098500626e-16 instead of 0.

This change tweaks the number formatting logic so that an exponential
value with a negative exponent that is larger than the precision+1
returns 0 instead. For example: with precision 2, anything with an
exponent of -4, -5 or more would become 0. 9e-3 = 0.009 = 0.01, but 9e-4
= 0.0009 = 0.001 = 0.00. This detail is unlikely to matter since this
quirk is usually only triggered with values very close to zero.

Closes #1469
2012-10-29 19:37:52 -07:00
Braden Shepherdson d930a410fb doc(faq): Add Common Pitfalls section
Describes several common pitfalls new users of Angular fall into that
I've observed in #angularjs.
2012-10-29 19:37:38 -07:00
Braden Shepherdson 66505ffc40 doc(faq): Fix minor spelling and wording errors 2012-10-29 19:37:29 -07:00
Igor Minar 045de959b9 chore(check-size.sh): fix rake target 2012-10-29 19:37:21 -07:00
Igor Minar 3ca11d5235 docs(contribute): add CLA note to code submission section 2012-10-19 09:15:34 -07:00
Igor Minar d5d8ac01e3 docs(contribute): add visible link to github project 2012-10-19 09:15:34 -07:00
Igor Minar ace81c053c chore(validate-commit-msg): allow * and - in scope string 2012-10-18 03:29:12 -07:00
Igor Minar 1e95c419b8 chore(jasmine): remove Jasmine from our repo
it's bundled with Testacular, so we don't need it here
2012-10-18 03:29:12 -07:00
Igor Minar 49ed63d26a chore(jstd): remove JsTestDriver from our repo
Testacular FTW!
2012-10-18 03:29:12 -07:00
Igor Minar 6ff2685668 docs(tutorial): replace JsTD with Testacular + drop snapshots
JsTD references have been replaced with Testacular stuff.

snapshots are PITA to maintain so I'm dropping them, everyone loves the Git
version anyway.
2012-10-18 02:34:27 -07:00
Igor Minar c4573c04aa chore(Rakefile): remove test_out dir when cleaning 2012-10-17 20:20:54 -07:00
Igor Minar d57abdb3f7 chore(Rakefile): tune JVM for closure compiler
Using the client VM and forcing 32bit mode gives us huge perf boost.

before:

reali   0m8.173s
user    0m39.984s
sys     0m1.408s

after:

real    0m3.000s
user    0m12.687s
sys     0m0.852s
2012-10-17 20:20:53 -07:00
Igor Minar 4050e89446 chore(Rakefile): paralelize closure compilation
this speeds up the build by paralelizing closure compilation (the slowest
piece of the build process)

before:

real  0m14.372s
user  0m31.649s
sys   0m1.006s

after:

real  0m8.191s
user  0m40.473s
sys   0m1.378s
2012-10-17 20:16:36 -07:00
Vojta Jina b6620c737f chore(test): add junit config for testacular 2012-10-17 20:16:36 -07:00
Igor Minar 0c8e908841 chore(Rakefile): misc_options should support + -> , conversion 2012-10-17 20:16:35 -07:00
Igor Minar 5595e196a8 chore(Rakefile): use exec for webserver
exec unlike system replaces the current process. this way when we kill
the webserver process we don't get scary looking 'rake aborted' error
2012-10-17 12:44:38 -07:00
Misko Hevery f92e4146d1 fix(doc): disable directory listing in docs.angularjs.org 2012-10-08 15:09:06 -07:00
Vojta Jina 8b7108e3c9 chore: add travis config 2012-10-05 10:20:02 -07:00
Igor Minar caf702cc88 docs(downloading): update the downloading docs 2012-10-05 03:15:11 -07:00
Vojta Jina cf2c49ed7f fix($compile): reference local in isolate scope
This was really corner case:
Watcher needs to return changed value, to notify that model might have changed and one more $digest cycle needs to be performed.

The watcher, that takes care of reference binding into an isolate scope ("="), did not return changed value, if the change was from the isolate scope to the parent.

If any other watcher returned change, it worked fine, as this change caused re-digest.

Closes #1272
2012-09-22 12:00:16 -07:00
Igor Minar ccd52abf5d docs(README): update README.md with new rake tasks 2012-09-17 14:52:06 -07:00
Igor Minar 74c574015d chore(Rakefile): fix test:jquery task 2012-09-17 14:52:06 -07:00
Igor Minar 1f1a6fb6d2 docs(contribute): update contribute docs 2012-09-17 09:46:34 -07:00
Igor Minar 8632e893b0 chore(): remove unused files 2012-09-17 09:46:34 -07:00
Igor Minar c2b6e127fa docs(contribute): update misc/contribute docs with Testacular info 2012-09-17 09:46:34 -07:00
Igor Minar 06eceeb09f chore(testing): Testacular config files + rake tasks
- adds testacular config files for jqlite, jquery, modules and e2e tests
- replaces obsolete JsTD Rake tasks with Testacular onces
- rake tasks are parameterazied so that they can be used locally as well as on CI server

usage:

rake test  # run all tests on Chrome
rake test[Safari+Chrome+Opera]  # run all tests on Safari, Chrome and Opera
rake test[Safari]  # run all tests on Safari
rake test:jqlite # run unit tests using jqlite on Chrome
rake test:jqlite[Safari,"--reporter=dots"]  # run jqlite-based unit tests on Safari with dots reporter
rake autotest:jquery  # start testacular with jquery-based config and watch fs for changes
rake test:e2e # run end to end tests
2012-09-17 09:46:13 -07:00
Miško Hevery 8133d468b9 docs(directive): remove reference to old isolation syntax 2012-09-13 11:32:13 -07:00
Misko Hevery 074a354fa9 fix($route): support inline annotation on .resolve 2012-09-11 23:16:41 -07:00
Vojta Jina e191582a02 chore(scripts): add init-repo script 2012-09-11 23:16:38 -07:00
Jay Zeng 6fbe926cda docs(ngResource): Spelling typo (agressive => aggressive) 2012-09-11 16:39:46 -07:00
Igor Minar ebbc224e09 fix($resource): fix isDefined -> angular.isDefined 2012-09-11 16:39:46 -07:00
Shyam Seshadri 2c6aa4c300 fix(*): name all anonymous watch functions in Angular
This will allow us to see function names in Batarang and debugger.

Closes #1119
2012-09-11 16:39:46 -07:00
Zhenbo Zhang f7a8f17fc7 fix(ng-repeat) to work with primitive types 2012-09-11 16:38:42 -07:00
Brian Ford 191efbb558 docs(guide): fix directive interpolation example code
Closes #1339
2012-09-11 16:19:45 -07:00
Shyam Seshadri bf873d6f02 fix(scenario): emit RunnerBegin event 2012-09-11 16:19:44 -07:00
Vojta Jina e741107c55 chore(scripts): add commit-msg hook (validation) 2012-09-11 16:19:44 -07:00
Jimmy Zhuo 82f4b99d99 fix(scenario): NPE when no angular loaded in test page 2012-09-11 16:19:44 -07:00
Daniel Luz 7210b7ae1d docs($rootScope): fix iteration limit described by $watch, it's actually 10 as of now 2012-09-11 16:19:44 -07:00
Daniel Luz afed23c001 docs($rootScope): fix typos and minor wording tweaks on $watch 2012-09-11 16:19:44 -07:00
Daniel Luz 1f69cc2989 docs($rootScope): fix quoting on expression 2012-09-11 16:19:43 -07:00
Daniel Luz 3401833c83 docs($rootScope): standardize on present, third-person actions for descriptions 2012-09-11 16:19:43 -07:00
Daniel Luz 06606e2816 docs($rootScope): backquote attribute types too on $on 2012-09-11 16:19:43 -07:00
Daniel Luz eba64e1f31 docs($cacheFactory): fix backquotes on method descriptions 2012-09-11 16:19:43 -07:00
Daniel Luz 81dd1df1b1 docs($rootScope): fix typos on $new 2012-09-11 16:19:43 -07:00
Daniel Luz dbafbb0de5 docs($rootScope): fix typo on $eval 2012-09-11 16:19:42 -07:00
Daniel Luz 1d0aa7b7c6 docs($rootScope): fix typos on $watch 2012-09-11 16:19:42 -07:00
Igor Minar afd02ca48c fix(docs): update docs top menu links 2012-09-06 15:56:11 -07:00
sgtpep 67db7616ad fix(a): prevent Opera from incorrectly navigating on link click
we handle the navigation by ourselves, so we need to prevent the default action.

Opera ignores event.preventDefault() call so we must return false.
2012-09-06 15:54:20 -07:00
Kai Groner 3d7c752e27 fix(FormController): propagate dirty state to parent forms 2012-09-06 15:54:19 -07:00
Jonathan Zacsh f02833d634 chore(docs): get correct location for jasmine-node 2012-09-06 15:54:19 -07:00
Misko Hevery 0eb373e0e6 fix($injector): more conservative annotation parsing 2012-09-06 15:49:50 -07:00
Xiangru Chen fd3071843c fix(ngSrc): don't set src if value is empty string
Current implementation of ngSrc may lead to empty src attribute when page is loading.

For example:

<img ng-src="{{image.url}}">
can be temporarily rendered as

<img src="">
before the image resource is loaded.

Some browser emits a request to the current page when seeing <img src=""> (Firefox13 and IE8 will, Chromium20 won't), which leads to performance problems.
2012-09-06 15:49:49 -07:00
Iwein Fuld a631ceb223 fix(dateFilter): make timezone optional
Makes the time zone optional in the date filter

Problem with the current R_ISO8601_STR regex was that the time was optional, but the zone was not.
This results in the filter not formatting local date times, which it could easily do.

For example:
2012-08-30 -> formatted
2012-08-30T06:06:06.123Z -> formatted
2012-08-30T06:06:06.123 -> NOT formatted

A simple change in the regex fixes this. Arguably this is closer to the ISO8601 spec which specifies
local dates being in the "current time zone" and not requiring a Z. In any case it behaves more like
a user would expect.
2012-09-06 15:49:49 -07:00
Misko Hevery a713928210 docs(concept): correct example for creating injector 2012-09-06 15:49:49 -07:00
Godmar Back 05fa20df81 docs(module): fixed module example and corrected typos 2012-09-06 15:49:49 -07:00
Benjamín Eidelman 125573602f fix($resource): allow falsy values in URL parameters
Close #1212

when a param value was 0 (or false) it was ignored and removed from url.
after this fix that only happens if the value is undefined or null.
2012-09-06 15:49:49 -07:00
Jay Zeng ed5dfbcd66 docs(module): myAppModule -> simpleAppModule 2012-09-06 15:49:49 -07:00
petrovalex d2e52b2376 fix($resource): ignore undefined parameters
- $resource should handle multiple params with same name
- ignore slashes of undefined parameters
- fix default parameters issue, mentioned in #875

Closes #875
Closes #782
2012-09-06 15:49:49 -07:00
petrovalex a56aaa9877 fix(ngClassEven/Odd): filtering/ordering and repeater
Closes #1076
2012-09-06 15:49:48 -07:00
Max Martinsson 79bb7b1f0b fix(ngClass): works with class interpolation
Closes #1016
2012-09-06 15:49:48 -07:00
Max Martinsson b936e52874 feat($resource): support custom headers per action
Closes #736
2012-09-06 15:49:48 -07:00
petrovalex 0d52ff0f10 fix($parser): string concatination with undefined model
Closes #988
2012-09-06 15:49:48 -07:00
Stein Jakob Nordbø baf52e902d fix(dateFilter): support sub-second precision on dateFilter 2012-09-06 15:49:48 -07:00
Igor Minar dffea9e2b7 docs($route): rename leftover $afterRouteChange to $routeChangeSuccess 2012-09-06 15:03:58 -07:00
Igor Minar 4a411b8f82 chore(release): prepare 1.0.3 bouncy-thunder iteration 2012-09-06 08:42:51 -07:00
Misko Hevery 278bfc4bb2 fix(docs): broken url to angular-bootstrap 2012-09-04 18:16:52 -07:00
Igor Minar 18731173f9 chore(Rakefile): add 'version' rake task to generate version.txt 2012-09-04 16:38:29 -07:00
Igor Minar d43fb404d7 chore(docs): bump up the stable version 2012-09-04 16:30:33 -07:00
Igor Minar da984ad187 chore(release): cut the 1.0.2 debilitating-awesomeness release 2012-09-04 11:08:40 -07:00
Igor Minar 4015357ce5 chore(docs): don't rewrite colons in doc filenames 2012-09-04 11:08:40 -07:00
Igor Minar dc3d11ad19 chore(Rakefile): zip only the build dir 2012-09-04 11:08:40 -07:00
Igor Minar 0e1545eb04 revert: fix(ng-repeat) to work with primitive types
this commit was accidentaly merged. it needs more work and we don't
have CLA signature

This reverts commit 98d489712e.
2012-08-31 13:44:36 -07:00
Igor Minar ec7cabf5c9 docs(changelog): release notes for 1.0.2 and 1.1.0 releases 2012-08-31 13:23:23 -07:00
Jonathan Zacsh 3051beba2f fix(docs): Making sure gen_docs.sh looks for a globally installed copy of jasmine-node as well as local. 2012-08-30 22:38:54 -07:00
Fernando Correia 92304323b1 docs(tutorial): correct typos and clarify a few sections 2012-08-30 22:38:54 -07:00
Brice Burgess c28123a872 fix(docs): indicate support for passing a string as the controller property on $routeProvider's route object 2012-08-30 22:38:53 -07:00
brettcannon d798423813 doc(misc) Mention how attribute names map to directive names. 2012-08-30 22:38:52 -07:00
Sahat Yalkabov 2583e77cc7 doc(module) changed simpleApp to myApp in the Module page guide for consistency 2012-08-30 21:34:43 -07:00
Steve Nicolai f66836fee4 doc(devguide) - Fix typos and small grammatical errors in the developer guide. 2012-08-30 21:34:42 -07:00
Uri Goldshtein 0ccc445d53 Loading from Google CDN
As you guys had mansion, we can and need to do it through Google CDN for better performance,
so i've updated it accordingly
2012-08-30 21:34:42 -07:00
Tyson Benson b7d5fa1cbe docs(typos): fix typos in dev guide 2012-08-30 21:34:42 -07:00
German Galvis 8bb3942453 fix(scenario): Adding meta tag to avoid cache issues 2012-08-30 21:34:42 -07:00
phil 51a79cebcb docs(api): fix typo on home page
Refference -> Reference
2012-08-30 21:34:41 -07:00
csugden 36bcf64008 Update docs/content/guide/overview.ngdoc
Corrects video information
2012-08-30 21:34:41 -07:00
Jamie Krug 5c6630605b fix(docs): Fix typos and improve grammar. 2012-08-30 21:34:41 -07:00
Jamie Krug 125827406c fix(docs): Fix bad links. 2012-08-30 21:34:41 -07:00
Colin Frei 62c21422a6 docs(module) fix typo 2012-08-30 21:34:41 -07:00
Zhenbo Zhang 98d489712e fix(ng-repeat) to work with primitive types 2012-08-30 21:34:41 -07:00
Igor Minar 2cab2d8ef1 test(locationSpec): fix broken tests after vojta's commit 2012-08-30 16:54:07 -07:00
Vojta Jina 8fa2bb72bc fix(mocks): free up memory after every spec 2012-08-30 16:53:52 -07:00
Igor Minar d151f94937 chore(docs): ask GAE to serve docs-keywords.js 2012-08-30 15:59:29 -07:00
Igor Minar 5b74b7185b test(bootstrap): test exception siling during bootstrap
Closes #1018
2012-08-30 15:18:11 -07:00
Igor Minar 4f0be2ae4e test(ngApp): add missing test for [ng-app] bootstrap 2012-08-30 15:18:02 -07:00
Igor Minar bb9badeb2a fix(jqLite): better support for xhtml
it turns out that some stuff doesn't work in xhtml as it does in html.

for example &nbsp; can't be innerHTML-ed and auto-closing of elements
doesn't work.

the reporter of the referenced issue claimed that innerHTML vs text on
script made a difference but that doesn't appear to be true in my testing.

I'm not including test for this because testacular doesn't currently
run tests in xhtml yet.

Closes #1301
2012-08-30 10:52:36 -07:00
Igor Minar c287c8361d chore(docs): correctly link docs images 2012-08-30 08:59:17 -07:00
Igor Minar ade7127c79 chore(Rakefile): fix the default task 2012-08-30 08:58:51 -07:00
Igor Minar d341483f1f chore(Rakefile): remove bogus symlink from build 2012-08-30 08:58:39 -07:00
Igor Minar b36acbc857 chore(docs): use symlinks to build docs
so that we can just edit source files without rebuilding docs.

this works for all docs files, except for those that are generated
or rewritten during build.
2012-08-28 16:08:03 -07:00
Igor Minar a4fea38b94 chore(Rakefile): various build script changes
- restructure rake tasks

  this splits up the concatination and minification into two
  tasks so that we can just build angular.js quickly without wasting
  time with minification which is often not needed when just debugging
  some issue on 3rd party site.

- use symlinks when creating final zip file

- switch from btar to zip

- get rid of version numbers from filenames

- rewrite version numbers in all index files

Closes #1226
2012-08-28 16:07:47 -07:00
Misko Hevery 300c5c0c99 doc($log): correct non-working example 2012-08-27 21:20:51 -07:00
Misko Hevery 152537c4e9 doc(guide): add concepts 2012-08-27 21:20:51 -07:00
Misko Hevery 8b46bf6bc9 fix(ngdoc): failing test 2012-08-27 21:20:50 -07:00
Colin Frei aef861eb41 doc(directive) correct typos 2012-08-27 21:20:50 -07:00
Misko Hevery f61d36861d fix(docs) typo 2012-08-27 21:20:50 -07:00
Misko Hevery 2af0348cea fix(ng-list): remove data bound flicker 2012-08-27 21:20:50 -07:00
Misko Hevery 78c5743494 doc(misc) updated getting started to reflect the new homepage 2012-08-27 21:20:49 -07:00
Misko Hevery 2cb9fbd043 doc(guide) simplify the guide home page 2012-08-27 21:20:49 -07:00
Igor Minar e9dad5dbf4 chore(Rakefile): rewrite version numbers in all index files 2012-08-27 12:25:40 -07:00
Igor Minar 54895fc2a1 chore(docs): support _escaped_fragment_ hack for crawler 2012-08-25 02:31:20 -07:00
Igor Minar 60a12b4161 chore(docs): use GAE and Google CDN for docs
Short summary: if you use local node server everything should work as before,
if you use GAE, everything should work now as well, but we pull assets from CDN.

- GAE doesn't support ':' in filenames, so I had to replace it with '_'
  but only in the filename, all servers were reconfigured to rewrite the
  urls from : to _ when doing file lookup
- We now pull angular assets from google CDN when deployed on GAE (locally
  or in production). When running on a non GAE server we pull assets from
  ../ directory as before
- Since only certain versions of Angular are available on CDN and we want
  to be able to autodeploy docs, I had to pin down the Angular files
  to a "stable" version when running on GAE
2012-08-24 15:00:36 -07:00
Igor Minar cd7e58ba41 docs(a): expose hidden docs
It seems that docs for these directive were previously hidden by accident
2012-08-24 14:59:52 -07:00
johnlindquist 9391475dc3 docs(ngRoute): fix typo
aftre -> after
2012-08-24 14:59:43 -07:00
phil 7840803add docs(tutorial): fix typo in step_00
Just removed an extra comma. No big deal.
2012-08-24 14:59:21 -07:00
Igor Minar 7d77de2834 fix($compile): denormalize directive templates
Since developers are allowed to customize start/end interpolation
strings, but third-party directive creators don't know about these
customizations, we should standardize on {{ }} in templates of
reusable (third-party) directives. During the compilation, these
templates are then denormalized to use whatever the custom
start/end symbol is, effectively translating the template into the
syntax of the runtime environment.

This addresses an issue raised at http://goo.gl/e8VPV

Existing code should not be affected by this change since project
that do use custom interpolation markers are not expected to use
{{ }} in existing directive templates.
2012-08-13 14:35:32 -07:00
Igor Minar ab044cada6 refactor($compile): code cleanup 2012-08-13 12:36:42 -07:00
Brian Ford d010e0cc7d fix(ngPluralize): fixes ng-pluralize when using non-standard start/end symbols
Closes #1134
2012-08-13 12:36:33 -07:00
Igor Minar 40f728b1aa style(ngPluralizeSpec): fix indentation 2012-08-13 12:36:22 -07:00
Igor Minar 23abb26405 feat($interpolate): expose start/end symbols in run phase
previously the startSymbol() and endSymbol() getters were exposed only via provider
in the config phase
2012-08-13 12:36:14 -07:00
Igor Minar fd55bc8e1d docs($interpolateProvider): fixing docs 2012-08-13 09:51:57 -07:00
Igor Minar 541aaa4e08 fix($interpolate): $interpolateProvider.endSymbol() returns startSymbol
I also added missing tests.
2012-08-13 09:51:45 -07:00
Igor Minar f22c422547 docs($interpolate): fix typo in description 2012-08-13 09:51:35 -07:00
Vojta Jina 0e461f0c07 docs($compileProvider): remove duplicate of .directive() 2012-08-12 11:04:32 -07:00
Vojta Jina 5074448443 docs: fix broken links to $compileProvider.directive() 2012-08-12 11:04:20 -07:00
Brian Ford 8d66af11e6 fix(docs): fixed documentation for using linky 2012-08-10 16:38:01 -07:00
Brian Ford 169948bb47 chore(ngDoc): add support for custom @usage metadata 2012-08-10 16:37:54 -07:00
Brian Ford 58d9469574 fix(docs): added note about using JSON3 as a polyfill for IE7 2012-08-10 16:37:42 -07:00
Brian Ford 8d858a2360 fix(docs): added note about needing JSON shim for IE7 and earlier 2012-08-10 16:36:56 -07:00
Igor Minar 5540748890 fix(option): support option elements in datalist
previously we expected to find option elements only within select element and if
that was not the case we throw an error. This made it impossible to include datalist
element with nested option elements in the template.

Closes #1165
2012-08-10 16:14:49 -07:00
unirgy f8a52be817 docs($rootScope): fix $on listener signature doc
Added args in $on() listener syntax declaration
2012-08-10 14:52:57 -07:00
Igor Minar 3b5f1105f6 test(jqLite): add missing test for $destroy event 2012-08-10 14:21:11 -07:00
Igor Minar 663ccc5449 fix(form): prevent page reload when form destroyed
this fix ensures that we prevent the default action on form submission
(full page reload) even in cases when the form is being destroyed as
a result of the submit event handler (e.g. when route change is
triggered).

The fix is more complicated than I'd like it to be mainly because
we need to ensure that we don't create circular references between
js closures and dom elements via DOM event handlers that would then
result in a memory leak.

Also the differences between IE8, IE9 and normal browsers make testing
this ugly.

Closes #1238
2012-08-10 14:21:02 -07:00
Igor Minar 263f47819f test(form): fix broken preventDefault test
the original test relied on incorrect assumptions about how jasmine async
tests work (when setTimeout is triggered) and how browser reloads a page
(the sequence of events) and thus the test passes even when the default
is not prevented.

this change fixes the test by registering an extra submit event handler
that checks if the default was prevented.

if the default was not prevented, the test will fail and the page will
be reloaded causing the test runner to panic.
2012-08-10 14:20:52 -07:00
Igor Minar 6b75475ce3 refactor(formSpec): group preventDefault specs into a describe 2012-08-10 14:20:28 -07:00
Igor Minar 07c354a8c0 docs(faq): update faq docs 2012-08-10 14:20:13 -07:00
Igor Minar 1391579599 docs(styles): fix the cog icon alignment 2012-08-10 14:19:57 -07:00
Vojta Jina 5d2bd1d84c chore(nodeserver): add font mime type 2012-08-10 14:19:47 -07:00
Vojta Jina bf77e212af docs(guide): hide scenario for directive example
scenario test for this example would be tricky, we need to teach
the runner how to inject mocks first.
2012-08-10 14:19:37 -07:00
Vojta Jina eef2f9c31e docs(design): fix icons
Copy fontawesome during build
2012-08-10 14:18:45 -07:00
brettcannon 438627c2c3 fix(docs): "in depth" -> "in-depth" 2012-08-10 14:18:06 -07:00
Igor Minar d3952b79c7 docs(readme): improve blurb about AngularJS in README.md 2012-07-19 21:48:45 -07:00
brettcannon 5ef9ed87d8 fix(docs): Capitalize Angular. 2012-07-19 15:23:21 -07:00
brettcannon 8c81a0f372 fix(docs): Fix a spelling mistake by replacing the noun with "it" 2012-07-19 15:04:29 -07:00
brettcannon bde931afd5 fix(docs): "were" -> "where" 2012-07-19 11:28:19 -07:00
brettcannon 6553fe68d1 fix(docs): Capitalize "URL". 2012-07-19 11:05:38 -07:00
Chris Dawson 13b5fd1b9d fix(docs): Fixed defer to timeout change in timer directive example 2012-07-19 10:04:22 -07:00
Chris Dawson 17209d5b4a fix(docs): Spelling errors 2012-07-19 10:01:50 -07:00
brettcannon 6f9a5721bc fic(docs): Consistently use __bold__ for things that must be done when moving the ng-controller declaration. 2012-07-19 09:57:58 -07:00
brettcannon 31c825607d fix(docs): Tweak some grammar and add some links relating to DI. 2012-07-19 09:54:53 -07:00
brettcannon ab6937e251 fix(docs): Capitalize "APIs" 2012-07-19 09:49:44 -07:00
brettcannon fbfda241f6 fix(docs): Capitalize "Angular". 2012-07-19 09:35:43 -07:00
brettcannon 206371b737 fix(docs): Capitalize Angular. 2012-07-19 09:26:34 -07:00
brettcannon b6b92bd866 fix(docs): Add a missing "the". 2012-07-19 09:09:52 -07:00
brettcannon 79f2d843a8 fix(docs): ngRepeater isn't a thing, ngRepeat is 2012-07-19 09:04:59 -07:00
brettcannon 64a9cd8f4f fix(docs): Remove a redundant "in". 2012-07-19 09:02:04 -07:00
brettcannon 7f6e1326f3 fix(docs): Grammatical fix 2012-07-18 15:48:08 -07:00
brettcannon 1fd2b3d402 fix(docs): Fixed some awkward wording 2012-07-18 15:42:29 -07:00
brettcannon d56d69cc83 fix(docs): Tweak formatting and wording of a list 2012-07-18 15:20:38 -07:00
brettcannon 01e726b2fa fix(docs): Don't want the present participle of "is" 2012-07-18 15:15:09 -07:00
brettcannon 1613621645 fix(docs): Adjectve accidentally made into an adverb 2012-07-18 12:16:14 -07:00
brettcannon 92a3d28218 fix(docs): Minor grammatical fix 2012-07-18 11:52:57 -07:00
Rishabh Rao 4c58501956 fix(docs): Fixed typo: changed ngRepeate to ngRepeat. 2012-07-16 12:33:19 -07:00
Jamie Krug c076fe08cf fix(docs): Fix spelling, punctuation and grammatical errors on dev guide bootstrap page. 2012-07-16 12:10:43 -07:00
Jamie Krug 2473412ba5 fix(docs): Fix spelling, punctuation and grammatical errors on dev guide compiler page. 2012-07-16 12:10:42 -07:00
Jamie Krug 1f2d50000e fix(docs): Fix spelling, punctuation and grammatical errors on dev guide overview page. 2012-07-16 12:10:33 -07:00
Kevin Old 5026315d6f fix(docs): correct typo 2012-07-16 11:40:21 -07:00
Igor Minar a8b04004e3 docs(readme): add blurb about AngularJS to README.md 2012-07-02 08:21:19 -07:00
Igor Minar f0a090ddf2 fix(docs): correctly generate sitemap 2012-07-02 08:21:19 -07:00
Igor Minar 6d9313a68d fix(docs): fix broken ng-docs specs 2012-07-02 08:21:19 -07:00
Vojta Jina 212f685e06 chore(changelog): fix typos in rc11 changelog 2012-06-25 20:36:41 -07:00
Igor Minar 35706ba482 chore(release): starting the 1.0.2 debilitating-awesomeness iteration 2012-06-25 12:52:32 -07:00
Igor Minar 9bef436b22 chore(release): cutting the 1.0.1 thorium-shielding release 2012-06-25 09:30:57 -07:00
Igor Minar 3f14a45aa5 docs(changelog): release notes for 1.0.1 thorium-shielding 2012-06-25 09:30:57 -07:00
Misko Hevery ffb270130a fix(browser): prevent ie from getting into redirect loop
Closes #1075
Closes #1079
Closes #1085
2012-06-22 10:21:31 -07:00
Igor Minar 0d57f1373f chore(release): starting the 1.0.1 iteration 2012-06-21 13:59:53 -07:00
Igor Minar 869143ec7d chore(logos): fix shield logo exports
the previous version is clipped at the top
2012-06-21 13:58:24 -07:00
Igor Minar 1e6d4d5f54 fix(logo): center A in the shield 2012-06-21 13:58:24 -07:00
Vojta Jina 3da4194f98 fix($location): url rewriting if element was removed
When user clicks a link, $location needs to intercept this event.  The <a> doesn't have to be target element of the DOM event, so it needs to traverse the DOM, to find first <a> parent.

If the target element was removed from DOM, during the same event, it would throw an exception. This fixes the issue.

Closes #1058
2012-06-20 12:18:48 -07:00
Misko Hevery ad5d2f2991 fix(doc) firefox icon rendering 2012-06-15 10:40:25 -07:00
Igor Minar 519bef4f3d chore(release): cutting the 1.0 temporal-domination release 2012-06-14 10:50:22 -07:00
Igor Minar 6dfe5be155 docs(changelog): release notes for 1.0 temporal-domination release 2012-06-14 10:50:22 -07:00
Misko Hevery 6593a3e082 fix($location): fix URL interception in hash-bang mode
Closes #1051
2012-06-14 10:48:56 -07:00
Misko Hevery 0f44964e5e fix($location): correctly parse link urls in hashbang mode with prefix
This is a second fix for a regression that was introduced by 92a2e180.
The fix addresses scenarios when the $location service is configured with
a hash prefix.

Closes #1037
2012-06-13 10:49:05 -07:00
Igor Minar f6b09b9139 chore(release): starting the 1.0 temporal-domination iteration 2012-06-13 10:46:22 -07:00
Igor Minar 7fa1995e08 chore(release): cutting the 1.0.0rc12 regression-extermination release 2012-06-12 01:46:02 -07:00
Igor Minar da94b03af7 docs(changelog): release notes for 1.0.0rc12 regression-extermination 2012-06-12 01:45:26 -07:00
Igor Minar f158d81d21 docs($browser): hide $browser docs - it's a private service 2012-06-12 01:14:45 -07:00
Igor Minar 9af7a9198e fix($defer): remove deprecated $defer service 2012-06-12 01:09:07 -07:00
Misko Hevery 74fa65ecb7 fix($location): correctly parse link urls in hashbang mode
This is a fix for a regression that was introduced by 92a2e180

Closes #1037
2012-06-12 00:27:25 -07:00
Igor Minar ee6014a3aa fix($location): throw Errors not Strings 2012-06-12 00:27:24 -07:00
Igor Minar d9ff5fd432 fix(docs): migrate from $defer to $timeout 2012-06-12 00:11:04 -07:00
Igor Minar f16150d5f1 docs(*): simplify doc urls
we now have two types of namespaces:

- true namespace: angular.* - used for all global apis
- virtual namespace: ng.*, ngMock.*, ... - used for all DI modules

the virual namespaces have services under the second namespace level (e.g. ng.)
and filters and directives prefixed with filter: and directive: respectively
(e.g. ng.filter:orderBy, ng.directive:ngRepeat)

this simplifies urls and makes them a lot shorter while still avoiding name collisions
2012-06-12 00:10:18 -07:00
Igor Minar fc0b2b5715 chore(logos): adding AngularJS and shield logos 2012-06-11 14:13:18 -07:00
Igor Minar f3f090da8a chore(release): start 1.0.0rc12 regression-exterminator release
quick release to fix $location regression
2012-06-11 14:10:02 -07:00
Igor Minar 068f2f9d43 chore(release): cutting the 1.0.0rc promise-resolution release 2012-06-11 00:03:01 -07:00
Igor Minar 2d48733723 docs(changelog): release notes for 1.0.0rc11 promise-resolution 2012-06-11 00:03:01 -07:00
Igor Minar d37d595b67 test($location): fix tests borked during event renaming 2012-06-10 17:42:44 -07:00
Igor Minar 5d70e4a89c docs(*): fix various outdated docs and examples
Closes #1030
2012-06-10 09:01:42 -07:00
Igor Minar b5bba65a93 docs($location): clarify the two-way data-binding note
Closes #1030
2012-06-09 06:57:55 -07:00
Max Martinsson fb99b539b4 fix($compile): correctly merge class attr for replace directives
Merging of interpolated class attribute from directive template with replace:true works

Closes #1006
2012-06-08 16:07:15 -07:00
Vojta Jina 10f80d7d29 fix($http): add utf-8 to default Content-Type header (post/put)
This fixes special characters issue with MongoLab.

https://groups.google.com/d/topic/angular/1T6h7bfZ7Rs/discussion
2012-06-08 16:07:15 -07:00
Misko Hevery c3a41ff9fe feat($compile): simplify isolate scope bindings
Changed the isolate scope binding options to:
  - @attr - attribute binding (including interpolation)
  - =model - by-directional model binding
  - &expr - expression execution binding

This change simplifies the terminology as well as
number of choices available to the developer. It
also supports local name aliasing from the parent.

BREAKING CHANGE: isolate scope bindings definition has changed and
the inject option for the directive controller injection was removed.

To migrate the code follow the example below:

Before:

scope: {
  myAttr: 'attribute',
  myBind: 'bind',
  myExpression: 'expression',
  myEval: 'evaluate',
  myAccessor: 'accessor'
}

After:

scope: {
  myAttr: '@',
  myBind: '@',
  myExpression: '&',
  // myEval - usually not useful, but in cases where the expression is assignable, you can use '='
  myAccessor: '=' // in directive's template change myAccessor() to myAccessor
}

The removed `inject` wasn't generaly useful for directives so there should be no code using it.
2012-06-08 15:50:13 -07:00
Igor Minar 5c95b8cccc fix(startingTag): make tag name always lowercase
some browsers (IE) always provide the nodeName as upper-case
2012-06-08 15:27:04 -07:00
Misko Hevery 9be82d942f refactor($compile): always call attr.$observe
attr.$observe used to call function only if there was interpolation
on that attribute. We now call the observation function all the time
but we only save the reference to it if interpolation is present.
2012-06-08 15:27:03 -07:00
Misko Hevery 2491319575 chore($compile): clean up compiler tests 2012-06-08 15:27:02 -07:00
Misko Hevery bcc3a021eb chore(jqLite): performance reordering 2012-06-08 15:27:02 -07:00
unknown a57141fd1d docs(guide): correct couple of typos 2012-06-04 18:46:09 -07:00
Ali Mills 1904596e0c fix($timeout): allow calling $timeout.cancel() with undefined
This is how it worked in rc9, before refactoring $defer into $timeout.
2012-06-04 17:43:14 -07:00
Igor Minar 22143381d8 chore(release): starting 1.0.0rc11 promise-resolution iteration 2012-06-04 10:03:59 -07:00
Misko Hevery ddefb42445 doc(app): switch to use $last on ng-repeat 2012-06-02 16:02:09 -07:00
Misko Hevery 676d6e0040 doc(app): remove un-needed file 2012-06-02 16:02:09 -07:00
Misko Hevery 8024a5742c doc(NgModelController) add example and $render documentation
Closes#930
2012-06-02 16:02:09 -07:00
Misko Hevery 073e76f835 doc(guide): corrected examples 2012-06-02 16:02:09 -07:00
Misko Hevery 7019f142ab merge cleanup 2012-06-02 16:02:09 -07:00
Misko Hevery 0532aabcf9 doc(guide): clean up broken links 2012-06-02 16:02:08 -07:00
Misko Hevery f0be543614 doc(ngdoc): clean up doc generation and add missing documentation links 2012-06-02 16:02:08 -07:00
Misko Hevery a3a37c2063 doc(compiler): rewrite 2012-06-02 16:02:08 -07:00
Misko Hevery 0f5259c5a2 docs(introduction): rename 2012-06-02 16:02:08 -07:00
Misko Hevery 321a4a6b1f doc(i18n): rename 2012-06-02 16:02:08 -07:00
Misko Hevery 41d26db32c docs(expression): rewrite 2012-06-02 16:02:08 -07:00
Misko Hevery dd38ce6585 docs(scope): rewrite 2012-06-02 16:02:07 -07:00
Misko Hevery 2e90cdc3d4 docs(dependency injecton): rewrite 2012-06-02 16:02:05 -07:00
Misko Hevery 581f93ae56 docs(ngdocs): cleaned up directive titles 2012-06-02 16:02:05 -07:00
Misko Hevery 6933fb7924 docs(bootstrap): rewritten bootstrap guide 2012-06-02 16:02:05 -07:00
Misko Hevery f5afcca99d docs(overview): updated overview guide 2012-06-02 16:02:04 -07:00
Misko Hevery 2356c21650 doc(ngdoc): proper label for source and demo section 2012-06-02 16:02:04 -07:00
Misko Hevery 275e5335dc fix(docs): include short words in keywords
Short words like $q are now searchable.

Closes #967
2012-06-02 15:44:58 -07:00
Misko Hevery 92a2e18076 feat($location): add $locatonChange[begin|completed] event
This allows location change cancelation
2012-06-02 15:44:58 -07:00
Misko Hevery 8aa18f0ad0 chore($location) switch to use $rootElement 2012-06-02 14:51:03 -07:00
Misko Hevery 85632cb44c feat($rootElement): added application root element
Publish the application root element as $rootElement
so that it can be injected to other services.
2012-06-02 14:50:58 -07:00
Misko Hevery 0a6e464a93 feat($route): rename template -> tempalteUrl and add support for inline templates
BREAKING CHANGE: template in $route definition is now templateUrl
To migrate just rename `template` to `templateUrl`.
2012-06-01 17:01:10 -07:00
Misko Hevery 7c24282188 chore($route): rename events
BREAKING CHANGE

rename $beforeRouteChange to $routeChangeStart
rename $afterRouteChange to $routeChangeSuccess
2012-06-01 16:57:49 -07:00
Misko Hevery 885fb0dd07 feat($route): resolve local route promises
Resolve all promises on route before we fire $afterRouteChange which then renders the ngView.
2012-06-01 16:56:31 -07:00
Misko Hevery 4361efb03b feat($injector): provide API for retrieving function annotations 2012-06-01 10:57:51 -07:00
Misko Hevery 416a783040 fix(jqLite): don't eat event exceptions
JQuery does not catch exceptions either, and just
lets them pass. This allows the exception to be
shown in console.
2012-05-24 13:48:44 -07:00
Misko Hevery bbaf9a2870 fix(docs): accept return in addition to returns
documentation used @return but parser expected
@returns, which made the generated documentation
incomplete.
2012-05-24 13:48:42 -07:00
Misko Hevery 7e70463da1 chore(docs): remove generated file 2012-05-24 13:48:42 -07:00
Misko Hevery 4235ee9ad6 chore(docs): remove unused doc_widget.js file 2012-05-24 13:48:40 -07:00
Misko Hevery 3fdb29242b chore(docs): correct spacings 2012-05-24 13:48:38 -07:00
Misko Hevery b5fb18ae35 fix(favicon): update to aliased icon 2012-05-24 13:48:31 -07:00
Igor Minar 5fdf42ce39 chore(release): cut the 1.0.0rc10 tesseract-giftwrapping release 2012-05-23 21:05:21 -07:00
Igor Minar bf6a0b7289 docs(changelog): release notes for 1.0.0rc10 tesseract-giftwrapping 2012-05-23 16:37:37 -07:00
Misko Hevery 989446ecee fix($rootScope): TTL exception does not clear $$phase
When $digest() throws infinite digest exception it
does not properly clear the $phase leaving the scope
in an inconsistent state.

Closes #979
2012-05-23 16:01:20 -07:00
Igor Minar 5214c1d0cb chore(package.json): add simple package.json with npm dependencies 2012-05-23 15:00:56 -07:00
Igor Minar 4511d39cc7 feat($timeout): add $timeout service that supersedes $defer
$timeout has a better name ($defer got often confused with something related to $q) and
is actually promise based with cancelation support.

With this commit the $defer service is deprecated and will be removed before 1.0.

Closes #704, #532
2012-05-23 15:00:56 -07:00
Daniel Gomes 15b8f205bb docs($filter): minor corrections 2012-05-22 14:27:26 -07:00
Max 1d388676e3 fix(ngRepeat): expose $first, $middle and $last instead of $position
$position marker doesn't work well in cases when we have just one item
in the list because then the item is both the first and last. To solve
this properly we need to expose individual $first and $middle and $last
flags.

BREAKING CHANGE: $position is not exposed in repeater scopes any more

To update, search for $position and replace it with one of $first,
$middle or $last.

Closes #912
2012-05-22 14:18:15 -07:00
Vojta Jina 84542d2431 feat(scope): add event.preventDefault() and event.defaultPrevented 2012-05-17 15:47:53 -07:00
Vojta Jina 91db99208e refactor(scope.$emit): rename event.cancel() to event.stopPropagation()
Breaks event.cancel() is event.stopPropagation()
2012-05-17 15:47:52 -07:00
Misko Hevery acf095d178 fix(jqLite): have same expando format as jQuery 2012-05-17 10:36:45 -07:00
Igor Minar 301d8f233b chore(release): start 1.0.0rc10 tesseract-giftwrapping iteration 2012-05-15 00:09:08 -07:00
Igor Minar d70223e53e chore(release): cutting 1.0.0rc9 eggplant-teleportation 2012-05-14 22:13:15 -07:00
Igor Minar 8ad02bb5a8 docs(changelog): release notes for 1.0.0rc9 eggplant-teleportation 2012-05-14 22:00:18 -07:00
Misko Hevery ec1c5dfaee fix(jqLite): .data()/.bind() memory leak
Since angular attaches scope/injector/controller
into DOM it should clean up after itself. No need
to complain about memory leaks, since they can
only happened on detached DOM. Detached DOM would
only be in tests, since in production the DOM
would be attached to render tree and removal
would automatically clear memory.
2012-05-14 21:56:22 -07:00
Misko Hevery 24e7da4f19 fix(angular-mocks): memory leak in jasmine's DI utils
When using inject/module helper methods in tests, these methods would
leave the injector laying around after the test. Since injector is
the application it can grow very large.
2012-05-14 21:56:22 -07:00
Vojta Jina 7b739c9702 fix($sniffer): report history false on Android < 4
Android has history.pushState, but it does not update the location correctly:
http://code.google.com/p/android/issues/detail?id=17471

Closes #904
2012-05-14 15:12:51 -07:00
Igor Minar c1533ef576 fix($location): support urls with any protocol
The url used for location parsing was quite strict and did not support
custom url schemes like "chrome-extension://". With this change the only
requirement for scheme is that it doesn't contain ":" character.
2012-05-14 14:45:56 -07:00
Igor Minar 679cb8a74a fix($browser/$location): single quote in url causes infinite digest in FF
The real issue is in FF, see https://bugzilla.mozilla.org/show_bug.cgi?id=407172.

FF overly encodes stuff which breaks our expectations and then we fail .url() != currentUrl.absUrl()
comparison unexpectidly, which leads to infinite digest.

The workaround is to correct for this inconsistency in $browser and decode any single quotes in urls.

Closes #920
2012-05-13 21:53:19 -07:00
Igor Minar 4e65635f85 doc($rootScope): fix $digest example 2012-05-08 17:00:25 -07:00
Misko Hevery aa02534865 bug(ie8 docs): docs now work on ie8 2012-05-07 15:43:09 -07:00
Misko Hevery b99f65f64d bug(html5 navigation): broken in Opera
http://my.opera.com/community/forums/topic.dml?id=1185462

Closes# 938
2012-05-07 15:43:09 -07:00
Igor Minar f76474823a chore(release): starting 1.0.0rc9 eggplant-teleportation interation 2012-05-07 00:11:50 -07:00
Igor Minar 8ba1fd87e1 chore(release): cutting the 1.0.0rc8 blooming-touch release 2012-05-07 00:09:20 -07:00
Igor Minar 4d2dd46483 docs(changelog): release notes for 1.0.0rc8 blooming-touch 2012-05-07 00:08:43 -07:00
Igor Minar b24cc63bcb fix(ngSrc,ngHref): binding should set element prop as well as attr
IE9 ignores setAttribute('src', val) calls on img if "ng:src" attribute
is present. It only fetches the image if element property is updated as well.

Closes #935
2012-05-06 23:01:33 -07:00
Igor Minar 49dfdf8f02 fix(ngModel): use keydown/change events on IE9 instead of input
On IE9 the input event is not fired when backspace or delete key are pressed or when
cut is performed. This makes listening on the input event unreliable and therefore
it's better for us to just use keydown/change events instead.

Closes #879
2012-05-06 23:01:33 -07:00
Vojta Jina 5bcb749abb fix(scenario): make browser().location() working if ng-app on other than <html> 2012-05-05 03:30:28 +02:00
Vojta Jina 499a76a08c fix($parse): support methods on falsy primitive types
e.g. zero, false, empty string

- fix tests to be executed with csp true
- fix cps (when more than 5 parts)
2012-05-05 03:30:19 +02:00
Misko Hevery 8e2675029f chore(docs): re-skin main documentation 2012-05-04 16:12:17 -07:00
Misko Hevery d0159454df bug($cookie): set on app base path rather the current path. 2012-05-04 15:50:39 -07:00
Misko Hevery 7f0eb15161 fix($compile): have $observe return registration function 2012-05-04 15:50:39 -07:00
Misko Hevery c4fa487250 feat(bootstrap): support code prettify and dropdown from bootstrap 2012-05-04 15:50:37 -07:00
Misko Hevery cef3535c16 chore(controller): allow setting map of controllers 2012-05-04 15:50:37 -07:00
Misko Hevery fbb499e0a8 chore(module): improved module prefix/suffix code 2012-05-04 15:50:37 -07:00
Misko Hevery e40f8d829f chore(debug): rewrite angular-bootstrap.js to use $script 2012-05-04 15:50:37 -07:00
Igor Minar 9c0418cf1a fix($compile): ignore ws when checking if template has single root
Also add the same error checking for sync templates.

Closes #910
2012-05-04 13:01:55 -07:00
Igor Minar 1564b82b49 style($compile): rename orig*Node to beforeTemplate*Node 2012-05-03 23:40:43 -07:00
Igor Minar b431ee3850 fix($compile): fix replaceWith
the old implementation didn't reattach jquery/jqlite data which caused
things like  to be lost

I tried various implementations but it appears that by reattaching the data
to the new node by copying the expando property is the most reliable of all.
2012-05-03 23:40:43 -07:00
Igor Minar a44d3dcd6a chore(testabilityPatch): print number of leaked references if any 2012-05-03 23:31:28 -07:00
Igor Minar ee579a071a feat(jqLite): support data() getter and data(obj) setter
... just like jquery does
2012-05-03 23:31:28 -07:00
Igor Minar 5df7e6fae5 style(jqLite): clean up the code 2012-05-03 23:31:28 -07:00
Igor Minar fff31d8d61 style($compile): clean up the code and normalize fn names 2012-05-03 23:31:28 -07:00
Igor Minar 9cba23a588 chore(trace): add helper method trace
use it as trace('label') to dump the stack during debugging
2012-05-03 10:07:30 -07:00
Igor Minar 705f4bbf11 fix($compile): attach scope to the directive element when templateUrl and replace=true
We forgot to reattach the scope to the replacement element. This affected only
directives that had templateUrl and replace:true properties.

Reported on the mailing list:
https://groups.google.com/forum/?fromgroups#!topic/angular/zwjLr1msS2Y
http://jsfiddle.net/lukebayes/g9Sh9/
2012-05-03 00:15:26 -07:00
Igor Minar bd530e2257 chore($compile): remove obsolete <<CONTENT>> transclusion
This stuff was never documented and is an accidental leftover from the time
when the compiler was rewritten.

If any code depends on this, it should be rewritten to use ngTransclude directive
intead.
2012-05-03 00:15:26 -07:00
Igor Minar 843f762c57 fix($compile): prevent duplicate directive controller instantiation
Closes #876
2012-05-03 00:15:26 -07:00
Igor Minar beea3a4bed style($compile): rename compiler.js to compile.js 2012-05-02 16:37:48 -07:00
Igor Minar 3bd3cc571d fix(select): don't interfere with selection if not databound
Closes #926
2012-05-02 14:24:43 -07:00
Igor Minar c7f1101520 chore(release): starting the 1.0.0rc8 blooming-touch iteration 2012-05-02 14:21:30 -07:00
Igor Minar 76afa406b1 chore(release): cut 1.0.0rc7 rc-generation release 2012-04-30 16:32:45 -07:00
Igor Minar f3c77858be docs(changelog): release notes for 1.0.0rc7 rc-generation 2012-04-30 15:53:05 -07:00
Igor Minar 96758c1c52 docs(ngCsp): make the CSP docs publicly visible 2012-04-30 15:37:12 -07:00
Igor Minar 006fb4fbeb docs(ngSanitize): fix directive links 2012-04-30 01:09:55 -07:00
Igor Minar 075c089b5c docs(tutorial): update all the remaining steps
I made some diagrams and portions of the text that are stil stale
invisible. We'll fix these in the next relese.
2012-04-30 01:08:15 -07:00
Igor Minar 2b87c814ab feat($parse): CSP compatibility
CSP (content security policy) forbids apps to use eval or
Function(string) generated functions (among other things). For us to be
compatible, we just need to implement the "getterFn" in $parse without
violating any of these restrictions.

We currently use Function(string) generated functions as a speed
optimization. With this change, it will be possible to opt into the CSP
compatible mode using the ngCsp directive. When this mode is on Angular
will evaluate all expressions up to 30% slower than in non-CSP mode, but
no security violations will be raised.

In order to use this feature put ngCsp directive on the root element of
the application. For example:

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

Closes #893
2012-04-27 23:04:24 -07:00
Igor Minar 2b1b257034 chore(server.js): Add CSP support
The support is disabled by default, uncomment relevant lines to enable
it.
2012-04-27 22:04:16 -07:00
Igor Minar 73caf76225 chore(check-size): add a script to check gziped size
this is useful to quickly check the resulting size during development
2012-04-23 11:42:27 -07:00
Igor Minar dbb92efd13 chore(release): start 1.0.0rc7 rc-generation iteration 2012-04-23 11:42:26 -07:00
Vojta Jina 1214084e9d docs(directive): fix transclusion examples 2012-04-21 21:08:30 +02:00
Misko Hevery a18926f986 fix(events): include ie8 in extra event property reset 2012-04-20 17:04:21 -07:00
Misko Hevery b806b30861 fix(bootstrap): rewritten to $script 2012-04-20 17:04:21 -07:00
Misko Hevery 43d15f830f fix(mouseenter): FF no longer throws exceptions 2012-04-20 17:04:21 -07:00
Igor Minar 1d26acb874 chore(release): cutting the 1.0.0rc6 runny-nose release 2012-04-20 15:06:39 -07:00
Igor Minar 983c309542 docs(changelog): release notes for 1.0.0rc6 runny-nose 2012-04-20 15:06:05 -07:00
Igor Minar 904b69c745 fix(select): properly handle empty & unknown options without ngOptions
Previously only when ngOptions was used, we correctly handled situations
when model was set to an unknown value. With this change, we'll add/remove
extra unknown option or reuse an existing empty option (option with value
set to "") when model is undefined.
2012-04-20 14:29:37 -07:00
Igor Minar c65c34ebfe test(selectSpec): clean up and simplify specs 2012-04-20 14:29:36 -07:00
Igor Minar 8ebe5ccd9a feat(jquery): jquery 1.7.2 support 2012-04-20 14:29:36 -07:00
simpulton e61fd1b43a feat($resource): support HTTP PATCH method
Properly serialize data into request body instead of url.

Closes #887
2012-04-20 12:32:33 -07:00
Misko Hevery ce15a3e049 chore(license): update to google 2012-04-20 11:29:34 -07:00
Misko Hevery 46bb08a9d0 fix(compiler): reading comment throws error in ie
Unders some circumstances reading the comment's text throws error.
2012-04-20 11:29:34 -07:00
Misko Hevery 94dd685709 fix(script): Incorrectly reading script text on ie
IE deals with script tags in special way and .text() does not work. Reading the .text property directly fixes the issue.
2012-04-20 11:29:34 -07:00
Misko Hevery dc32ea627e chore(logo): added angular shield logo 2012-04-20 11:29:33 -07:00
Misko Hevery eafe15f54c fix(document): accidental clobbering of document.getAttribute
Closes #877
2012-04-20 11:29:33 -07:00
Chris Dawson 666f326c5d docs(guide/controllers): update w/ controller scope separation 2012-04-20 10:57:26 -07:00
pkozlowski-opensource 908785960d docs(guide/e2e): fix a link to e2e dsl 2012-04-20 10:49:44 -07:00
johnlindquist 5cc245dd80 docs(ngBind): "angular.module.ng.$sanitize" -> "angular.module.ngSanitize.$sanitize" 2012-04-20 10:44:18 -07:00
johnlindquist 0bd0ef7813 docs($compile) "updateh"->"updated" 2012-04-20 10:43:58 -07:00
johnlindquist 0c7252f929 docs(ngBind): "makes make" -> "makes" 2012-04-20 10:43:41 -07:00
Vojta Jina b94fb5c8c1 docs($resource): fix the example 2012-04-15 09:42:54 -07:00
Igor Minar c322735f83 chore(release): starting the 1.0.0rc6 runny-nose iteration 2012-04-12 03:57:14 -07:00
Igor Minar 9260b4937d chore(release): cutting the 1.0.0rc5 reality-distortion release 2012-04-12 03:56:28 -07:00
Igor Minar e9ccec76a6 docs(changelog): release notes for 1.0.0rc5 reality-distortion 2012-04-12 03:26:10 -07:00
Igor Minar 2037facc99 docs(tutorial): update step-04 to v1.0 2012-04-12 02:45:12 -07:00
Igor Minar b2d0a386f6 style(docs-scenario.html): rename <angular/> to AngularJS in the title 2012-04-12 02:36:03 -07:00
Igor Minar 6d7e7fdea6 fix($location): properly rewrite urls in html5 mode with base url set
previously we were doing all kinds of checks to see if we should rewrite the url or not and we
were missing many scenarios. not any more.

with this change, we rewrite the url unless:
- the href is not set
- link has target attribute
- the absolute url of the link doesn't match the absolute prefix for all urls in our app

This also means that ng-ext-link attribute which we previously used to distinguish external
links from app links is not necessary any more. apps can just set target=_self to prevent
rewriting.

BREAKING CHANGE: ng-ext-link directive was removed because it's unnecessary

apps that relied on ng-ext-link should simply replace it with target=_self
2012-04-12 02:36:03 -07:00
Igor Minar df72852f34 fix(e2eRunner): $browser.location should delegate to apps $location
previously it would create a new instance which wasn't configured as the one in the app,
which resulted in incorrect values being returned in html5 mode with base url set
2012-04-12 02:36:03 -07:00
simpulton c4f6ccb065 docs($compile): fixed typo 2012-04-11 23:48:53 -07:00
Igor Minar 0c49bbdc38 test(ngView): fix failing e2e tests 2012-04-11 21:27:55 -07:00
Igor Minar 7d074a3775 docs($http): fix return types 2012-04-11 17:29:16 -07:00
Igor Minar dceafd32ee feat($http): expose the defaults config as $http.defaults
Often it is impossible to set the http defaults during the config phase,
because the config info is not available at this time.

A good example is authentication - often the app needs to bootstrap,
allow user to enter credentials and only then it gains access to
session token which then should be sent to the server with every request.
Without having the ability to set the defaults at runtime, the developer
either has to resort to hacks, or has to set the session token header
with every request made by the app.
2012-04-11 17:29:16 -07:00
Thibault Leruitte 0a5050eb3c fix($location): don't rewrite links to different base paths
links to different base paths should not be left untouched
2012-04-11 17:27:32 -07:00
Vojta Jina 7c430c5ed0 chore(release scripts): group changelog only if more than 1 entry 2012-04-11 16:12:58 -07:00
Vojta Jina 93d62860e9 fix(input.radio): support 2-way binding in a repeater
Closes #869
2012-04-11 15:50:52 -07:00
Vojta Jina 5bcd719866 chore(ngSanitize): extract $sanitize, ngBindHtml, linkyFilter into a module
Create build for other modules as well (ngResource, ngCookies):
- wrap into a function
- add license
- add version

Breaks `$sanitize` service, `ngBindHtml` directive and `linky` filter were moved to the `ngSanitize` module. Apps that depend on any of these will need to load `angular-sanitize.js` and include `ngSanitize` in their dependency list: `var myApp = angular.module('myApp', ['ngSanitize']);`
2012-04-11 15:50:47 -07:00
Igor Minar e1743cc837 docs($compile): fix typo in the docs templateURL -> templateUrl 2012-04-11 11:23:48 -07:00
Igor Minar 52ee1ab5eb chore(*): remove dead code and fix code style issues 2012-04-10 16:52:12 -07:00
Vojta Jina fcc556df37 docs(guide.forms): fix the forms dev guide to use ng-disabled 2012-04-10 13:42:17 -07:00
Igor Minar 5c0ec9d06d docs(angular.bootstrap): fix typos and errors 2012-04-10 13:21:29 -07:00
Igor Minar ac2f0cece6 docs(tutorial): fix typos in steps 2 and 3 2012-04-10 06:04:13 -07:00
Igor Minar fbaa1968b7 chore($browser): remove the addJs method
this was never meant to be a public api used by apps. I refactored
the code to hide the functionality.

BREAKING CHANGE: $browser.addJs method was removed

apps that depended on this functionality should either use many of the
existing script loaders or create a simple helper method specific to the
app.
2012-04-09 17:59:47 -07:00
Igor Minar 13d5528a5f chore($browser): remove the addCss method
this api was never supposed to be public. nobody should be relying
on it.

I'm removing it since angular doesn't need it.

BREAKING CHANGE: $browser.addCss was removed

apps the depend on this functionality should write a simple utility
function specific to the app (see this diff for hints).
2012-04-09 15:21:46 -07:00
Igor Minar b5406d276d chore(ngBind): remove obsolete test
this test is not testing what it claims it is.

we don't need it any more
2012-04-09 11:49:51 -07:00
Igor Minar 0f89383d98 chore(tests): rename all directive names to the normalized form 2012-04-09 11:48:54 -07:00
Igor Minar 10daefc6f4 fix(ngBindHtml): clear contents when model is falsy
Closes #864
2012-04-09 09:52:28 -07:00
Igor Minar dc7b764d4d test(ngBindSpec): correct tests + split them up 2012-04-09 09:52:28 -07:00
Igor Minar 82d90a4096 fix(docs): change all directive references to use the normalized names 2012-04-09 09:52:27 -07:00
Igor Minar 7468bcb80b chore(release): starting 1.0.0rc5 reality-distortion iteration 2012-04-09 08:59:31 -07:00
Igor Minar bd4a4d390c chore(release): cutting the 1.0.0rc4 insomnia-induction release 2012-04-05 11:46:36 -07:00
Igor Minar 94fca76a08 docs(changelog): release notes for 1.0.0rc4 insomnia-induction 2012-04-05 11:45:34 -07:00
Igor Minar 1c8c083404 fix(docs): move $cookies and $cookieStore docs to module 2012-04-05 11:33:42 -07:00
Igor Minar 0f2de12273 chore(docs): add nonminified jquery debug version of docs 2012-04-05 11:33:42 -07:00
Igor Minar 1bbc67ef6c chore(Rakefile): fix and improve file rewriting code 2012-04-05 10:22:27 -07:00
Igor Minar 637817e3ba fix(Rakefile): move 'use strict'; flag into the angular closure
closure compiler is stubborn and puts the flag to the top of the file, so
we have to post-process the minified file to move the flag into the angular
closure.
2012-04-05 10:22:27 -07:00
Vojta Jina 86182a9415 feat($http): add withCredentials config option 2012-04-04 16:13:02 -07:00
Igor Minar 15ecc6f366 feat($route): allow chaining of whens and otherwise
Previously one had to write:

$routeProvider.when('/foo', {...});
$routeProvider.when('/bar', {...});
$routeProvider.otherwise({...});

After this change it's just:

$routeProvider.
    when('/foo', {...}).
    when('/bar', {...}).
    otherwise({...});

Breaks #when which used to return the route definition object but now
returns self. Returning the route definition object is not very useful
so its likely that nobody ever used it.
2012-04-04 16:10:44 -07:00
Igor Minar 53b2254ea7 docs(tutorial): update tutorial intro + steps 0-3
also contains all kinds of fixes that I had to make in the docs app to
get the tutorial to render correctly
2012-04-04 15:59:18 -07:00
Igor Minar 6336b6e89e chore(docs): restore old tutorial ngdoc files 2012-04-04 15:59:18 -07:00
Igor Minar fdf17d729f fix(docs): remove ngModelInstant from all examples
just fixing leftover code after the removal of ngModelInstant
2012-04-04 15:56:15 -07:00
Vojta Jina 85776c0d37 refactor(ngHref, ngSrc): remove duplicate tests 2012-04-04 15:01:27 -07:00
Vojta Jina 02cf958a07 chore(directive): correct file names for booleanAttrs 2012-04-04 14:58:27 -07:00
Vojta Jina 8fe4295a06 refactor(ngInclude): correct the tests 2012-04-04 14:58:07 -07:00
Vojta Jina dcb8e0767f fix(booleanAttrs): convert to boolean
jQuery's attr() does not handle 0 as false, when it comes to boolean attrs.
2012-04-04 08:26:28 -07:00
Misko Hevery 21b77ad5c2 fix(form): preperly clean up when invalid widget is removed
Removing invalid widget sometimes resulted in improper cleanup of the form state.
2012-04-03 23:28:05 -07:00
Misko Hevery 2f5dba488e fix(ng-href): copy even if no binding
Closes# 850

fixed an issue where ng-href would not copy its content into href if it did not contain binding.
2012-04-03 16:02:20 -07:00
Misko Hevery 7e86eacf30 fix($compile): relax the restriction that directives can not add siblings
Relax the restriction that directives can not add siblings
2012-04-03 16:02:20 -07:00
Vojta Jina 15c1fe3929 refactor(ngView): remove extra $watch, refactor one ugly test 2012-04-03 10:10:44 -07:00
Vojta Jina 428f2b5636 feat(ngInclude): allow ngInclude on css class
And make it terminal so that it does not compile its content, which would cause leaks.
2012-04-03 10:10:44 -07:00
Vojta Jina 199ac26986 fix(ngInclude): fire $includeContentLoaded on proper (child) scope 2012-04-03 10:10:44 -07:00
Vojta Jina 5f70d615a5 refactor(ngInclude): remove scope attribute
The purpose of allowing the scope to be specified was to enable the $route service to work
together with ngInclude. However the functionality of creating scopes was in the recent past
moved from the $route service to the ngView directive, so currently there is no valid use case
for specifying the scope for ngInclude. In fact, allowing the scope to be defined can under
certain circumstances lead to memory leaks.

Breaks ngInclude does not have scope attribute anymore.
2012-04-03 10:10:44 -07:00
Vojta Jina 06d0955074 feat(ngModel): update model on each key stroke (revert ngModelInstant)
It turns out that listening only on "blur" event is not sufficient in many scenarios,
especially when you use form validation you always had to use ngModelnstant
e.g. if you want to disable a button based on valid/invalid form.

The feedback we got from our apps as well as external apps is that the
ngModelInstant should be the default.

In the future we might provide alternative ways of suppressing updates
on each key stroke, but it's not going to be the default behavior.

Apps already using the ngModelInstant can safely remove it from their
templates. Input fields without ngModelInstant directive will start propagating
the input changes into the model on each key stroke.
2012-04-03 10:10:44 -07:00
Vojta Jina a22e0699be feat($sniffer): add hasEvent method for sniffing events
Skip changelog
2012-04-03 10:10:44 -07:00
Brad Green 28ff7c3a66 Doc fixes in bootstrap
Now makes sense.
2012-04-03 07:07:49 -07:00
Mykhailo Kotsur 59ae8adb3c fix(scenario): dev secenario tests
closes #843

Fixed failed e2e test
2012-04-02 16:10:15 -07:00
Igor Minar c0b78478a0 fix($q): $q.reject should forward callbacks if missing
$q.reject('some reason').then() should not blow up, but correctly
forward the callbacks instead.

Closes #845
2012-04-02 10:14:04 -07:00
Mykhailo Kotsur 59fa40ec0e fix($location): search setter should not double-encode the value
By mistake both the setter and helper function that composes the whole
url were encoding the search values.

Closes #751
2012-04-02 08:35:30 -07:00
Igor Minar a1f7f5d4d0 chore(release): start 1.0.0rc4 insomnia-induction iteration 2012-03-30 13:23:36 -07:00
Igor Minar 20687aa5f6 chore(release): cutting 1.0.0rc3 barefoot-telepathy 2012-03-29 16:10:40 -07:00
Igor Minar fc52b81d52 fix(docs): update the example widget regexp for detecting angular.js url
so that we don't show angular-cookies instead of angular.js
2012-03-29 16:10:40 -07:00
Igor Minar ae1aee2b6c fix(FormController): ask for dependency to fool the BC module 2012-03-29 16:10:40 -07:00
Igor Minar 423242017e fix(docs): properly rewrite urls in doc examples at docs-next 2012-03-29 16:10:40 -07:00
Vojta Jina 95c5df5958 fix(ngValue): bind properly inside ng-repeat 2012-03-29 14:05:19 -07:00
Igor Minar 2cb907a836 fix($injector): properly infer dependencies from fn with no args
Previously if there was a white-space in fn: fn( ) {} we failed to infer no args.

This was originally reported by recht, but I decided to use a different fix.

Closes #829
2012-03-29 11:21:04 -07:00
Igor Minar 2f2fd465a4 docs(changelog): release notes for 1.0.0rc3 barefoot-telepathy 2012-03-29 08:10:28 -07:00
Vojta Jina 6da355c3e1 refactor($compile): move methods of attr object into prototype
We have many instances of this object and we clone them as well (e.g. ng-repeat).
This should save some memory and performance as well.

Double prefixed private properties of attr object:
attr.$element -> attr.$$element
attr.$observers -> attr.$$observers

Update shallowCopy to not copy $$ properties and allow passing optional destination object.
2012-03-29 07:30:32 -07:00
Vojta Jina f2106692b1 fix($compile): properly clone attr.$observers in ng-repeat
The `attr` object was only shallow copied which caused all observers to be shared.
Fixing similar issue in ng-* boolean attributes as well as ng-src and ng-href.
2012-03-29 07:30:32 -07:00
Vojta Jina 4557881cf8 chore(release scripts): auto release scripts 2012-03-29 07:22:13 -07:00
Igor Minar af0ad6561c refactor(fromJson/toJson): move the contents of these files into Angular.js
these files are now mostly empty so it doesn't make sense to keep them
separated from other helper functions
2012-03-28 16:57:34 -07:00
Igor Minar 35125d2513 refactor(toJson): use native JSON.stringify
Instead of using our custom serializer we now use the native one and
use the replacer function to customize the serialization to preserve
most of the previous behavior (ignore $ and $$ properties as well
as window, document and scope instances).
2012-03-28 16:57:22 -07:00
Igor Minar 87f5c6e5b7 refactor(fromJson): always use native JSON.parse
This breaks IE7 for which you can use polyfill:

https://github.com/douglascrockford/JSON-js

<!--[if lt IE 8]>
<script src="json2.min.js"></script>
<![endif]-->

or

http://bestiejs.github.com/json3/

<!--[if lt IE 8]>
<script src="json3.min.js"></script>
<![endif]-->
2012-03-28 16:30:38 -07:00
Igor Minar a8a750ab05 feat($http): make the transform defaults to an array
$httpProvider.defaults.transformRequest and $httpProvider.defaults.transformResponse
are now arrays containing single function. This makes it easy to add an
extra transform fn.

adding an extra fn before had to be done in this cluncky way:

$httpProvider.defaults.transformResponse =
[$httpProvider.defaults.transformResponse, myTransformFn];

after this change, it's simply:

$httpProvider.defaults.transformResponse.push(myTransformFn);
2012-03-28 16:30:38 -07:00
Igor Minar 13a95ae499 style($http): remove redundant 'use strict' header 2012-03-28 16:30:31 -07:00
Igor Minar da9f4dfcf4 feat(TzDate): add support for toISOString method 2012-03-28 16:30:31 -07:00
Igor Minar ac4318a2fa refactor(fromJson/date filter): move date string logic to date filter
Breaks angular.fromJson which doesn't deserialize date strings into date objects.

This was done to make fromJson compatible with JSON.parse.

If you do require the old behavior - if at all neeeded then because of
json deserialization of XHR responses - then please create a custom
$http transform:

$httpProvider.defaults.transformResponse.push(function(data) {
  // recursively parse dates from data object here
  // see code removed in this diff for hints
});

Closes #202
2012-03-28 16:30:30 -07:00
Misko Hevery bb2fa6f63f fix(i18n e2e tests): 2012-03-28 11:24:47 -07:00
Igor Minar ba59ef4950 docs(examples): update example apps 2012-03-28 11:24:47 -07:00
Igor Minar 8b93541522 style(Rakefile): use snake_case in ruby code 2012-03-28 11:16:36 -07:00
Misko Hevery 7b22d59b4a chore(ngCookies): moved to module 2012-03-28 11:16:36 -07:00
Misko Hevery 798bca62c6 chore(resource): moved to module 2012-03-28 11:16:36 -07:00
Misko Hevery 8218c4b60b chore(Rakefile): get ready for modules 2012-03-28 11:16:36 -07:00
Misko Hevery 2430f52bb9 chore(module): move files around in preparation for more modules 2012-03-28 11:16:35 -07:00
Brad Green 944098a4e0 Updated manual bootstrap document
Explained why you'd want to manually bootstrap, added contrasting
example for automatic vs manual methods.
2012-03-27 18:06:00 -07:00
Brad Green 2ce0485e6f Rewrite of Automatic Initialization doc
Added examples, explained the reasons why you initialize the whole app
or parts of the page.
2012-03-27 08:28:34 -07:00
Vojta Jina a08cbc02e7 feat($compile): do not interpolate boolean attributes, rather evaluate them
So that we can have non string values, e.g. ng-value="true" for radio inputs

Breaks boolean attrs are evaluated rather than interpolated

To migrate your code, change: <input ng-disabled="{{someBooleanVariable}}">
to: <input ng-disabled="someBooleanVariabla">


Affected directives:

* ng-multiple
* ng-selected
* ng-checked
* ng-disabled
* ng-readonly
* ng-required
2012-03-26 21:14:09 -07:00
Vojta Jina 55027132f3 refactor(ngBindAttr): remove
Breaks ng-bind-attr directive removed
2012-03-26 21:14:09 -07:00
Vojta Jina 09e175f02c feat(ngValue): allow radio inputs to have non string values
Closes #816
2012-03-26 21:14:09 -07:00
Mykhailo Kotsur 5c5b1183c8 docs(guide/module): fix syntax error and expectation in test example 2012-03-26 16:06:46 -07:00
Mykhailo Kotsur f04142ea28 docs(guide/unit-testing): fixed typo in code example 2012-03-26 16:06:16 -07:00
Igor Minar aaedefb92e refactor($sniffer): make $sniffer service private
This service has been accidentaly documented in the past, it should not be considered
to be public api.

I'm also removing fallback to Modernizr since we don't need it.

Breaks any app that depends on this service and its fallback to Modernizr, please
migrate to custom "Modernizr" service:

    module.value('Modernizr', function() { return Modernizr; });
2012-03-26 15:43:59 -07:00
Igor Minar d54dfecb00 feat($controller): support controller registration via $controllerProvider
It's now possible to register controllers as:

.register('MyCtrl', function($scope) { ... });
// or
.register('MyCtrl', ['$scope', function($scope) { ... });

Additionally a module loader shortcut api was added as well:

myModule.controller('MyCtr', function($scope) { ... });
2012-03-26 15:23:29 -07:00
Igor Minar 4b8d926062 feat(assertArgFn): should support array annotated fns 2012-03-26 12:21:42 -07:00
Igor Minar 74c84501ed doc(guide/module): fix typo 2012-03-23 16:57:24 -07:00
Igor Minar 4581b79bbd doc(guide/controller): fix examples 2012-03-23 16:54:48 -07:00
Manuel Woelker 2be8847ef6 doc(guide): order topic list in guide sidebar in accordance with overview
Closes #405
2012-03-23 16:31:33 -07:00
Igor Minar cb2ad9abf2 fix(init): use jQuery#ready for init if available
Closes #818
2012-03-23 15:41:37 -07:00
Misko Hevery 73c8593077 feat(http): added params parameter
The params parameter can now be used to serialize parameters in the URLs. The serialization does proper escaping and JSON encoding if it is an object.
2012-03-23 14:21:43 -07:00
Misko Hevery ac75079e21 fix(q): resolve all of nothing to nothing
$q.all([]) no longer throws exception and resolves to empty array []
2012-03-23 14:21:43 -07:00
Igor Minar 5390fb37d2 fix($compile): create new (isolate) scopes for directives on root elements
previously we would not create them and it's causing all kinds of issues and accidental leaks

Closes #817
2012-03-23 11:46:54 -07:00
Igor Minar 8d7e694849 fix(forEach): should ignore prototypically inherited properties
Closes #813
2012-03-22 16:39:36 -07:00
Igor Minar 5fdab52dd7 feat(jqLite): make injector() and scope() work with the document object
For typical app that has ng-app directive on the html element, we now can do:

angular.element(document).injector() or .injector()
angular.element(document).scope() or .scope()

instead of:

angular.element(document.getElementsByTagName('html')[0]).injector()
...
2012-03-22 16:39:36 -07:00
Vojta Jina 541bedd1a9 refactor(ngController): remove unused deps 2012-03-22 16:29:31 -07:00
Igor Minar 98e18a64aa docs(cookbook/form): fix the example
Closes #712
2012-03-21 13:52:11 -07:00
Igor Minar 0a45bff472 chore(docs): switch disqus id from angularjs to angularjs-next 2012-03-21 13:46:35 -07:00
Igor Minar 263524d381 docs(changelog): fix rc2 release date 2012-03-20 17:21:41 -07:00
Igor Minar 52c59cf0ce chore(release): start 1.0.0rc barefoot-telepathy iteration 2012-03-20 16:02:49 -07:00
Igor Minar c5f8edfe03 chore(release): cutting the 1.0.0rc2 silence-absorption release 2012-03-20 15:38:57 -07:00
Igor Minar 69f0aa899d docs(changelog): release notes for 1.0.0rc2 silence-absorption 2012-03-20 15:25:31 -07:00
Daniel Zen e7cd0bcc5a docs(guide/controllers): add a section on testing controllers 2012-03-20 15:23:58 -07:00
Vojta Jina ade6c45275 feat(input.radio): Allow value attribute to be interpolated 2012-03-20 14:39:23 -07:00
Igor Minar 9eafd10fcd docs(guide/location): fix example 2012-03-20 12:05:57 -07:00
Igor Minar 3436c027f2 docs(guide/started): fix examples 2012-03-20 11:30:21 -07:00
Igor Minar 6a8749e65a refactor($resource): unify and simplify the code 2012-03-20 11:07:38 -07:00
Igor Minar 1a5bebd927 fix($http): don't send Content-Type header when no data
When a http request has no data (body), we should not send the
Content-Type header as it causes problems for some server-side
frameworks.

Closes #749
2012-03-20 11:07:38 -07:00
Igor Minar 83155e8fbe style(ResourceSpec): style clean up 2012-03-20 11:07:37 -07:00
Igor Minar 6d6f875345 fix($resource): support escaping of ':' in resource url
So one can how define cors/jsonp resources with port number as:

resource.route('http://localhost\\:8080/Path')
2012-03-20 11:07:37 -07:00
Igor Minar a4fe51da3b feat($route): when matching consider trailing slash as optional
This makes for a much more flexible route matching:

- route /foo matches /foo and redirects /foo/ to /foo
- route /bar/ matches /bar/ and redirects /bar to /bar/

Closes #784
2012-03-20 11:07:37 -07:00
Igor Minar ee5a5352fd fix(e2e runner): fix typo that caused errors on IE8
Closes #806
2012-03-20 11:07:37 -07:00
Igor Minar 9cb2195e61 fix($compile): don't touch static element attributes
Compiler should not reassign values to element attributes if its not neccessary due
to interpolation or special attribute magic (ng-src -> src)

This resolves several issues on IE caused by reassigning script.src attribute which
caused all of the scripts to be reloaded.
2012-03-20 11:07:36 -07:00
Igor Minar 15213ec212 fix($log): avoid console.log.apply calls in IE
In IE window.console.log and friends are functions that don't have apply or call fns.

For this reason we have to treat them specially and do our best to log at least
something when running in this browser.

Closes #805
2012-03-20 11:07:36 -07:00
Igor Minar 9171c76bb4 style($log): reformat code for readability 2012-03-20 11:07:35 -07:00
Igor Minar 64fb1f2620 docs(filters): use ng-model-instant in live examples
Closes #807
2012-03-20 11:07:35 -07:00
Vojta Jina f49eaf8bf2 fix($compile): Merge interpolated css class when replacing an element 2012-03-20 10:39:43 -07:00
Vojta Jina f701ce08f9 fix(matchers.toHaveClass): Correct reference to angular.mock.dump 2012-03-19 17:26:29 -07:00
Misko Hevery 1cc0e4173d bug(ie7): incorrectly set all inputs to disabled
In ie7 all of the input fields are set to readonly and disabled, because ie7 enumerates over all attributes even if the are not declared on the element.
2012-03-19 15:49:42 -07:00
Misko Hevery d4ae7988da chore(parseInt): cleanup parseInt() for our int() 2012-03-19 11:41:23 -07:00
Misko Hevery 5ac14f633a fix(json): added support for iso8061 timezone
Added support of timezone in dates not just zulu timezone.

This fixes issues for date filter which uses json deserialization under the hood. (for now)

Closes #/800
2012-03-19 11:41:10 -07:00
Misko Hevery 9918b748be fix(compiler): allow transclusion of root elements
Fixed an issue where a directive that uses transclusion (such as ngRepeat) failed to link if it was declared on the root element of the compilation tree. (For example ngView or ngInclude including template where ngRepeat was the top most element).
2012-03-19 11:35:10 -07:00
Misko Hevery 6ecac8e71a fix(select): multiselect failes to update view on selection insert
In multiselect when the underlying selection array push/pops an element the view did not re-render since the array reference stayed the same.
2012-03-19 11:35:10 -07:00
Misko Hevery 823adb2319 fix(ngForm): alias name||ngForm
form directive was requiring name attribute even when invoked as attribute, resulting in unnecessary duplication
2012-03-19 11:35:09 -07:00
Misko Hevery 21e74c2d2e fix(ngView): controller not published
corrected omitted assignment of controller to the element data object. Without this fix the controller created by ngView is not accessible from the browser debugger.
2012-03-19 11:35:09 -07:00
Misko Hevery 6c5a05ad49 feat(jqLite): add .controller() method
extend JQuery with .controller() method which retrieves the closest controller for a given element
2012-03-19 11:35:09 -07:00
Vojta Jina 192ff61f5d feat(scope.$eval): Allow passing locals to the expression 2012-03-18 23:46:30 -07:00
Igor Minar 935c1018da fix(ngRepeat): correct variable reference in error message
Closese #803
2012-03-17 15:57:55 -07:00
Igor Minar 78a6291666 docs(scope): add $destroy event docs 2012-03-16 15:32:14 -07:00
Igor Minar 53b6f522a5 fix(ngDocSpec): fix broken tests 2012-03-16 15:32:14 -07:00
961 changed files with 95299 additions and 28452 deletions
+4
View File
@@ -0,0 +1,4 @@
{
"directory": "bower_components",
"json": "bower.json"
}
-10
View File
@@ -1,10 +0,0 @@
<?xml version="1.0" encoding="UTF-8" standalone="no"?>
<launchConfiguration type="org.eclipse.ui.externaltools.ProgramBuilderLaunchConfigurationType">
<booleanAttribute key="org.eclipse.debug.ui.ATTR_LAUNCH_IN_BACKGROUND" value="false"/>
<booleanAttribute key="org.eclipse.ui.externaltools.ATTR_BUILDER_ENABLED" value="true"/>
<stringAttribute key="org.eclipse.ui.externaltools.ATTR_BUILD_SCOPE" value="${working_set:&lt;?xml version=&quot;1.0&quot; encoding=&quot;UTF-8&quot;?&gt;&#10;&lt;launchConfigurationWorkingSet editPageId=&quot;org.eclipse.ui.resourceWorkingSetPage&quot; factoryID=&quot;org.eclipse.ui.internal.WorkingSetFactory&quot; id=&quot;1262905463390_2&quot; label=&quot;workingSet&quot; name=&quot;workingSet&quot;&gt;&#10;&lt;item factoryID=&quot;org.eclipse.ui.internal.model.ResourceFactory&quot; path=&quot;/angular.js/test&quot; type=&quot;2&quot;/&gt;&#10;&lt;item factoryID=&quot;org.eclipse.ui.internal.model.ResourceFactory&quot; path=&quot;/angular.js/src&quot; type=&quot;2&quot;/&gt;&#10;&lt;/launchConfigurationWorkingSet&gt;}"/>
<stringAttribute key="org.eclipse.ui.externaltools.ATTR_LOCATION" value="${workspace_loc:/angular.js}/test.sh"/>
<stringAttribute key="org.eclipse.ui.externaltools.ATTR_RUN_BUILD_KINDS" value="full,incremental,auto,"/>
<booleanAttribute key="org.eclipse.ui.externaltools.ATTR_TRIGGERS_CONFIGURED" value="true"/>
<stringAttribute key="org.eclipse.ui.externaltools.ATTR_WORKING_DIRECTORY" value="${workspace_loc:/angular.js}"/>
</launchConfiguration>
-10
View File
@@ -1,10 +0,0 @@
<?xml version="1.0" encoding="UTF-8" standalone="no"?>
<launchConfiguration type="org.eclipse.ui.externaltools.ProgramBuilderLaunchConfigurationType">
<booleanAttribute key="org.eclipse.debug.ui.ATTR_LAUNCH_IN_BACKGROUND" value="false"/>
<booleanAttribute key="org.eclipse.ui.externaltools.ATTR_BUILDER_ENABLED" value="false"/>
<stringAttribute key="org.eclipse.ui.externaltools.ATTR_BUILD_SCOPE" value="${working_set:&lt;?xml version=&quot;1.0&quot; encoding=&quot;UTF-8&quot;?&gt;&#10;&lt;resources&gt;&#10;&lt;item path=&quot;/angular.js/perf&quot; type=&quot;2&quot;/&gt;&#10;&lt;item path=&quot;/angular.js/src&quot; type=&quot;2&quot;/&gt;&#10;&lt;/resources&gt;}"/>
<stringAttribute key="org.eclipse.ui.externaltools.ATTR_LOCATION" value="${workspace_loc:/angular.js/perf.sh}"/>
<stringAttribute key="org.eclipse.ui.externaltools.ATTR_RUN_BUILD_KINDS" value="full,incremental,auto,"/>
<booleanAttribute key="org.eclipse.ui.externaltools.ATTR_TRIGGERS_CONFIGURED" value="true"/>
<stringAttribute key="org.eclipse.ui.externaltools.ATTR_WORKING_DIRECTORY" value="${workspace_loc:/angular.js}"/>
</launchConfiguration>
-11
View File
@@ -1,11 +0,0 @@
<?xml version="1.0" encoding="UTF-8" standalone="no"?>
<launchConfiguration type="org.eclipse.ui.externaltools.ProgramBuilderLaunchConfigurationType">
<stringAttribute key="org.eclipse.debug.core.ATTR_REFRESH_SCOPE" value="${working_set:&lt;?xml version=&quot;1.0&quot; encoding=&quot;UTF-8&quot;?&gt;&#10;&lt;resources&gt;&#10;&lt;item path=&quot;/angular.js/build&quot; type=&quot;2&quot;/&gt;&#10;&lt;/resources&gt;}"/>
<booleanAttribute key="org.eclipse.debug.ui.ATTR_LAUNCH_IN_BACKGROUND" value="false"/>
<booleanAttribute key="org.eclipse.ui.externaltools.ATTR_BUILDER_ENABLED" value="true"/>
<stringAttribute key="org.eclipse.ui.externaltools.ATTR_BUILD_SCOPE" value="${working_set:&lt;?xml version=&quot;1.0&quot; encoding=&quot;UTF-8&quot;?&gt;&#10;&lt;resources&gt;&#10;&lt;item path=&quot;/angular.js/docs&quot; type=&quot;2&quot;/&gt;&#10;&lt;item path=&quot;/angular.js/src&quot; type=&quot;2&quot;/&gt;&#10;&lt;/resources&gt;}"/>
<stringAttribute key="org.eclipse.ui.externaltools.ATTR_LOCATION" value="${workspace_loc:/angular.js/gen_docs.sh}"/>
<stringAttribute key="org.eclipse.ui.externaltools.ATTR_RUN_BUILD_KINDS" value="full,incremental,auto,"/>
<booleanAttribute key="org.eclipse.ui.externaltools.ATTR_TRIGGERS_CONFIGURED" value="true"/>
<stringAttribute key="org.eclipse.ui.externaltools.ATTR_WORKING_DIRECTORY" value="${workspace_loc:/angular.js}"/>
</launchConfiguration>
-7
View File
@@ -1,7 +0,0 @@
<?xml version="1.0" encoding="UTF-8" standalone="no"?>
<launchConfiguration type="org.eclipse.ui.externaltools.ProgramLaunchConfigurationType">
<stringAttribute key="org.eclipse.debug.core.ATTR_REFRESH_SCOPE" value="${working_set:&lt;?xml version=&quot;1.0&quot; encoding=&quot;UTF-8&quot;?&gt;&#10;&lt;resources&gt;&#10;&lt;item path=&quot;/angular.js/docs&quot; type=&quot;2&quot;/&gt;&#10;&lt;/resources&gt;}"/>
<stringAttribute key="org.eclipse.ui.externaltools.ATTR_LAUNCH_CONFIGURATION_BUILD_SCOPE" value="${none}"/>
<stringAttribute key="org.eclipse.ui.externaltools.ATTR_LOCATION" value="${workspace_loc:/angular.js/gen_docs.sh}"/>
<stringAttribute key="org.eclipse.ui.externaltools.ATTR_WORKING_DIRECTORY" value="${workspace_loc:/angular.js}"/>
</launchConfiguration>
-6
View File
@@ -1,6 +0,0 @@
<?xml version="1.0" encoding="UTF-8" standalone="no"?>
<launchConfiguration type="org.eclipse.ui.externaltools.ProgramLaunchConfigurationType">
<stringAttribute key="org.eclipse.ui.externaltools.ATTR_LOCATION" value="${workspace_loc:/angular.js/lib/jsl/jsl}"/>
<stringAttribute key="org.eclipse.ui.externaltools.ATTR_TOOL_ARGUMENTS" value="-conf lib/jsl/jsl.default.conf"/>
<stringAttribute key="org.eclipse.ui.externaltools.ATTR_WORKING_DIRECTORY" value="${workspace_loc:/angular.js}"/>
</launchConfiguration>
+2 -1
View File
@@ -10,6 +10,7 @@ performance/temp*.html
*~
angular.js.tmproj
node_modules
jsTestDriver*.conf
angular.xcodeproj
.idea
libpeerconnection.log
npm-debug.log
-47
View File
@@ -1,47 +0,0 @@
<?xml version="1.0" encoding="UTF-8"?>
<projectDescription>
<name>angular.js</name>
<comment></comment>
<projects>
</projects>
<buildSpec>
<buildCommand>
<name>org.eclipse.wst.jsdt.core.javascriptValidator</name>
<arguments>
</arguments>
</buildCommand>
<buildCommand>
<name>org.eclipse.ui.externaltools.ExternalToolBuilder</name>
<triggers>auto,full,incremental,</triggers>
<arguments>
<dictionary>
<key>LaunchConfigHandle</key>
<value>&lt;project&gt;/.externalToolBuilders/docs.launch</value>
</dictionary>
</arguments>
</buildCommand>
<buildCommand>
<name>org.eclipse.ui.externaltools.ExternalToolBuilder</name>
<triggers>auto,full,incremental,</triggers>
<arguments>
<dictionary>
<key>LaunchConfigHandle</key>
<value>&lt;project&gt;/.externalToolBuilders/JSTD_Tests.launch</value>
</dictionary>
</arguments>
</buildCommand>
<buildCommand>
<name>org.eclipse.ui.externaltools.ExternalToolBuilder</name>
<triggers>auto,full,incremental,</triggers>
<arguments>
<dictionary>
<key>LaunchConfigHandle</key>
<value>&lt;project&gt;/.externalToolBuilders/JSTD_perf.launch</value>
</dictionary>
</arguments>
</buildCommand>
</buildSpec>
<natures>
<nature>org.eclipse.wst.jsdt.core.jsNature</nature>
</natures>
</projectDescription>
-10
View File
@@ -1,10 +0,0 @@
<?xml version="1.0" encoding="UTF-8"?>
<classpath>
<classpathentry excluding="test/" kind="src" path="src"/>
<classpathentry excluding="docs-data.js|docs-scenario.js" kind="src" path="docs"/>
<classpathentry excluding="test/" kind="src" path="test"/>
<classpathentry kind="src" path="test/test"/>
<classpathentry kind="con" path="org.eclipse.wst.jsdt.launching.JRE_CONTAINER"/>
<classpathentry kind="con" path="org.eclipse.wst.jsdt.launching.baseBrowserLibrary"/>
<classpathentry kind="output" path=""/>
</classpath>
@@ -1,16 +0,0 @@
#Mon Jan 24 10:31:47 PST 2011
activeContentFilterList=*.makefile,makefile,*.Makefile,Makefile,Makefile.*,*.mk,MANIFEST.MF
addNewLine=true
convertActionOnSaave=AnyEdit.CnvrtTabToSpaces
eclipse.preferences.version=1
inActiveContentFilterList=
javaTabWidthForJava=true
org.eclipse.jdt.ui.editor.tab.width=2
projectPropsEnabled=false
removeTrailingSpaces=true
replaceAllSpaces=false
replaceAllTabs=false
saveAndAddLine=true
saveAndConvert=true
saveAndTrim=true
useModulo4Tabs=false
@@ -1 +0,0 @@
org.eclipse.wst.jsdt.launching.JRE_CONTAINER
@@ -1 +0,0 @@
Global
+19
View File
@@ -0,0 +1,19 @@
language: node_js
node_js:
- 0.10
env:
global:
- SAUCE_USERNAME=angular-ci
- SAUCE_ACCESS_KEY=9b988f434ff8-fbca-8aa4-4ae3-35442987
- SAUCE_CONNECT_READY_FILE=/tmp/sauce-connect-ready
before_script:
- export SAUCE_ACCESS_KEY=`echo $SAUCE_ACCESS_KEY | rev`
- ./lib/sauce/sauce_connect_setup.sh
- npm install -g grunt-cli
- grunt ci-checks package
- ./lib/sauce/sauce_connect_block.sh
script:
- grunt parallel:travis --reporters dots --browsers SL_Chrome
+2092 -11
View File
File diff suppressed because it is too large Load Diff
+32
View File
@@ -0,0 +1,32 @@
## Submitting issues
If you have questions about how to use AngularJS, please direct these to the
[Google Group][groups] discussion list or [StackOverflow][stackoverflow]. We are
also available on [IRC][irc].
### Guidelines
* Search the archive first, it's likely that your question was already answered.
* A live example demonstrating your problem or question, will get an answer faster.
* Create one using this [template][template]
* If you get help, help others. Good karma rulez!
If your issue appears to be a bug, and hasn't been reported, open a new issue.
Help us to maximize the effort we can spend fixing issues and adding new
features, by not reporting duplicate issues.
[stackoverflow]: http://stackoverflow.com/questions/tagged/angularjs
[groups]: https://groups.google.com/forum/?fromgroups#!forum/angular
[irc]: http://webchat.freenode.net/?channels=angularjs&uio=d4
[template]: http://plnkr.co/edit/gist:3510140
## Contributing to Source Code
We'd love for you to contribute to our source code and to make AngularJS even
better than it is today!
Please read the [contribution guidelines][contribute] to learn about how to submit code as well as
other useful info like how to build and test AngularJS code.
[list]: https://groups.google.com/forum/?fromgroups#!forum/angular
[contribute]: http://docs.angularjs.org/misc/contribute
+228
View File
@@ -0,0 +1,228 @@
var files = require('./angularFiles').files;
var util = require('./lib/grunt/utils.js');
module.exports = function(grunt) {
//grunt plugins
grunt.loadNpmTasks('grunt-contrib-clean');
grunt.loadNpmTasks('grunt-contrib-copy');
grunt.loadNpmTasks('grunt-contrib-connect');
grunt.loadNpmTasks('grunt-contrib-compress');
grunt.loadNpmTasks('grunt-ddescribe-iit');
grunt.loadNpmTasks('grunt-merge-conflict');
grunt.loadNpmTasks('grunt-parallel');
grunt.loadTasks('lib/grunt');
var NG_VERSION = util.getVersion();
var dist = 'angular-'+ NG_VERSION.full;
//global beforeEach
util.init();
//config
grunt.initConfig({
NG_VERSION: NG_VERSION,
parallel: {
travis: {
options: {
stream: true,
},
tasks: [
util.parallelTask('test:modules'),
util.parallelTask('test:jquery'),
util.parallelTask('test:jqlite'),
util.parallelTask('test:e2e')
]
}
},
connect: {
devserver: {
options: {
port: 8000,
hostname: '0.0.0.0',
base: '.',
keepalive: true,
middleware: function(connect, options){
return [
//uncomment to enable CSP
// util.csp(),
util.rewrite(),
connect.favicon('images/favicon.ico'),
connect.static(options.base),
connect.directory(options.base)
];
}
}
},
testserver: {
options: {
// We use end2end task (which does not start the webserver)
// and start the webserver as a separate process (in travis_build.sh)
// to avoid https://github.com/joyent/libuv/issues/826
port: 8000,
hostname: '0.0.0.0',
middleware: function(connect, options){
return [
function(req, resp, next) {
// cache get requests to speed up tests on travis
if (req.method === 'GET') {
resp.setHeader('Cache-control', 'public, max-age=3600');
}
next();
},
connect.favicon('images/favicon.ico'),
connect.static(options.base)
];
}
}
}
},
test: {
jqlite: 'karma-jqlite.conf.js',
jquery: 'karma-jquery.conf.js',
modules: 'karma-modules.conf.js',
//NOTE run grunt test:e2e instead and it will start a webserver for you
end2end: 'karma-e2e.conf.js'
},
autotest: {
jqlite: 'karma-jqlite.conf.js',
jquery: 'karma-jquery.conf.js'
},
clean: {build: ['build']},
build: {
scenario: {
dest: 'build/angular-scenario.js',
src: [
'lib/jquery/jquery.js',
util.wrap([files['angularSrc'], files['angularScenario']], 'ngScenario/angular')
],
styles: {
css: ['css/angular.css', 'css/angular-scenario.css']
}
},
angular: {
dest: 'build/angular.js',
src: util.wrap([files['angularSrc']], 'angular'),
styles: {
css: ['css/angular.css'],
minify: true
}
},
loader: {
dest: 'build/angular-loader.js',
src: util.wrap(['src/loader.js'], 'loader')
},
mocks: {
dest: 'build/angular-mocks.js',
src: ['src/ngMock/angular-mocks.js'],
strict: false
},
sanitize: {
dest: 'build/angular-sanitize.js',
src: util.wrap([
'src/ngSanitize/sanitize.js',
'src/ngSanitize/directive/ngBindHtml.js',
'src/ngSanitize/filter/linky.js',
], 'module')
},
resource: {
dest: 'build/angular-resource.js',
src: util.wrap(['src/ngResource/resource.js'], 'module')
},
cookies: {
dest: 'build/angular-cookies.js',
src: util.wrap(['src/ngCookies/cookies.js'], 'module')
},
bootstrap: {
dest: 'build/angular-bootstrap.js',
src: util.wrap(['src/bootstrap/bootstrap.js'], 'module')
},
bootstrapPrettify: {
dest: 'build/angular-bootstrap-prettify.js',
src: util.wrap(['src/bootstrap/bootstrap-prettify.js', 'src/bootstrap/google-prettify/prettify.js'], 'module'),
styles: {
css: ['src/bootstrap/google-prettify/prettify.css'],
minify: true
}
}
},
min: {
angular: 'build/angular.js',
cookies: 'build/angular-cookies.js',
loader: 'build/angular-loader.js',
resource: 'build/angular-resource.js',
sanitize: 'build/angular-sanitize.js',
bootstrap: 'build/angular-bootstrap.js',
bootstrapPrettify: 'build/angular-bootstrap-prettify.js',
},
docs: {
process: ['build/docs/*.html', 'build/docs/.htaccess']
},
"ddescribe-iit": {
files: [
'test/**/*.js',
'!test/ngScenario/DescribeSpec.js'
]
},
"merge-conflict": {
files: [
'src/**/*',
'test/**/*',
'docs/**/*',
'css/**/*'
]
},
copy: {
i18n: {
files: [
{ src: 'src/ngLocale/**', dest: 'build/i18n/', expand: true, flatten: true }
]
}
},
compress: {
build: {
options: {archive: 'build/' + dist +'.zip', mode: 'zip'},
src: ['**'], cwd: 'build', expand: true, dot: true, dest: dist + '/'
}
},
write: {
versionTXT: {file: 'build/version.txt', val: NG_VERSION.full},
versionJSON: {file: 'build/version.json', val: JSON.stringify(NG_VERSION)}
}
});
//alias tasks
grunt.registerTask('test:unit', ['test:jqlite', 'test:jquery', 'test:modules']);
grunt.registerTask('minify', ['clean', 'build', 'minall']);
grunt.registerTask('test:e2e', ['connect:testserver', 'test:end2end']);
grunt.registerTask('webserver', ['connect:devserver']);
grunt.registerTask('package', ['clean', 'buildall', 'minall', 'docs', 'copy', 'write', 'compress']);
grunt.registerTask('ci-checks', ['ddescribe-iit', 'merge-conflict']);
grunt.registerTask('default', ['package']);
};
+1 -1
View File
@@ -1,6 +1,6 @@
The MIT License
Copyright (c) 2010 Adam Abrons and Misko Hevery http://getangular.com
Copyright (c) 2010-2012 Google, Inc. http://angularjs.org
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
+30 -9
View File
@@ -1,19 +1,40 @@
AngularJS
=========
* Web site: http://angularjs.org
* Tutorial: http://docs.angularjs.org/#!/tutorial
* API Docs: http://docs.angularjs.org
* Developer Guide: http://docs.angularjs.org/#!/guide
AngularJS lets you write client-side web applications as if you had a smarter browser. It lets you
use good old HTML (or HAML, Jade and friends!) as your template language and lets you extend HTMLs
syntax to express your applications components clearly and succinctly. It automatically
synchronizes data from your UI (view) with your JavaScript objects (model) through 2-way data
binding. To help you structure your application better and make it easy to test, AngularJS teaches
the browser how to do dependency injection and inversion of control. Oh yeah and it also helps with
server-side communication, taming async callbacks with promises and deferreds; and make client-side
navigation and deeplinking with hashbang urls or HTML5 pushState a piece of cake. The best of all:
it makes development fun!
Compiling
* Web site: http://angularjs.org
* Tutorial: http://docs.angularjs.org/tutorial
* API Docs: http://docs.angularjs.org/api
* Developer Guide: http://docs.angularjs.org/guide
* Contribution guidelines: http://docs.angularjs.org/misc/contribute
* Dashboard: http://dashboard.angularjs.org
Building AngularJS
---------
rake compile
[Once you have your environment setup](http://docs.angularjs.org/misc/contribute) just run:
grunt package
Running Tests
-------------
./server.sh # start the server
open http://localhost:9876/capture # capture browser
./test.sh # run all unit tests
To execute all unit tests, use:
grunt test:unit
To execute end-to-end (e2e) tests, use:
grunt package
grunt test:e2e
To learn more about the grunt tasks, run `grunt --help` and also read our
[contribution guidelines](http://docs.angularjs.org/misc/contribute).
-338
View File
@@ -1,338 +0,0 @@
require 'yaml'
include FileUtils
content = File.open('angularFiles.js', 'r') {|f| f.read }
files = eval(content.gsub(/\};(\s|\S)*/, '}').gsub(/angularFiles = /, '').gsub(/:/, '=>'));
BUILD_DIR = 'build'
task :default => [:compile, :test]
desc 'Init the build workspace'
task :init do
FileUtils.mkdir(BUILD_DIR) unless File.directory?(BUILD_DIR)
v = YAML::load( File.open( 'version.yaml' ) )
match = v['version'].match(/^([^-]*)(-snapshot)?$/)
NG_VERSION = Struct.new(:full, :major, :minor, :dot, :codename).
new(match[1] + (match[2] ? ('-' + %x(git rev-parse HEAD)[0..7]) : ''),
match[1].split('.')[0],
match[1].split('.')[1],
match[1].split('.')[2].sub(/\D+.*$/, ''),
v['codename'])
end
desc 'Clean Generated Files'
task :clean do
FileUtils.rm_r(BUILD_DIR, :force => true)
FileUtils.mkdir(BUILD_DIR)
end
desc 'Compile Scenario'
task :compile_scenario => :init do
deps = [
'lib/jquery/jquery.js',
'src/scenario/angular.prefix',
files['angularSrc'],
files['angularScenario'],
'src/scenario/angular.suffix',
]
concat = 'cat ' + deps.flatten.join(' ')
File.open(path_to('angular-scenario.js'), 'w') do |f|
f.write(%x{#{concat}}.gsub('"NG_VERSION_FULL"', NG_VERSION.full))
f.write(gen_css('css/angular.css') + "\n")
f.write(gen_css('css/angular-scenario.css'))
end
end
desc 'Compile JSTD Scenario Adapter'
task :compile_jstd_scenario_adapter => :init do
deps = [
'src/jstd-scenario-adapter/angular.prefix',
'src/jstd-scenario-adapter/Adapter.js',
'src/jstd-scenario-adapter/angular.suffix',
]
concat = 'cat ' + deps.flatten.join(' ')
File.open(path_to('jstd-scenario-adapter.js'), 'w') do |f|
f.write(%x{#{concat}}.gsub('"NG_VERSION_FULL"', NG_VERSION.full))
end
# TODO(vojta) use jstd configuration when implemented
# (instead of including jstd-adapter-config.js)
File.open(path_to('jstd-scenario-adapter-config.js'), 'w') do |f|
f.write("/**\r\n" +
" * Configuration for jstd scenario adapter \n */\n" +
"var jstdScenarioAdapter = {\n relativeUrlPrefix: '/build/docs/'\n};\n")
end
end
desc 'Compile JavaScript'
task :compile => [:init, :compile_scenario, :compile_jstd_scenario_adapter] do
deps = [
'src/angular.prefix',
files['angularSrc'],
'src/angular.suffix',
]
File.open(path_to('angular.js'), 'w') do |f|
concat = 'cat ' + deps.flatten.join(' ')
content = %x{#{concat}}.
gsub('"NG_VERSION_FULL"', NG_VERSION.full).
gsub('"NG_VERSION_MAJOR"', NG_VERSION.major).
gsub('"NG_VERSION_MINOR"', NG_VERSION.minor).
gsub('"NG_VERSION_DOT"', NG_VERSION.dot).
gsub('"NG_VERSION_CODENAME"', NG_VERSION.codename).
gsub(/^\s*['"]use strict['"];?\s*$/, ''). # remove all file-specific strict mode flags
gsub(/'USE STRICT'/, "'use strict'") # rename the placeholder in angular.prefix
f.write(content)
f.write(gen_css('css/angular.css', true))
end
%x(java -jar lib/closure-compiler/compiler.jar \
--compilation_level SIMPLE_OPTIMIZATIONS \
--language_in ECMASCRIPT5_STRICT \
--js #{path_to('angular.js')} \
--js_output_file #{path_to('angular.min.js')})
FileUtils.cp_r 'i18n/locale', path_to('i18n')
File.open(path_to('angular-loader.js'), 'w') do |f|
concat = 'cat ' + [
'src/loader.prefix',
'src/loader.js',
'src/loader.suffix'].flatten.join(' ')
content = %x{#{concat}}.
gsub('"NG_VERSION_FULL"', NG_VERSION.full).
gsub(/^\s*['"]use strict['"];?\s*$/, '') # remove all file-specific strict mode flags
f.write(content)
end
%x(java -jar lib/closure-compiler/compiler.jar \
--compilation_level SIMPLE_OPTIMIZATIONS \
--language_in ECMASCRIPT5_STRICT \
--js #{path_to('angular-loader.js')} \
--js_output_file #{path_to('angular-loader.min.js')})
end
desc 'Generate docs'
task :docs => [:init] do
`node docs/src/gen-docs.js`
File.open(path_to('docs/.htaccess'), File::RDWR) do |f|
text = f.read
f.truncate 0
f.rewind
f.write text.sub('"NG_VERSION_FULL"', NG_VERSION.full)
end
end
desc 'Create angular distribution'
task :package => [:clean, :compile, :docs] do
tarball = "angular-#{NG_VERSION.full}.tgz"
pkg_dir = path_to("pkg/angular-#{NG_VERSION.full}")
FileUtils.rm_r(path_to('pkg'), :force => true)
FileUtils.mkdir_p(pkg_dir)
['src/angular-mocks.js',
path_to('angular.js'),
path_to('angular-loader.js'),
path_to('angular.min.js'),
path_to('angular-loader.min.js'),
path_to('angular-scenario.js'),
path_to('jstd-scenario-adapter.js'),
path_to('jstd-scenario-adapter-config.js'),
].each do |src|
dest = src.gsub(/^[^\/]+\//, '').gsub(/((\.min)?\.js)$/, "-#{NG_VERSION.full}\\1")
FileUtils.cp(src, pkg_dir + '/' + dest)
end
FileUtils.cp_r path_to('i18n'), "#{pkg_dir}/i18n-#{NG_VERSION.full}"
FileUtils.cp_r path_to('docs'), "#{pkg_dir}/docs-#{NG_VERSION.full}"
File.open("#{pkg_dir}/angular-mocks-#{NG_VERSION.full}.js", File::RDWR) do |f|
text = f.read
f.truncate 0
f.rewind
f.write text.sub('"NG_VERSION_FULL"', NG_VERSION.full)
end
File.open("#{pkg_dir}/docs-#{NG_VERSION.full}/index.html", File::RDWR) do |f|
text = f.read
f.truncate 0
f.rewind
f.write text.sub('angular.min.js', "angular-#{NG_VERSION.full}.min.js").
sub('/build/docs/', "/#{NG_VERSION.full}/docs-#{NG_VERSION.full}/")
end
File.open("#{pkg_dir}/docs-#{NG_VERSION.full}/index-jq.html", File::RDWR) do |f|
text = f.read
f.truncate 0
f.rewind
f.write text.sub('angular.min.js', "angular-#{NG_VERSION.full}.min.js").
sub('/build/docs/', "/#{NG_VERSION.full}/docs-#{NG_VERSION.full}/")
end
File.open("#{pkg_dir}/docs-#{NG_VERSION.full}/index-nocache.html", File::RDWR) do |f|
text = f.read
f.truncate 0
f.rewind
f.write text.sub('angular.min.js', "angular-#{NG_VERSION.full}.min.js").
sub('/build/docs/', "/#{NG_VERSION.full}/docs-#{NG_VERSION.full}/")
end
File.open("#{pkg_dir}/docs-#{NG_VERSION.full}/index-jq-nocache.html", File::RDWR) do |f|
text = f.read
f.truncate 0
f.rewind
f.write text.sub('angular.min.js', "angular-#{NG_VERSION.full}.min.js").
sub('/build/docs/', "/#{NG_VERSION.full}/docs-#{NG_VERSION.full}/")
end
File.open("#{pkg_dir}/docs-#{NG_VERSION.full}/index-debug.html", File::RDWR) do |f|
text = f.read
f.truncate 0
f.rewind
f.write text.sub('../angular.js', "../angular-#{NG_VERSION.full}.js").
sub('/build/docs/', "/#{NG_VERSION.full}/docs-#{NG_VERSION.full}/")
end
File.open("#{pkg_dir}/docs-#{NG_VERSION.full}/index-jq-debug.html", File::RDWR) do |f|
text = f.read
f.truncate 0
f.rewind
f.write text.sub('../angular.js', "../angular-#{NG_VERSION.full}.js").
sub('/build/docs/', "/#{NG_VERSION.full}/docs-#{NG_VERSION.full}/")
end
File.open("#{pkg_dir}/docs-#{NG_VERSION.full}/docs-scenario.html", File::RDWR) do |f|
text = f.read
f.truncate 0
f.rewind
f.write text.sub('angular-scenario.js', "angular-scenario-#{NG_VERSION.full}.js")
end
File.open("#{pkg_dir}/docs-#{NG_VERSION.full}/appcache.manifest", File::RDWR) do |f|
text = f.read
f.truncate 0
f.rewind
f.write text.sub('angular.min.js', "angular-#{NG_VERSION.full}.min.js").
sub('/build/docs/', "/#{NG_VERSION.full}/docs-#{NG_VERSION.full}/")
end
File.open("#{pkg_dir}/docs-#{NG_VERSION.full}/appcache-offline.manifest", File::RDWR) do |f|
text = f.read
f.truncate 0
f.rewind
f.write text.sub('angular.min.js', "angular-#{NG_VERSION.full}.min.js").
sub('/build/docs/', "/#{NG_VERSION.full}/docs-#{NG_VERSION.full}/")
end
%x(tar -czf #{path_to(tarball)} -C #{path_to('pkg')} .)
FileUtils.cp path_to(tarball), pkg_dir
FileUtils.mv pkg_dir, path_to(['pkg', NG_VERSION.full])
puts "Package created: #{path_to(tarball)}"
end
namespace :server do
desc 'Run JsTestDriver Server'
task :start do
sh %x(java -jar lib/jstestdriver/JsTestDriver.jar --browser open --port 9876)
end
desc 'Run JavaScript tests against the server'
task :test do
sh %(java -jar lib/jstestdriver/JsTestDriver.jar --tests all)
end
end
desc 'Run JavaScript tests'
task :test do
sh %(java -jar lib/jstestdriver/JsTestDriver.jar --tests all --browser open --port 9876)
end
desc 'Lint'
task :lint do
out = %x(lib/jsl/jsl -conf lib/jsl/jsl.default.conf)
print out
end
desc 'push_angularjs'
task :push_angularjs => :compile do
sh %(cat angularjs.ftp | ftp -N angularjs.netrc angularjs.org)
end
###################
# utility methods #
###################
##
# generates css snippet from a given files and optionally applies simple minification rules
#
def gen_css(cssFile, minify = false)
css = ''
File.open(cssFile, 'r') do |f|
css = f.read
end
if minify
css.gsub! /\n/, ''
css.gsub! /\/\*.*?\*\//, ''
css.gsub! /:\s+/, ':'
css.gsub! /\s*\{\s*/, '{'
css.gsub! /\s*\}\s*/, '}'
css.gsub! /\s*\,\s*/, ','
css.gsub! /\s*\;\s*/, ';'
end
#escape for js
css.gsub! /\\/, "\\\\\\"
css.gsub! /'/, "\\\\'"
css.gsub! /\n/, "\\n"
return %Q{angular.element(document).find('head').append('<style type="text/css">#{css}</style>');}
end
##
# returns path to the file in the build directory
#
def path_to(filename)
return File.join(BUILD_DIR, *filename)
end
+144 -145
View File
@@ -3,189 +3,188 @@ angularFiles = {
'src/Angular.js',
'src/loader.js',
'src/AngularPublic.js',
'src/JSON.js',
'src/Injector.js',
'src/Resource.js',
'src/jqLite.js',
'src/apis.js',
'src/service/anchorScroll.js',
'src/service/browser.js',
'src/service/cacheFactory.js',
'src/service/compiler.js',
'src/service/controller.js',
'src/service/cookieStore.js',
'src/service/cookies.js',
'src/service/defer.js',
'src/service/document.js',
'src/service/exceptionHandler.js',
'src/service/filter.js',
'src/service/filter/filter.js',
'src/service/filter/filters.js',
'src/service/filter/limitTo.js',
'src/service/filter/orderBy.js',
'src/service/interpolate.js',
'src/service/location.js',
'src/service/log.js',
'src/service/resource.js',
'src/service/parse.js',
'src/service/q.js',
'src/service/route.js',
'src/service/routeParams.js',
'src/service/scope.js',
'src/service/sanitize.js',
'src/service/sniffer.js',
'src/service/window.js',
'src/service/http.js',
'src/service/httpBackend.js',
'src/service/locale.js',
'src/directive/directives.js',
'src/directive/a.js',
'src/directive/booleanAttrDirs.js',
'src/directive/form.js',
'src/directive/input.js',
'src/directive/ngBind.js',
'src/directive/ngClass.js',
'src/directive/ngCloak.js',
'src/directive/ngController.js',
'src/directive/ngEventDirs.js',
'src/directive/ngInclude.js',
'src/directive/ngInit.js',
'src/directive/ngNonBindable.js',
'src/directive/ngPluralize.js',
'src/directive/ngRepeat.js',
'src/directive/ngShowHide.js',
'src/directive/ngStyle.js',
'src/directive/ngSwitch.js',
'src/directive/ngTransclude.js',
'src/directive/ngView.js',
'src/directive/script.js',
'src/directive/select.js',
'src/directive/style.js'
'src/auto/injector.js',
'src/ng/anchorScroll.js',
'src/ng/browser.js',
'src/ng/cacheFactory.js',
'src/ng/compile.js',
'src/ng/controller.js',
'src/ng/document.js',
'src/ng/exceptionHandler.js',
'src/ng/interpolate.js',
'src/ng/location.js',
'src/ng/log.js',
'src/ng/parse.js',
'src/ng/q.js',
'src/ng/route.js',
'src/ng/routeParams.js',
'src/ng/rootScope.js',
'src/ng/sniffer.js',
'src/ng/window.js',
'src/ng/http.js',
'src/ng/httpBackend.js',
'src/ng/locale.js',
'src/ng/timeout.js',
'src/ng/filter.js',
'src/ng/filter/filter.js',
'src/ng/filter/filters.js',
'src/ng/filter/limitTo.js',
'src/ng/filter/orderBy.js',
'src/ng/directive/directives.js',
'src/ng/directive/a.js',
'src/ng/directive/booleanAttrs.js',
'src/ng/directive/form.js',
'src/ng/directive/input.js',
'src/ng/directive/ngBind.js',
'src/ng/directive/ngClass.js',
'src/ng/directive/ngCloak.js',
'src/ng/directive/ngController.js',
'src/ng/directive/ngCsp.js',
'src/ng/directive/ngEventDirs.js',
'src/ng/directive/ngInclude.js',
'src/ng/directive/ngInit.js',
'src/ng/directive/ngNonBindable.js',
'src/ng/directive/ngPluralize.js',
'src/ng/directive/ngRepeat.js',
'src/ng/directive/ngShowHide.js',
'src/ng/directive/ngStyle.js',
'src/ng/directive/ngSwitch.js',
'src/ng/directive/ngTransclude.js',
'src/ng/directive/ngView.js',
'src/ng/directive/script.js',
'src/ng/directive/select.js',
'src/ng/directive/style.js'
],
'angularSrcModules': [
'src/ngCookies/cookies.js',
'src/ngResource/resource.js',
'src/ngSanitize/sanitize.js',
'src/ngSanitize/directive/ngBindHtml.js',
'src/ngSanitize/filter/linky.js',
'src/ngMock/angular-mocks.js',
'src/bootstrap/bootstrap.js'
],
'angularScenario': [
'src/scenario/Scenario.js',
'src/scenario/Application.js',
'src/scenario/Describe.js',
'src/scenario/Future.js',
'src/scenario/ObjectModel.js',
'src/scenario/Describe.js',
'src/scenario/Runner.js',
'src/scenario/SpecRunner.js',
'src/scenario/dsl.js',
'src/scenario/matchers.js',
'src/scenario/output/Html.js',
'src/scenario/output/Json.js',
'src/scenario/output/Xml.js',
'src/scenario/output/Object.js'
'src/ngScenario/Scenario.js',
'src/ngScenario/Application.js',
'src/ngScenario/Describe.js',
'src/ngScenario/Future.js',
'src/ngScenario/ObjectModel.js',
'src/ngScenario/Runner.js',
'src/ngScenario/SpecRunner.js',
'src/ngScenario/dsl.js',
'src/ngScenario/matchers.js',
'src/ngScenario/output/Html.js',
'src/ngScenario/output/Json.js',
'src/ngScenario/output/Xml.js',
'src/ngScenario/output/Object.js'
],
'jstd': [
'lib/jasmine/jasmine.js',
'lib/jasmine-jstd-adapter/JasmineAdapter.js',
'angularTest': [
'test/testabilityPatch.js',
'test/matchers.js',
'test/ngScenario/*.js',
'test/ngScenario/output/*.js',
'test/*.js',
'test/auto/*.js',
'test/bootstrap/*.js',
'test/ng/*.js',
'test/ng/directive/*.js',
'test/ng/filter/*.js',
'test/ngCookies/*.js',
'test/ngResource/*.js',
'test/ngSanitize/*.js',
'test/ngSanitize/directive/*.js',
'test/ngSanitize/filter/*.js',
'test/ngMock/*.js'
],
'karma': [
'lib/jquery/jquery.js',
'test/jquery_remove.js',
'@angularSrc',
'src/publishExternalApis.js',
'@angularSrcModules',
'@angularScenario',
'@angularTest',
'example/personalLog/*.js',
'test/testabilityPatch.js',
'test/matchers.js',
'src/scenario/Scenario.js',
'src/scenario/output/*.js',
'src/jstd-scenario-adapter/*.js',
'src/scenario/*.js',
'src/angular-mocks.js',
'test/scenario/*.js',
'test/scenario/output/*.js',
'test/jstd-scenario-adapter/*.js',
'test/*.js',
'test/service/*.js',
'test/service/filter/*.js',
'test/directive/*.js',
'example/personalLog/test/*.js'
],
'jstdExclude': [
'karmaExclude': [
'test/jquery_alias.js',
'src/angular-bootstrap.js',
'src/scenario/angular-bootstrap.js'
'src/ngScenario/angular-bootstrap.js'
],
'jstdScenario': [
'karmaScenario': [
'build/angular-scenario.js',
'build/jstd-scenario-adapter-config.js',
'build/jstd-scenario-adapter.js',
'build/docs/docs-scenario.js'
],
'jstdMocks': [
'lib/jasmine/jasmine.js',
'lib/jasmine-jstd-adapter/JasmineAdapter.js',
"karmaModules": [
'build/angular.js',
'src/angular-mocks.js',
'src/ngMock/angular-mocks.js',
'src/ngCookies/cookies.js',
'src/ngResource/resource.js',
'src/ngSanitize/sanitize.js',
'src/ngSanitize/directive/ngBindHtml.js',
'src/ngSanitize/filter/linky.js',
'test/matchers.js',
'test/angular-mocksSpec.js'
'test/ngMock/*.js',
'test/ngCookies/*.js',
'test/ngResource/*.js',
'test/ngSanitize/*.js',
'test/ngSanitize/directive/*.js',
'test/ngSanitize/filter/*.js'
],
'jstdPerf': [
'lib/jasmine/jasmine.js',
'lib/jasmine-jstd-adapter/JasmineAdapter.js',
'angularSrc',
'src/angular-mocks.js',
'perf/data/*.js',
'perf/testUtils.js',
'perf/*.js'
],
'jstdPerfExclude': [
'src/angular-bootstrap.js',
'src/scenario/angular-bootstrap.js'
],
'jstdJquery': [
'lib/jasmine/jasmine.js',
'lib/jasmine-jstd-adapter/JasmineAdapter.js',
'karmaJquery': [
'lib/jquery/jquery.js',
'test/jquery_alias.js',
'@angularSrc',
'src/publishExternalApis.js',
'@angularSrcModules',
'@angularScenario',
'@angularTest',
'example/personalLog/*.js',
'test/testabilityPatch.js',
'test/matchers.js',
'src/scenario/Scenario.js',
'src/scenario/output/*.js',
'src/jstd-scenario-adapter/*.js',
'src/scenario/*.js',
'src/angular-mocks.js',
'test/scenario/*.js',
'test/scenario/output/*.js',
'test/jstd-scenario-adapter/*.js',
'test/*.js',
'test/service/*.js',
'test/directive/*.js',
'example/personalLog/test/*.js'
],
'jstdJqueryExclude': [
'karmaJqueryExclude': [
'src/angular-bootstrap.js',
'src/scenario/angular-bootstrap.js',
'src/ngScenario/angular-bootstrap.js',
'test/jquery_remove.js'
]
};
// Execute only in slim-jim
if (typeof JASMINE_ADAPTER !== 'undefined') {
// SlimJim config
files = [JASMINE, JASMINE_ADAPTER];
angularFiles.jstd.forEach(function(pattern) {
// replace angular source
if (pattern === '@angularSrc') files = files.concat(angularFiles.angularSrc);
// ignore jstd and jasmine files
else if (!/jstd|jasmine/.test(pattern)) files.push(pattern);
});
if (exports) {
exports.files = angularFiles;
exports.mergeFilesFor = function() {
var files = [];
exclude = angularFiles.jstdExclude;
Array.prototype.slice.call(arguments, 0).forEach(function(filegroup) {
angularFiles[filegroup].forEach(function(file) {
// replace @ref
var match = file.match(/^\@(.*)/);
if (match) {
files = files.concat(angularFiles[match[1]]);
} else {
files.push(file);
}
});
});
autoWatch = true;
autoWatchInterval = 1;
logLevel = LOG_INFO;
logColors = true;
return files;
};
}
-5
View File
@@ -1,5 +0,0 @@
bin
cd angularjs.org/ng
put angular-debug.js js/angular-debug.js
put angular-minified.js js/angular-minified.js
put angular-scenario.js js/angular-scenario.js
Executable
+210
View File
@@ -0,0 +1,210 @@
#!/usr/bin/env node
// TODO(vojta): pre-commit hook for validating messages
// TODO(vojta): report errors, currently Q silence everything which really sucks
var child = require('child_process');
var fs = require('fs');
var util = require('util');
var q = require('qq');
var GIT_LOG_CMD = 'git log --grep="%s" -E --format=%s %s..HEAD';
var GIT_TAG_CMD = 'git describe --tags --abbrev=0';
var HEADER_TPL = '<a name="%s"></a>\n# %s (%s)\n\n';
var LINK_ISSUE = '[#%s](https://github.com/angular/angular.js/issues/%s)';
var LINK_COMMIT = '[%s](https://github.com/angular/angular.js/commit/%s)';
var EMPTY_COMPONENT = '$$';
var MAX_SUBJECT_LENGTH = 80;
var warn = function() {
console.log('WARNING:', util.format.apply(null, arguments));
};
var parseRawCommit = function(raw) {
if (!raw) return null;
var lines = raw.split('\n');
var msg = {}, match;
msg.hash = lines.shift();
msg.subject = lines.shift();
msg.closes = [];
msg.breaks = [];
lines.forEach(function(line) {
match = line.match(/(?:Closes|Fixes)\s#(\d+)/);
if (match) msg.closes.push(parseInt(match[1]));
});
match = raw.match(/BREAKING CHANGE:([\s\S]*)/);
if (match) {
msg.breaking = match[1];
}
msg.body = lines.join('\n');
match = msg.subject.match(/^(.*)\((.*)\)\:\s(.*)$/);
if (!match || !match[1] || !match[3]) {
warn('Incorrect message: %s %s', msg.hash, msg.subject);
return null;
}
if (match[3].length > MAX_SUBJECT_LENGTH) {
warn('Too long subject: %s %s', msg.hash, msg.subject);
match[3] = match[3].substr(0, MAX_SUBJECT_LENGTH);
}
msg.type = match[1];
msg.component = match[2];
msg.subject = match[3];
return msg;
};
var linkToIssue = function(issue) {
return util.format(LINK_ISSUE, issue, issue);
};
var linkToCommit = function(hash) {
return util.format(LINK_COMMIT, hash.substr(0, 8), hash);
};
var currentDate = function() {
var now = new Date();
var pad = function(i) {
return ('0' + i).substr(-2);
};
return util.format('%d-%s-%s', now.getFullYear(), pad(now.getMonth() + 1), pad(now.getDate()));
};
var printSection = function(stream, title, section, printCommitLinks) {
printCommitLinks = printCommitLinks === undefined ? true : printCommitLinks;
var components = Object.getOwnPropertyNames(section).sort();
if (!components.length) return;
stream.write(util.format('\n## %s\n\n', title));
components.forEach(function(name) {
var prefix = '-';
var nested = section[name].length > 1;
if (name !== EMPTY_COMPONENT) {
if (nested) {
stream.write(util.format('- **%s:**\n', name));
prefix = ' -';
} else {
prefix = util.format('- **%s:**', name);
}
}
section[name].forEach(function(commit) {
if (printCommitLinks) {
stream.write(util.format('%s %s\n (%s', prefix, commit.subject, linkToCommit(commit.hash)));
if (commit.closes.length) {
stream.write(',\n ' + commit.closes.map(linkToIssue).join(', '));
}
stream.write(')\n');
} else {
stream.write(util.format('%s %s', prefix, commit.subject));
}
});
});
stream.write('\n');
};
var readGitLog = function(grep, from) {
var deferred = q.defer();
// TODO(vojta): if it's slow, use spawn and stream it instead
child.exec(util.format(GIT_LOG_CMD, grep, '%H%n%s%n%b%n==END==', from), function(code, stdout, stderr) {
var commits = [];
stdout.split('\n==END==\n').forEach(function(rawCommit) {
var commit = parseRawCommit(rawCommit);
if (commit) commits.push(commit);
});
deferred.resolve(commits);
});
return deferred.promise;
};
var writeChangelog = function(stream, commits, version) {
var sections = {
fix: {},
feat: {},
breaks: {}
};
sections.breaks[EMPTY_COMPONENT] = [];
commits.forEach(function(commit) {
var section = sections[commit.type];
var component = commit.component || EMPTY_COMPONENT;
if (section) {
section[component] = section[component] || [];
section[component].push(commit);
}
if (commit.breaking) {
sections.breaks[component] = sections.breaks[component] || [];
sections.breaks[component].push({
subject: util.format("due to %s,\n %s", linkToCommit(commit.hash), commit.breaking),
hash: commit.hash,
closes: []
});
};
});
stream.write(util.format(HEADER_TPL, version, version, currentDate()));
printSection(stream, 'Bug Fixes', sections.fix);
printSection(stream, 'Features', sections.feat);
printSection(stream, 'Breaking Changes', sections.breaks, false);
}
var getPreviousTag = function() {
var deferred = q.defer();
child.exec(GIT_TAG_CMD, function(code, stdout, stderr) {
if (code) deferred.reject('Cannot get the previous tag.');
else deferred.resolve(stdout.replace('\n', ''));
});
return deferred.promise;
};
var generate = function(version, file) {
getPreviousTag().then(function(tag) {
console.log('Reading git log since', tag);
readGitLog('^fix|^feat|BREAKING', tag).then(function(commits) {
console.log('Parsed', commits.length, 'commits');
console.log('Generating changelog to', file || 'stdout', '(', version, ')');
writeChangelog(file ? fs.createWriteStream(file) : process.stdout, commits, version);
});
});
};
// publish for testing
exports.parseRawCommit = parseRawCommit;
// hacky start if not run by jasmine :-D
if (process.argv.join('').indexOf('jasmine-node') === -1) {
generate(process.argv[2], process.argv[3]);
}
+43
View File
@@ -0,0 +1,43 @@
describe('changelog.js', function() {
var ch = require('./changelog');
describe('parseRawCommit', function() {
it('should parse raw commit', function() {
var msg = ch.parseRawCommit(
'9b1aff905b638aa274a5fc8f88662df446d374bd\n' +
'feat(scope): broadcast $destroy event on scope destruction\n' +
'perf testing shows that in chrome this change adds 5-15% overhead\n' +
'when destroying 10k nested scopes where each scope has a $destroy listener\n');
expect(msg.type).toBe('feat');
expect(msg.hash).toBe('9b1aff905b638aa274a5fc8f88662df446d374bd');
expect(msg.subject).toBe('broadcast $destroy event on scope destruction');
expect(msg.body).toBe('perf testing shows that in chrome this change adds 5-15% overhead\n' +
'when destroying 10k nested scopes where each scope has a $destroy listener\n')
expect(msg.component).toBe('scope');
});
it('should parse closed issues', function() {
var msg = ch.parseRawCommit(
'13f31602f396bc269076ab4d389cfd8ca94b20ba\n' +
'feat(ng-list): Allow custom separator\n' +
'bla bla bla\n\n' +
'Closes #123\nCloses #25\n');
expect(msg.closes).toEqual([123, 25]);
});
it('should parse breaking changes', function() {
var msg = ch.parseRawCommit(
'13f31602f396bc269076ab4d389cfd8ca94b20ba\n' +
'feat(ng-list): Allow custom separator\n' +
'bla bla bla\n\n' +
'BREAKING CHANGE: first breaking change\nsomething else\n' +
'another line with more info\n');
expect(msg.breaking).toEqual(' first breaking change\nsomething else\nanother line with more info\n');
});
});
});
+80
View File
@@ -0,0 +1,80 @@
<a name="v1.0.0rc3"></a>
# v1.0.0rc3 (2012-03-27)
## Bug Fixes
- **$compile:**
- create new (isolate) scopes for directives on root elements ([5390fb37](https://github.com/angular/angular.js/commit/5390fb37d2c01937922613fc57df4986af521787), closes [#817](https://github.com/angular/angular.js/issues/817))
- don't touch static element attributes ([9cb2195e](https://github.com/angular/angular.js/commit/9cb2195e61a78e99020ec19d687a221ca88b5900))
- Merge interpolated css class when replacing an element ([f49eaf8b](https://github.com/angular/angular.js/commit/f49eaf8bf2df5f4e0e82d6c89e849a4f82c8d414))
- **$http:**
- don't send Content-Type header when no data ([1a5bebd9](https://github.com/angular/angular.js/commit/1a5bebd927ecd22f9c34617642fdf58fe3f62efb), closes [#749](https://github.com/angular/angular.js/issues/749))
- **$log:**
- avoid console.log.apply calls in IE ([15213ec2](https://github.com/angular/angular.js/commit/15213ec212769837cb2b7e781ffc5bfd598d27ca), closes [#805](https://github.com/angular/angular.js/issues/805))
- **$resource:**
- support escaping of ':' in resource url ([6d6f8753](https://github.com/angular/angular.js/commit/6d6f875345e01f2c6c63ef95164f6f39e923da15))
- **compiler:**
- allow transclusion of root elements ([9918b748](https://github.com/angular/angular.js/commit/9918b748be01266eb10db39d51b4d3098d54ab66))
- **e2e runner:**
- fix typo that caused errors on IE8 ([ee5a5352](https://github.com/angular/angular.js/commit/ee5a5352fd4b94cedee6ef20d4bf2d43ce77e00b), closes [#806](https://github.com/angular/angular.js/issues/806))
- **forEach:**
- should ignore prototypically inherited properties ([8d7e6948](https://github.com/angular/angular.js/commit/8d7e6948496ff26ef1da8854ba02fcb8eebfed61), closes [#813](https://github.com/angular/angular.js/issues/813))
- **forms:**
- Remove double registering of form ([1faafa31](https://github.com/angular/angular.js/commit/1faafa31582c4e9413f48dc7d12f5b681f9fe9fd))
- Set ng-valid/ng-invalid correctly ([08bfea18](https://github.com/angular/angular.js/commit/08bfea183a850b29da270eac47f80b598cbe600f))
- **init:**
- use jQuery#ready for init if available ([cb2ad9ab](https://github.com/angular/angular.js/commit/cb2ad9abf24e6f855cc749efe3155bd7987ece9d), closes [#818](https://github.com/angular/angular.js/issues/818))
- **json:**
- added support for iso8061 timezone ([5ac14f63](https://github.com/angular/angular.js/commit/5ac14f633a69f49973b5512780c6ec7752405967))
- **matchers.toHaveClass:**
- Correct reference to angular.mock.dump ([f701ce08](https://github.com/angular/angular.js/commit/f701ce08f9d63be05fc3b92f57ad473e1e749b2d))
- **ng-switch:**
- properly destroy child scopes ([2315d9b3](https://github.com/angular/angular.js/commit/2315d9b3610994b36c44e4a97fb1427d59471ce8))
- **ngDocSpec:**
- fix broken tests ([53b6f522](https://github.com/angular/angular.js/commit/53b6f522a56eea314cbd084816e08f24b2c7879f))
- **ngForm:**
- alias name||ngForm ([823adb23](https://github.com/angular/angular.js/commit/823adb231995e917bc060bfa49453e2a96bac2b6))
- **ngRepeat:**
- correct variable reference in error message ([935c1018](https://github.com/angular/angular.js/commit/935c1018da05dbf3124b2dd33619c4a3c82d7a2a))
- **ngView:**
- controller not published ([21e74c2d](https://github.com/angular/angular.js/commit/21e74c2d2e8e985b23711785287feb59965cbd90))
- **q:**
- resolve all of nothing to nothing ([ac75079e](https://github.com/angular/angular.js/commit/ac75079e2113949d5d64adbcf23d56f3cf295d41))
- **select:**
- multiselect failes to update view on selection insert ([6ecac8e7](https://github.com/angular/angular.js/commit/6ecac8e71a84792a434d21db2c245b3648c55f18))
## Features
- **$compile:**
- do not interpolate boolean attributes, rather evaluate them ([a08cbc02](https://github.com/angular/angular.js/commit/a08cbc02e78e789a66e9af771c410e8ad1646e25))
- **$controller:**
- support controller registration via $controllerProvider ([d54dfecb](https://github.com/angular/angular.js/commit/d54dfecb00fba41455536c5ddd55310592fdaf84))
- **$route:**
- when matching consider trailing slash as optional ([a4fe51da](https://github.com/angular/angular.js/commit/a4fe51da3ba0dc297ecd389e230d6664f250c9a6), closes [#784](https://github.com/angular/angular.js/issues/784))
- **assertArgFn:**
- should support array annotated fns ([4b8d9260](https://github.com/angular/angular.js/commit/4b8d926062eb4d4483555bdbdec4656f585ab40b))
- **http:**
- added params parameter ([73c85930](https://github.com/angular/angular.js/commit/73c8593077155a9f2e8ef42efd4c497eba0bef4f))
- **injector:**
- infer _foo_ as foo ([f13dd339](https://github.com/angular/angular.js/commit/f13dd3393dfb7a33565c9360342c193bc0bddcb6))
- **input.radio:**
- Allow value attribute to be interpolated ([ade6c452](https://github.com/angular/angular.js/commit/ade6c452753145c84884d17027a7865bf4b34b0c))
- **jqLite:**
- make injector() and scope() work with the document object ([5fdab52d](https://github.com/angular/angular.js/commit/5fdab52dd7c269f99839f4fa6b5854d9548269fa))
- add .controller() method ([6c5a05ad](https://github.com/angular/angular.js/commit/6c5a05ad49a1e083570c3dfe331403398f899dbe))
- **ngValue:**
- allow radio inputs to have non string values ([09e175f0](https://github.com/angular/angular.js/commit/09e175f02cca0f4a295fd0c9b980cd8f432e722b), closes [#816](https://github.com/angular/angular.js/issues/816))
- **scope:**
- broadcast $destroy event on scope destruction ([9b1aff90](https://github.com/angular/angular.js/commit/9b1aff905b638aa274a5fc8f88662df446d374bd))
- **scope.$eval:**
- Allow passing locals to the expression ([192ff61f](https://github.com/angular/angular.js/commit/192ff61f5d61899e667c6dbce4d3e6e399429d8b))
## Breaking Changes
- boolean attrs are evaluated rather than interpolated ([a08cbc02](https://github.com/angular/angular.js/commit/a08cbc02e78e789a66e9af771c410e8ad1646e25))
- ng-bind-attr directive removed ([55027132](https://github.com/angular/angular.js/commit/55027132f3d57e5dcf94683e6e6bd7b0aae0087d))
- any app that depends on this service and its fallback to Modernizr, please ([aaedefb9](https://github.com/angular/angular.js/commit/aaedefb92e6bec6626e173e5155072c91471596a))
Executable
+5
View File
@@ -0,0 +1,5 @@
#!/bin/bash
grunt minify
gzip -c < build/angular.min.js > build/angular.min.js.gzip
ls -l build/angular.min.*
+14
View File
@@ -0,0 +1,14 @@
This file contains externs for use with the Closure compiler (aka JSCompiler).
Passing these files to the --externs parameter of a compiler pass allows using
type annotations for AngularJS objects. For example, Angular's $scope objects
can be annotated as:
/** @type {angular.Scope} */ var scope = $scope;
This allows JSCompiler to type check accesses to scope, give warnings about
missing methods or incorrect arguments, and also prevents renaming of property
accesses with advanced compilation.
The externs are incomplete and maintained on an as-needed basis, but strive to
be correct. Externs for individual modules should be added in separate files.
See https://developers.google.com/closure/compiler/
+1719
View File
File diff suppressed because it is too large Load Diff
+1 -1
View File
@@ -2,7 +2,7 @@
[ng\:cloak], [ng-cloak], [data-ng-cloak], [x-ng-cloak],
.ng-cloak, .x-ng-cloak {
display: none;
display: none !important;
}
ng\:form {
+3 -59
View File
@@ -2,62 +2,6 @@
@name API Reference
@description
## Angular Compiler API
* {@link angular.module.ng.$compileProvider.directive Directives} - Angular DOM element attributes
* {@link angular.module.ng.$filter Filters} - Angular output filters
* {@link angular.module.ng.$compile $compile} - Template compiler
## Angular Scope API
* {@link angular.module.ng.$rootScope.Scope Scope Object} - Angular scope object
## Angular Services & Dependency Injection API
* {@link angular.module.ng Angular Services}
* {@link angular.injector angular.injector() }
## Angular Testing API
* {@link angular.module.ngMock Testing Mocks API} - Mock objects for testing
* {@link guide/dev_guide.e2e-testing Angular Scenario Runner} - Automated scenario testing
documentation
## Angular Utility Functions
### HTML & DOM Manipulation
* {@link angular.element angular.element()}
### Misc
* {@link angular.bind angular.bind() }
* {@link angular.extend angular.extend() }
* {@link angular.forEach angular.forEach() }
* {@link angular.identity angular.identity() }
* {@link angular.noop angular.noop() }
## Type Identification
* {@link angular.isArray angular.isArray() }
* {@link angular.isDate angular.isDate() }
* {@link angular.isDefined angular.isDefined() }
* {@link angular.isFunction angular.isFunction() }
* {@link angular.isNumber angular.isNumber() }
* {@link angular.isObject angular.isObject() }
* {@link angular.isString angular.isString() }
* {@link angular.isUndefined angular.isUndefined() }
## Strings
* {@link angular.lowercase angular.lowercase() }
* {@link angular.uppercase angular.uppercase() }
### JSON
* {@link angular.fromJson angular.fromJson() }
* {@link angular.toJson angular.toJson() }
Use the API Reference documentation when you need more information about a specific feature. Check out
{@link guide/ Developer Guide} for AngularJS concepts. If you are new to AngularJS we recommend the
{@link tutorial/ Tutorial}.
@@ -1,5 +1,5 @@
@ngdoc overview
@name angular.module.ng
@name ng
@description
The `ng` is an angular module which contains all of the core angular services.
+2 -2
View File
@@ -85,8 +85,8 @@ detection, and preventing invalid form submission.
<input type="text" ng-model="contact.value" required/>
[ <a href="" ng-click="removeContact(contact)">X</a> ]
</div>
<button ng-click="cancel()" ng-disabled="{{isCancelDisabled()}}">Cancel</button>
<button ng-click="save()" ng-disabled="{{isSaveDisabled()}}">Save</button>
<button ng-click="cancel()" ng-disabled="isCancelDisabled()">Cancel</button>
<button ng-click="save()" ng-disabled="isSaveDisabled()">Save</button>
</form>
<hr/>
+12 -12
View File
@@ -3,7 +3,7 @@
@description
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
{@link http://code.google.com/apis/buzz/v1/getting_started.html#background-operations| Google Buzz
API}
@@ -12,22 +12,22 @@ to retrieve Buzz activity and comments.
<doc:example>
<doc:source>
<script>
BuzzController.$inject = ['$resource'];
function BuzzController($resource) {
this.userId = 'googlebuzz';
this.Activity = $resource(
BuzzController.$inject = ['$scope', '$resource'];
function BuzzController($scope, $resource) {
$scope.userId = 'googlebuzz';
$scope.Activity = $resource(
'https://www.googleapis.com/buzz/v1/activities/:userId/:visibility/:activityId/:comments',
{alt: 'json', callback: 'JSON_CALLBACK'},
{ get: {method: 'JSONP', params: {visibility: '@self'}},
replies: {method: 'JSONP', params: {visibility: '@self', comments: '@comments'}}
});
}
BuzzController.prototype = {
fetch: function() {
this.activities = this.Activity.get({userId:this.userId});
},
expandReplies: function(activity) {
activity.replies = this.Activity.replies({userId: this.userId, activityId: activity.id});
$scope.fetch = function() {
$scope.activities = $scope.Activity.get({userId:this.userId});
}
$scope.expandReplies = function(activity) {
activity.replies = $scope.Activity.replies({userId: this.userId, activityId: activity.id});
}
};
</script>
+92 -53
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
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.
# Assumptions
@@ -30,83 +30,122 @@ In this example we have a simple app which consist of two screens:
* Welcome: url `welcome` Show the user contact information.
* Settings: url `settings` Show an edit screen for user contact information.
<example module="deepLinking" deps="angular-sanitize.js">
<file name="script.js">
angular.module('deepLinking', ['ngSanitize'])
.config(function($routeProvider) {
$routeProvider.
when("/welcome", {templateUrl:'welcome.html', controller:WelcomeCntl}).
when("/settings", {templateUrl:'settings.html', controller:SettingsCntl});
});
The two partials are defined in the following URLs:
AppCntl.$inject = ['$scope', '$route']
function AppCntl($scope, $route) {
$scope.$route = $route;
* <a href="./examples/settings.html" ng-ext-link>./examples/settings.html</a>
* <a href="./examples/welcome.html" ng-ext-link>./examples/welcome.html</a>
// initialize the model to something useful
$scope.person = {
name:'anonymous',
contacts:[{type:'email', url:'anonymous@example.com'}]
};
}
<doc:example module="deepLinking">
<doc:source jsfiddle="false">
<script>
angular.module('deepLinking', [])
.config(function($routeProvider) {
$routeProvider.when("/welcome", {template:'./examples/welcome.html', controller:WelcomeCntl});
$routeProvider.when("/settings", {template:'./examples/settings.html', controller:SettingsCntl});
});
function WelcomeCntl($scope) {
$scope.greet = function() {
alert("Hello " + $scope.person.name);
};
}
AppCntl.$inject = ['$scope', '$route']
function AppCntl($scope, $route) {
// initialize the model to something useful
$scope.person = {
name:'anonymous',
contacts:[{type:'email', url:'anonymous@example.com'}]
};
}
function SettingsCntl($scope, $location) {
$scope.cancel = function() {
$scope.form = angular.copy($scope.person);
};
function WelcomeCntl($scope) {
$scope.greet = function() {
alert("Hello " + $scope.person.name);
};
}
$scope.save = function() {
angular.copy($scope.form, $scope.person);
$location.path('/welcome');
};
function SettingsCntl($scope, $location) {
$scope.cancel = function() {
$scope.form = angular.copy($scope.person);
};
$scope.cancel();
}
</file>
<file name="style.css">
[ng-view] {
border: 1px solid blue;
margin: 0;
padding:1em;
}
$scope.save = function() {
angular.copy($scope.form, $scope.person);
$location.path('/welcome');
};
$scope.cancel();
}
</script>
.partial-info {
background-color: blue;
color: white;
padding: 3px;
}
</file>
<file name="index.html">
<div ng-controller="AppCntl">
<h1>Your App Chrome</h1>
[ <a href="welcome">Welcome</a> | <a href="settings">Settings</a> ]
<hr/>
<span style="background-color: blue; color: white; padding: 3px;">
<span class="partial-info">
Partial: {{$route.current.template}}
</span>
<ng:view style="border: 1px solid blue; margin: 0; display:block; padding:1em;"></ng:view>
<div ng-view></div>
<small>Your app footer </small>
</div>
</doc:source>
<doc:scenario>
</file>
<file name="settings.html">
<label>Name:</label>
<input type="text" ng:model="form.name" required>
<div ng:repeat="contact in form.contacts">
<select ng:model="contact.type">
<option>url</option>
<option>email</option>
<option>phone</option>
</select>
<input type="text" ng:model="contact.url">
[ <a href="" ng:click="form.contacts.$remove(contact)">X</a> ]
</div>
<div>
[ <a href="" ng:click="form.contacts.$add()">add</a> ]
</div>
<button ng:click="cancel()">Cancel</button>
<button ng:click="save()">Save</button>
</file>
<file name="welcome.html">
Hello {{person.name}},
<div>
Your contact information:
<div ng:repeat="contact in person.contacts">{{contact.type}}:
<span ng-bind-html="contact.url|linky"></span>
</div>
</div>
</file>
<file name="scenario.js">
it('should navigate to URL', function() {
element('a:contains(Welcome)').click();
expect(element('ng\\:view').text()).toMatch(/Hello anonymous/);
element('a:contains(Settings)').click();
input('form.name').enter('yourname');
element(':button:contains(Save)').click();
element('a:contains(Welcome)').click();
expect(element('ng\\:view').text()).toMatch(/Hello yourname/);
element('a:contains(Welcome)').click();
expect(element('[ng-view]').text()).toMatch(/Hello anonymous/);
element('a:contains(Settings)').click();
input('form.name').enter('yourname');
element(':button:contains(Save)').click();
element('a:contains(Welcome)').click();
expect(element('[ng-view]').text()).toMatch(/Hello yourname/);
});
</doc:scenario>
</doc:example>
</file>
</example>
# Things to notice
* Routes are defined in the `AppCntl` class. The initialization of the controller causes the
initialization of the {@link api/angular.module.ng.$route $route} service with the proper URL
initialization of the {@link api/ng.$route $route} service with the proper URL
routes.
* The {@link api/angular.module.ng.$route $route} service then watches the URL and instantiates the
* The {@link api/ng.$route $route} service then watches the URL and instantiates the
appropriate controller when the URL changes.
* The {@link api/angular.module.ng.$compileProvider.directive.ng-view ng-view} widget loads the
* The {@link api/ng.directive:ngView ngView} widget loads the
view when the URL changes. It also sets the view scope to the newly instantiated controller.
* Changing the URL is sufficient to change the controller and view. It makes no difference whether
the URL is changed programatically or by the user.
+18 -19
View File
@@ -2,7 +2,7 @@
@name Cookbook: Form
@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
allow a user to enter data.
@@ -11,7 +11,7 @@ allow a user to enter data.
<doc:source>
<script>
function FormController($scope) {
$scope.user = {
var user = $scope.user = {
name: 'John Smith',
address:{line1: '123 Main St.', city:'Anytown', state:'AA', zip:'12345'},
contacts:[{type:'phone', value:'1(234) 555-1212'}]
@@ -20,12 +20,12 @@ allow a user to enter data.
$scope.zip = /^\d\d\d\d\d$/;
$scope.addContact = function() {
$scope.user.contacts.push({type:'', value:''});
user.contacts.push({type:'email', value:''});
};
$scope.removeContact = function(contact) {
for (var i = 0, ii = this.user.contacts.length; i < ii; i++) {
if (contact === this.user.contacts[i]) {
for (var i = 0, ii = user.contacts.length; i < ii; i++) {
if (contact === user.contacts[i]) {
$scope.user.contacts.splice(i, 1);
}
}
@@ -34,16 +34,16 @@ allow a user to enter data.
</script>
<div ng-controller="FormController" class="example">
<label>Name:</label><br/>
<input type="text" ng-model="user.name" required/> <br/><br/>
<label>Name:</label><br>
<input type="text" ng-model="user.name" required/> <br><br>
<label>Address:</label><br/>
<input type="text" ng-model="user.address.line1" size="33" required> <br/>
<label>Address:</label><br>
<input type="text" ng-model="user.address.line1" size="33" required> <br>
<input type="text" ng-model="user.address.city" size="12" required>,
<input type="text" ng-model="user.address.state" size="2"
ng-pattern="state" required>
<input type="text" ng-model="user.address.state"
ng-pattern="state" size="2" required>
<input type="text" ng-model="user.address.zip" size="5"
ng-pattern="zip" required><br/><br/>
ng-pattern="zip" required><br><br>
<label>Phone:</label>
[ <a href="" ng-click="addContact()">add</a> ]
@@ -54,12 +54,12 @@ allow a user to enter data.
<option>pager</option>
<option>IM</option>
</select>
<input type="text" ng-model="contact.value" required/>
<input type="text" ng-model="contact.value" required>
[ <a href="" ng-click="removeContact(contact)">X</a> ]
</div>
<hr/>
Debug View:
<pre>user={{user}}</pre>
<pre>user={{user | json}}</pre>
</div>
</doc:source>
@@ -102,14 +102,13 @@ allow a user to enter data.
# Things to notice
* The user data model is initialized {@link api/angular.module.ng.$compileProvider.directive.ng-controller controller} and is
available in the {@link api/angular.module.ng.$rootScope.Scope scope} with the initial data.
* The user data model is initialized {@link api/ng.directive:ngController controller} and is
available in the {@link api/ng.$rootScope.Scope scope} with the initial data.
* For debugging purposes we have included a debug view of the model to better understand what
is going on.
* The {@link api/angular.module.ng.$compileProvider.directive.input input directives} simply refer
* The {@link api/ng.directive:input input directives} simply refer
to the model and are data-bound.
* The inputs {@link guide/dev_guide.forms validate}. (Try leaving them blank or entering non digits
in the zip field)
* The inputs validate. (Try leaving them blank or entering non digits in the zip field)
* In your application you can simply read from or write to the model and the form will be updated.
* By clicking the 'add' link you are adding new items into the `user.contacts` array which are then
reflected in the view.
+6 -6
View File
@@ -10,9 +10,9 @@
}
</script>
<div ng-controller="HelloCntl">
Your name: <input type="text" ng-model="name" value="World"/>
Your name: <input type="text" ng-model="name"/>
<hr/>
Hello {{name}}!
Hello {{name || "World"}}!
</div>
</doc:source>
<doc:scenario>
@@ -28,11 +28,11 @@
Take a look through the source and note:
* The script tag that {@link guide/dev_guide.bootstrap bootstraps} the angular environment.
* The text {@link api/angular.module.ng.$compileProvider.directive.input input widget} which is
* The script tag that {@link guide/bootstrap bootstraps} the Angular environment.
* The text {@link api/ng.directive:input input form control} which is
bound to the greeting name text.
* 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/angular.module.ng.$rootScope.Scope scope}.
* 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 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
changes to the
+4 -4
View File
@@ -2,7 +2,7 @@
@name Cookbook
@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
@@ -44,8 +44,8 @@ allowing you to send links to specific screens in your app.
# Services
{@link api/angular.module.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
{@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
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
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
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.
+7 -6
View File
@@ -2,13 +2,14 @@
@name Cookbook: MVC
@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
view. This makes it very easy for the controller and the view to share the model.
The model is simply the controller's this. This makes it very easy to test the controller in
isolation since one can simply instantiate the controller and test without a view, because there is
no connection between the controller and the view.
The model is a set of objects and primitives that are referenced from the Scope ($scope) object.
This makes it very easy to test the controller in isolation since one can simply instantiate the
controller and test without a view, because there is no connection between the controller and the
view.
<doc:example>
@@ -114,7 +115,7 @@ no connection between the controller and the view.
# Things to notice
* 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.
This makes it very testable.
* The HTML view is a projection of the model. In the above example, the model is stored in the
@@ -124,4 +125,4 @@ board variable.
* The view can call any controller function.
* In this example, the `setUrl()` and `readUrl()` functions copy the game state to/from the URL's
hash so the browser's back button will undo game steps. See deep-linking. This example calls {@link
api/angular.module.ng.$rootScope.Scope#$watch $watch()} to set up a listener that invokes `readUrl()` when needed.
api/ng.$rootScope.Scope#$watch $watch()} to set up a listener that invokes `readUrl()` when needed.
+114
View File
@@ -0,0 +1,114 @@
@ngdoc overview
@name Developer Guide: Bootstrap
@description
# Overview
This page explains the Angular initialization process and how you can manually initialize Angular
if necessary.
## Angular `<script>` Tag
This example shows the recommended path for integrating Angular with what we call automatic
initialization.
<pre>
<!doctype html>
<html xmlns:ng="http://angularjs.org" ng-app>
<body>
...
<script src="angular.js">
</body>
</html>
</pre>
* Place the `script` tag at the bottom of the page. Placing script tags at the end of the page
improves app load time because the HTML loading is not blocked by loading of the `angular.js`
script. You can get the latest bits from {@link http://code.angularjs.org}. Please don't link
your production code to this URL, as it will expose a security hole on your site. For
experimental development linking to our site is fine.
* Choose: `angular-[version].js` for a human-readable file, suitable for development and
debugging.
* Choose: `angular-[version].min.js` for a compressed and obfuscated file, suitable for use in
production.
* Place `ng-app` to the root of your application, typically on the `<html>` tag if you want
angular to auto-bootstrap your application.
<html ng-app>
* If IE7 support is required add `id="ng-app"`
<html ng-app id="ng-app">
* If you choose to use the old style directive syntax `ng:` then include xml-namespace in `html`
to make IE happy. (This is here for historical reasons, and we no longer recommend use of
`ng:`.)
<html xmlns:ng="http://angularjs.org">
## Automatic Initialization
Angular initializes automatically upon `DOMContentLoaded` event, at which point Angular looks for
the {@link api/ng.directive:ngApp `ng-app`} directive which
designates your application root. If the {@link
api/ng.directive:ngApp `ng-app`} directive is found then Angular
will:
* load the {@link guide/module module} associated with the directive.
* create the application {@link api/AUTO.$injector injector}
* compile the DOM treating the {@link api/ng.directive:ngApp
`ng-app`} directive as the root of the compilation. This allows you to tell it to treat only a
portion of the DOM as an Angular application.
<pre>
<!doctype html>
<html ng-app="optionalModuleName">
<body>
I can add: {{ 1+2 }}.
<script src="angular.js"></script>
</body>
</html>
</pre>
## Manual Initialization
If you need to have more control over the initialization process, you can use a manual
bootstrapping method instead. Examples of when you'd need to do this include using script loaders
or the need to perform an operation before Angular compiles a page.
Here is an example of manually initializing Angular:
<pre>
<!doctype html>
<html xmlns:ng="http://angularjs.org">
<body>
Hello {{'World'}}!
<script src="http://code.angularjs.org/angular.js"></script>
<script>
angular.element(document).ready(function() {
angular.module('myApp', []);
angular.bootstrap(document, ['myApp']);
});
</script>
</body>
</html>
</pre>
Note that we have provided the name of our application module to be loaded into the injector as the second
parameter of the {@link api/angular.bootstrap} function. Notice that `angular.bootstrap` will not create modules
on the fly. You must create any custom {@link guide/module modules} before you pass them as a parameter.
This is the sequence that your code should follow:
1. After the page and all of the code is loaded, find the root element of your AngularJS
application, which is typically the root of the document.
2. Call {@link api/angular.bootstrap} to {@link compiler compile} the element into an
executable, bi-directionally bound application.
+142
View File
@@ -0,0 +1,142 @@
@ngdoc overview
@name Developer Guide: HTML Compiler
@description
# Overview
Angular's {@link api/ng.$compile HTML compiler} allows the developer to teach the
browser new HTML syntax. The compiler allows you to attach behavior to any HTML element or attribute
and even create new HTML elements or attributes with custom behavior. Angular calls these behavior
extensions {@link api/ng.$compileProvider#directive directives}.
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
browser how the window size needs to be divided in half so that the center is found, and that this
center needs to be aligned with the text's center. Simply add an `align="center"` attribute to any
element to achieve the desired behavior. Such is the power of declarative language.
But the declarative language is also limited, since it does not allow you to teach the browser new
syntax. For example there is no easy way to get the browser to align the text at 1/3 the position
instead of 1/2. What is needed is a way to teach the browser new HTML syntax.
Angular comes pre-bundled with common directives which are useful for building any app. We also
expect that you will create directives that are specific to your app. These extensions become a
Domain Specific Language for building your application.
All of this compilation takes place in the web browser; no server side or pre-compilation step is
involved.
# Compiler
Compiler is an angular service which traverses the DOM looking for attributes. The compilation
process happens in two phases.
1. **Compile:** traverse the DOM and collect all of the directives. The result is a linking
function.
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
in the scope model. This makes the scope model the single source of truth.
Some directives such as {@link api/ng.directive:ngRepeat `ng-repeat`} clone DOM elements once
for each item in a collection. Having a compile and link phase improves performance since the
cloned template only needs to be compiled once, and then linked once for each clone instance.
# Directive
A directive is a behavior which should be triggered when specific HTML constructs are encountered
during 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 the {@link
api/ng.directive:ngBind `ng-bind`} directive.
<pre>
<span ng-bind="exp"></span>
<span class="ng-bind: exp;"></span>
<ng-bind></ng-bind>
<!-- directive: ng-bind exp -->
</pre>
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
to write directives.
Here is a directive which makes any element draggable. Notice the `draggable` attribute on the
`<span>` element.
<example module="drag">
<file name="script.js">
angular.module('drag', []).
directive('draggable', function($document) {
return function(scope, element, attr) {
var startX = 0, startY = 0, x = 0, y = 0;
element.css({
position: 'relative',
border: '1px solid red',
backgroundColor: 'lightgrey',
cursor: 'pointer'
});
element.bind('mousedown', function(event) {
// Prevent default dragging of selected content
event.preventDefault();
startX = event.screenX - x;
startY = event.screenY - y;
$document.bind('mousemove', mousemove);
$document.bind('mouseup', mouseup);
});
function mousemove(event) {
y = event.screenY - startY;
x = event.screenX - startX;
element.css({
top: y + 'px',
left: x + 'px'
});
}
function mouseup() {
$document.unbind('mousemove', mousemove);
$document.unbind('mouseup', mouseup);
}
}
});
</file>
<file name="index.html">
<span draggable>Drag ME</span>
</file>
</example>
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
what the browser understands in a way which is natural to anyone who is familiar with HTML
principles.
# Understanding View
There are many templating systems out there. Most of them consume a static string template and
combine it with data, resulting in a new string. The resulting text is then `innerHTML`ed into
an element.
<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
`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
expressiveness.
Angular is different. The Angular compiler consumes the DOM with directives, not string templates.
The result is a linking function, which when combined with a scope model results in a live view. The
view and scope model bindings are transparent. No action from the developer is needed to update
the view. And because no `innerHTML` is used there are no issues of clobbering user input.
Furthermore, Angular directives can contain not just text bindings, but behavioral constructs as
well.
<img src="img/Two_Way_Data_Binding.png">
The Angular approach produces a stable DOM. This means that the DOM element instance bound to a model
item instance does not change for the lifetime of the binding. This means that the code can get
hold of the elements and register event handlers and know that the reference will not be destroyed
by template data merge.
+451
View File
@@ -0,0 +1,451 @@
@ngdoc overview
@name Conceptual Overview
@description
# Overview
This document gives a quick overview of the main angular components and how they work together.
These are:
* {@link concepts#startup startup} - bring up hello world
* {@link concepts#runtime runtime} - overview of angular runtime
* {@link concepts#scope scope} - the glue between the view and the controller
* {@link concepts#controller controller} - application behavior
* {@link concepts#model model} - your application data
* {@link concepts#view view} - what the user sees
* {@link concepts#directives directives} - extend HTML vocabulary
* {@link concepts#filters filters} - format the data in user locale
* {@link concepts#injector injector} - assembles your application
* {@link concepts#module module} - configures the injector
* {@link concepts#angular_namespace `$`} - angular namespace
<a name="startup"></a>
# Startup
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">
1. The browser loads the HTML and parses it into a DOM
2. The browser loads `angular.js` script
3. Angular waits for `DOMContentLoaded` event
4. Angular looks for {@link api/ng.directive:ngApp ng-app}
{@link guide/directive directive}, which designates the application boundary
5. The {@link guide/module Module} specified in {@link
api/ng.directive:ngApp ng-app} (if any) is used to configure
the {@link api/AUTO.$injector $injector}
6. The {@link api/AUTO.$injector $injector} is used to create the {@link
api/ng.$compile $compile} service as well as {@link
api/ng.$rootScope $rootScope}
7. The {@link api/ng.$compile $compile} service is used to compile the DOM and link
it with {@link api/ng.$rootScope $rootScope}
8. The {@link api/ng.directive:ngInit ng-init} {@link
guide/directive directive} assigns `World` to the `name` property on the {@link guide/scope
scope}
9. The `{{name}}` {@link api/ng.$interpolate interpolates} the expression to
`Hello World!`
<example>
<file name="index.html">
<p ng-init=" name='World' ">Hello {{name}}!</p>
</file>
</example>
<a name="runtime"></a>
# Runtime
<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 the browser's event loop.
1. The browser's event-loop waits for an event to arrive. An event is a user interaction, timer event,
or network event (response from a server).
2. The event's callback gets executed. This enters the JavaScript context. The callback can
modify the DOM structure.
3. Once the callback executes, the browser leaves the JavaScript context and
re-renders the view based on DOM changes.
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
applied in Angular execution context will benefit from Angular data-binding, exception handling,
property watching, etc... You can also use $apply() to enter Angular execution context from JavaScript. Keep in
mind that in most places (controllers, services) $apply has already been called for you by the
directive which is handling the event. An explicit call to $apply is needed only when
implementing custom event callbacks, or when working with third-party library callbacks.
1. Enter Angular execution context by calling {@link guide/scope scope}`.`{@link
api/ng.$rootScope.Scope#$apply $apply}`(stimulusFn)`. Where `stimulusFn` is
the work you wish to do in Angular execution context.
2. Angular executes the `stimulusFn()`, which typically modifies application state.
3. Angular enters the {@link api/ng.$rootScope.Scope#$digest $digest} loop. The
loop is made up of two smaller loops which process {@link
api/ng.$rootScope.Scope#$evalAsync $evalAsync} queue and the {@link
api/ng.$rootScope.Scope#$watch $watch} list. The {@link
api/ng.$rootScope.Scope#$digest $digest} loop keeps iterating until the model
stabilizes, which means that the {@link api/ng.$rootScope.Scope#$evalAsync
$evalAsync} queue is empty and the {@link api/ng.$rootScope.Scope#$watch
$watch} list does not detect any changes.
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's
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
each event.
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`
function is called which typically updates the DOM with the new value.
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
re-rendering the DOM to reflect any changes.
Here is the explanation of how the `Hello world` example achieves the data-binding effect when the
user enters text into the text field.
1. During the compilation phase:
1. the {@link api/ng.directive:ngModel ng-model} and {@link
api/ng.directive:input input} {@link guide/directive
directive} set up a `keydown` listener on the `<input>` control.
2. the {@link api/ng.$interpolate &#123;&#123;name&#125;&#125; } interpolation
sets up a {@link api/ng.$rootScope.Scope#$watch $watch} to be notified of
`name` changes.
2. During the runtime phase:
1. Pressing an '`X`' key causes the browser to emit a `keydown` event on the input control.
2. The {@link api/ng.directive:input input} directive
captures the change to the input's value and calls {@link
api/ng.$rootScope.Scope#$apply $apply}`("name = 'X';")` to update the
application model inside the Angular execution context.
3. Angular applies the `name = 'X';` to the model.
4. The {@link api/ng.$rootScope.Scope#$digest $digest} loop begins
5. The {@link api/ng.$rootScope.Scope#$watch $watch} list detects a change
on the `name` property and notifies the {@link api/ng.$interpolate
&#123;&#123;name&#125;&#125; } interpolation, which in turn updates the DOM.
6. Angular exits the execution context, which in turn exits the `keydown` event and with it
the JavaScript execution context.
7. The browser re-renders the view with update text.
<example>
<file name="index.html">
<input ng-model="name">
<p>Hello {{name}}!</p>
</file>
</example>
<a name="scope"></a>
#Scope
The {@link guide/scope scope} is responsible for detecting changes to the model section and
provides the execution context for expressions. The scopes are nested in a hierarchical structure
which closely follow the DOM structure. (See individual directive documentation to see which
directives cause a creation of new scopes.)
The following example demonstrates how the `name` {@link guide/expression expression} will evaluate
into a different value depending on which scope it is evaluated in. The example is followed by
a diagram depicting the scope boundaries.
<div class="show-scope">
<example>
<file name="index.html">
<div ng-controller="GreetCtrl">
Hello {{name}}!
</div>
<div ng-controller="ListCtrl">
<ol>
<li ng-repeat="name in names">{{name}}</li>
</ol>
</div>
</file>
<file name="script.js">
function GreetCtrl($scope) {
$scope.name = 'World';
}
function ListCtrl($scope) {
$scope.names = ['Igor', 'Misko', 'Vojta'];
}
</file>
<file name="style.css">
.show-scope .doc-example-live.ng-scope,
.show-scope .doc-example-live .ng-scope {
border: 1px solid red;
margin: 3px;
}
</file>
</example>
</div>
<img class="center" src="img/guide/concepts-scope.png">
<a name="controller"></a>
# Controller
<img class="pull-right" style="padding-left: 3em; padding-bottom: 1em;" src="img/guide/concepts-controller.png">
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
HTML). The scope is the glue which marshals the model to the view and forwards the events to the
controller.
The separation of the controller and the view is important because:
* The controller is written in JavaScript. JavaScript is imperative. Imperative is a good fit
for specifying application behavior. The controller should not contain any rendering
information (DOM references or HTML fragments).
* The view template is written in HTML. HTML is declarative. Declarative is a good fit for
specifying UI. The View should not contain any behavior.
* Since the controller is unaware of the view, there could be many views for the same
controller. This is important for re-skinning, device specific views (i.e. mobile vs desktop),
and testability.
<example>
<file name="index.html">
<div ng-controller="MyCtrl">
Hello {{name}}!
<button ng-click="action()">
OK
</button>
</div>
</file>
<file name="script.js">
function MyCtrl($scope) {
$scope.action = function() {
$scope.name = 'OK';
}
$scope.name = 'World';
}
</file>
</example>
<a name="model"></a>
# Model
<img class="pull-right" style="padding-left: 3em; padding-bottom: 1em;" src="img/guide/concepts-model.png">
The model is the data which is merged with the template to produce the view. To be able to
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 on the model. There are no classes
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.
<a name="view"></a>
# View
<img class="pull-right" style="padding-left: 3em; padding-bottom: 1em;" src="img/guide/concepts-view.png">
The view is what the user sees. The view begins its life as a template, is merged with the
model and finally rendered into the browser DOM. Angular takes a very different approach to
rendering the view compared to most other templating systems.
* **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
edited by an HTML editor. The template string is then parsed by the template engine, and
merged with the data. The result of the merge is an HTML string. The HTML string is then
written to the browser using the `.innerHTML`, which causes the browser to render the HTML.
When the model changes the whole process needs to be repeated. The granularity of the template
is the granularity of the DOM updates. The key here is that the templating system manipulates
strings.
* **Angular** - Angular is different, since its templating system works on DOM objects not on
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 the DOM, and the DOM becomes the input to
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
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
the single source-of-truth for your view.
<example>
<file name="index.html">
<div ng-init="list = ['Chrome', 'Safari', 'Firefox', 'IE'] ">
<input ng-model="list" ng-list> <br>
<input ng-model="list" ng-list> <br>
<pre>list={{list}}</pre> <br>
<ol>
<li ng-repeat="item in list">
{{item}}
</li>
</ol>
</div>
</file>
</example>
<a name="directives"></a>
# Directives
A directive is a behavior or DOM transformation which is triggered by the presence of a custom attribute,
element name, class name or comment. A directive allows you to extend the HTML vocabulary in a
declarative fashion. Following is an example which enables data-binding for the `contenteditable`
in HTML.
<example module="directive">
<file name="script.js">
angular.module('directive', []).directive('contenteditable', function() {
return {
require: 'ngModel',
link: function(scope, elm, attrs, ctrl) {
// view -> model
elm.bind('blur', function() {
scope.$apply(function() {
ctrl.$setViewValue(elm.html());
});
});
// model -> view
ctrl.$render = function(value) {
elm.html(value);
};
// load init value from DOM
ctrl.$setViewValue(elm.html());
}
};
});
</file>
<file name="index.html">
<div contentEditable="true" ng-model="content">Edit Me</div>
<pre>model = {{content}}</pre>
</file>
<file name="style.css">
div[contentEditable] {
cursor: pointer;
background-color: #D0D0D0;
margin-bottom: 1em;
padding: 1em;
}
</file>
</example>
<a name="filters"></a>
# Filters
{@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 follow the spirit of UNIX filters and use similar syntax `|` (pipe).
<example>
<file name="index.html">
<div ng-init="list = ['Chrome', 'Safari', 'Firefox', 'IE'] ">
Number formatting: {{ 1234567890 | number }} <br>
array filtering <input ng-model="predicate">
{{ list | filter:predicate | json }}
</div>
</file>
</example>
<a name="module"></a>
<a name="injector"></a>
# Modules and the Injector
<img class="pull-right" style="padding-left: 3em; padding-bottom: 1em;" src="img/guide/concepts-module-injector.png">
The {@link api/AUTO.$injector injector} is a service locator. There is a single
{@link api/AUTO.$injector injector} per Angular {@link
api/ng.directive:ngApp application}. The {@link
api/AUTO.$injector injector} provides a way to look up an object instance by its
name. The injector keeps an internal cache of all objects so that repeated calls to get the same
object name result in the same instance. If the object does not exist, then the {@link
api/AUTO.$injector injector} asks the instance factory to create a new instance.
A {@link api/angular.Module module} is a way to configure the injector's instance factory, known
as a {@link api/AUTO.$provide provider}.
<pre>
// Create a module
var myModule = angular.module('myModule', [])
// Configure the injector
myModule.factory('serviceA', function() {
return {
// instead of {}, put your object creation here
};
});
// create an injector and configure it from 'myModule'
var $injector = angular.injector(['myModule']);
// retrieve an object from the injector by name
var serviceA = $injector.get('serviceA');
// always true because of instance cache
$injector.get('serviceA') === $injector.get('serviceA');
</pre>
But the real magic of the {@link api/AUTO.$injector injector} is that it can be
used to {@link api/AUTO.$injector#invoke call} methods and {@link
api/AUTO.$injector#instantiate instantiate} types. This subtle feature is what
allows the methods and types to ask for their dependencies instead of having to look for them.
<pre>
// You write functions such as this one.
function doSomething(serviceA, serviceB) {
// do something here.
}
// Angular provides the injector for your application
var $injector = ...;
///////////////////////////////////////////////
// the old-school way of getting dependencies.
var serviceA = $injector.get('serviceA');
var serviceB = $injector.get('serviceB');
// now call the function
doSomething(serviceA, serviceB);
///////////////////////////////////////////////
// the cool way of getting dependencies.
// the $injector will supply the arguments to the function automatically
$injector.invoke(doSomething); // This is how the framework calls your functions
</pre>
Notice that the only thing you needed to write was the function, and list the dependencies in the
function arguments. When angular calls the function, it will use the {@link
api/AUTO.$injector#invoke call} which will automatically fill the function
arguments.
Examine the `ClockCtrl` below, and notice how it lists the dependencies in the constructor. When the
{@link api/ng.directive:ngController ng-controller} instantiates
the controller it automatically provides the dependencies. There is no need to create
dependencies, look for dependencies, or even get a reference to the injector.
<example module="timeExampleModule">
<file name="index.html">
<div ng-controller="ClockCtrl">
Current time is: {{ time.now }}
</div>
</file>
<file name="script.js">
angular.module('timeExampleModule', []).
// Declare new object called time,
// which will be available for injection
factory('time', function($timeout) {
var time = {};
(function tick() {
time.now = new Date().toString();
$timeout(tick, 1000);
})();
return time;
});
// Notice that you can simply ask for time
// and it will be provided. No need to look for it.
function ClockCtrl($scope, time) {
$scope.time = time;
}
</file>
</example>
<a name="angular_namespace"></a>
# Angular Namespace
To prevent accidental name collision, Angular prefixes names of objects which could potentially
collide with `$`. Please do not use the `$` prefix in your code as it may accidentally collide
with Angular code.
@@ -1,49 +0,0 @@
@ngdoc overview
@name Developer Guide: Initializing Angular: Automatic Initialization
@description
Angular initializes automatically when you load the angular script into your page that contains an element
with `ng-app` directive:
<pre>
<!doctype html>
<html ng-app>
<head>
<script src="angular.js"></script>
</head>
<body>
I can add: {{ 1+2 }}.
</body>
</html>
</pre>
From a high-level view, this is what happens during angular's automatic initialization process:
1. The browser loads the page, and then runs the angular script. Angular waits for the
`DOMContentLoaded` (or 'Load') event to attempt to bootstrap.
2. Angular looks for the `ng-app` directive. If found it then proceeds to compile the DOM element and its children.
Optionally the `ng-app` may specify a {@link api/angular.module module} to load before the compilation. For details on
how the compiler works, see {@link dev_guide.compiler Angular HTML Compiler}.
## Initialization Options
The reason why `ng-app` exists is because angular should not assume that the entire HTML
document should be processed just because the `angular.js` script is included. In order to compile
only a part of the document set the `ng-app` on the root element of this portion.
## Global Angular Object
The angular script creates a single global variable `angular` in the global namespace. All angular
APIs are bound to fields of this global object.
## Related Topics
* {@link dev_guide.bootstrap Initializing Angular}
* {@link dev_guide.bootstrap.manual_bootstrap Manual Initialization}
## Related API
{@link api/angular.module.ng.$compile Compiler API}
@@ -1,46 +0,0 @@
@ngdoc overview
@name Developer Guide: Initializing Angular: Manual Initialization
@description
Letting angular handle the initialization process (bootstrapping) is a handy way to start using
angular, but advanced users who want more control over the initialization process can choose to use
the manual bootstrapping method instead.
The best way to get started with manual bootstrapping is to look at the what happens when you use
{@link api/angular.module.ng.$compileProvider.directive.ng-app ng-app}, by showing each step of the process
explicitly.
<pre>
<!doctype html>
<html>
<head>
<script src="http://code.angularjs.org/angular.js"></script>
<script>
angular.element(document).ready(function() {
angular.bootstrap(document);
});
</script>
</head>
<body>
Hello {{'World'}}!
</body>
</html>
</pre>
This is the sequence that your code should follow if you bootstrap angular on your own:
1. After the page is loaded, find the root of the HTML template, which is typically the root of
the document.
2. Call {@link api/angular.bootstrap} to {@link dev_guide.compiler compile} the template into
an executable, bi-directionally bound application.
## Related Topics
* {@link dev_guide.bootstrap Initializing Angular}
* {@link dev_guide.bootstrap.auto_bootstrap Automatic Initialization}
* {@link dev_guide.compiler Angular HTML compiler}
## Related API
{@link api/angular.module.ng.$compile Compiler API}
@@ -1,65 +0,0 @@
@ngdoc overview
@name Developer Guide: Initializing Angular
@description
Initializing angular consists of loading the `angular.js` script in your page, and specifying how
angular should process and manage the page. To initialize angular you do the following:
* Specify the angular namespace in the `<html>` page
* Choose which flavor of angular script to load (debug or production)
* Specify whether or not angular should process and manage the page automatically (`ng-app`)
The simplest way to initialize angular is to load the angular script and tell angular to compile
and manage the whole page. You do this as follows:
<pre>
<!doctype html>
<html ng-app>
<head>
...
</head>
<body>
...
<script src="angular.js">
</body>
</pre>
## Specifying the Angular Namespace
<html xmlns:ng="http://angularjs.org">
You need to add the angular namespace declaration if you use `ng:something` style of declaring
angular directives and you write your templates as XHTML. Or when you are targeting Internet
Explorer older than version 9 (because older versions of IE do not render namespace
properly for either HTML or XHTML). For more info please read {@link ie Internet Explorer
Compatibility} doc.
## Creating Your Own Namespaces
When you are ready to define your own {@link api/angular.module.ng.$compileProvider.directive
directive}, you may chose to create your own namespace in addition to specifying the angular
namespace. You use your own namespace to form the fully qualified name for directives that you
create.
For example, you could map the alias `my` to your domain, and create a directive called `my:directive`.
To create your own namespace, simply add another `xmlns` tag to your page, create an alias, and set
it to your unique domain:
<html xmlns:ng="http://angularjs.org" xmlns:my="http://mydomain.com">
## Loading the Angular Bootstrap Script
The angular bootstrap script comes in two flavors; a debug script, and a production script:
* angular-[version].js - This is a human-readable file, suitable for development and debugging.
* angular-[version].min.js - This is a compressed and obfuscated file, suitable for use in
production.
## Related Topics
* {@link dev_guide.bootstrap.auto_bootstrap Automatic Initialization}
* {@link dev_guide.bootstrap.manual_bootstrap Manual Initialization}
@@ -1,23 +0,0 @@
@ngdoc overview
@name Developer Guide: Angular HTML Compiler
@description
The core of angular is its HTML compiler. The compiler processes angular directives allowing them
to transform a static HTML page into a dynamic web application.
The default HTML transformations that the angular compiler provides are useful for building generic
apps, but you can also extend the compiler to create a domain-specific language for building
specific types of web applications.
All compilation takes place in the web browser; no server is involved.
## Related Topics
* {@link dev_guide.compiler.understanding_compiler Understanding How the Compiler Works}
* {@link dev_guide.compiler.testing_dom_element Testing a New DOM Element}
## Related API
* {@link api/angular.module.ng.$compile Angular Compiler API}
* {@link api/angular.module.ng.$compileProvider.directive Directives API}
@@ -1,16 +0,0 @@
@ngdoc overview
@name Developer Guide: Angular HTML Compiler: Testing a New DOM Element
@description
"Testing, testing, come in, over?"
## Related Topics
* {@link dev_guide.compiler Angular HTML Compiler}
* {@link dev_guide.compiler.understanding_compiler Understanding How the Compiler Works}
## Related API
* {@link api/angular.module.ng.$compile $compile()}
@@ -1,34 +0,0 @@
@ngdoc overview
@name Developer Guide: Angular HTML Compiler: Understanding How the Compiler Works
@description
The {@link api/angular.module.ng.$compile compiler} is responsible for applying
{@link api/angular.module.ng.$compileProvider.directive directives} to the HTML. The directives
extend the behavior of HTML elements and can effect the DOM structure, presentation, and behavior.
This allows Angular to teach the browser new tricks.
The compilation starts at the root element and proceeds in a depth-first order. As the compiler
visits each node it collects the directives, orders them by priority and executes their compile
function. The result of the compilation process is a linking function. The linking function
can be used on the template clones to quickly bind the directives with the scope.
The result of the compilation process is a live view. We say 'live' since any changes to the
model attached to the {@link api/angular.module.ng.$rootScope.Scope scope} are reflected in the view,
and any changes in the view are reflected in the scope. This makes the scope the 'single source of
truth'.
Since directives allow attachment of behavior to the HTML, the angular philosophy is to use the
HTML as Domain Specific Language (DSL) when building an application. For example it may be useful
to declare `TabPanel` directive, or `KeyboardShortcut` directive when for an application.
For details on how directives are created see {@link api/angular.module.ng.$compileProvider.directive
directives}
## Related Topics
* {@link dev_guide.compiler Angular HTML Compiler}
* {@link dev_guide.compiler.testing_dom_element Testing a New DOM Element}
## Related API
* {@link api/angular.module.ng.$compile $compile()}
-32
View File
@@ -1,32 +0,0 @@
@ngdoc overview
@name Developer Guide: About Dependency Injection (DI)
@description
Dependency Injection (DI) is an object-oriented software design pattern that supports the
decoupling and dependency management of application components.
The idea behind DI is to decouple each component from all of the other components that it depends
on to do its particular job. The way this is done in DI is by moving the responsibility for
managing dependencies out of each individual component and into a provider component. The provider
(or injector) component manages the life cycles and dependencies for all of the other components in
an application.
Angular has a built-in dependency management subsystem that helps to make your applications easier
to develop, understand, and test.
For more information on DI in general, see {@link http://en.wikipedia.org/wiki/Dependency_injection
Dependency Injection} at Wikipedia, and {@link http://martinfowler.com/articles/injection.html
Inversion of Control} by Martin Fowler, or read about DI in your favorite software design pattern
book.
## Related Topics
* {@link dev_guide.di.understanding_di Understanding DI in Angular}
* {@link dev_guide.services Angular Services}
## Related API
* {@link api/angular.module.ng Service API}
* {@link api/angular.injector Angular Injector API}
@@ -1,193 +0,0 @@
@ngdoc overview
@name Developer Guide: DI: Understanding DI in Angular
@description
While DI is widely used in statically typed languages such as Java or C++, it has not been widely
used in JavaScript. Angular brings the benefits of DI into JavaScript apps.
In angular, DI is implemented as a subsystem that manages dependencies between services,
controllers, widgets, and filters.
Services are objects that handle common tasks in web applications. Angular provides several {@link
api/angular.module.ng built-in services}, and you can create your
{@link dev_guide.services.creating_services own custom services}.
The main job of angular's DI subsystem is to provide services to angular components that depend on
them. The way the DI subsystem provides services is as follows: all services are registered with
angular's {@link api/angular.module.ng service API}, and all components that depend on services
define those dependencies as a property (`$inject`). With this information, the DI subsystem
manages the creation of service objects and the provision of those objects to the components that
need them, at the time they need them. The following illustration steps through the sequence of
events:
<img src="img/guide/di_sequence_final.png">
In the illustration above, the dependency injection sequence proceeds as follows:
1. Module "phonecat" is created and all the service providers are registered with this module.
(the "ng" module is created by Angular behind the scenes as well)
2. `ng-app` triggers bootstrap sequence on given element, during which angular creates injector,
loads "phonecat" and "ng" modules and compiles the template.
3. The `ng-controller` directive implicitly creates a new child scope and instantiates
`PhoneListCtrl` controller.
4. Injector identifies the `$http` service as `PhoneListCtrl` controller's only dependency.
5. Injector checks its instances cache whether the `$http` service has already been instantiated.
If not uses the provider from the available modules to construct it.
6. Injector provides the instance of `$http` service to the `PhoneListCtrl` controller constructor.
## How Scope Relates to DI
The root scope of the application is just a service that is available for injection to any part of
the application under the service name "$rootScope".
## Inferring dependencies from the signature of the factory function or constructor
**EXPERIMENTAL FEATURE**: This is an experimental feature. See the important note at the end of
this section for drawbacks.
We resort to `$inject` and our own annotation because there is no way in JavaScript to get a list
of arguments. Or is there? It turns out that calling `.toString()` on a function returns the
function declaration along with the argument names as shown below:
<pre>
function myFn(a,b){}
expect(myFn.toString()).toEqual('function myFn(a,b){}');
</pre>
This means that angular can infer the function names after all and use that information to generate
the `$inject` annotation automatically. Therefore the following two function definitions are
equivalent:
<pre>
// given a user defined service
angular.module('module1', [], function($provide) {
$provide.factory('serviceA', ...);
});
// inject '$window', 'serviceA', curry 'name';
function fnA($window, serviceA, name){};
fnA.$inject = ['$window', 'serviceA'];
// inject '$window', 'serviceA', curry 'name';
function fnB($window, serviceA_, name){};
// implies: fnB.$inject = ['$window', 'serviceA'];
</pre>
If angular does not find a `$inject` annotation on the function, then it calls the `.toString()`
method and tries to infer what should be injected by using function argument names as dependency
identifiers.
**IMPORTANT**
Minifiers/obfuscators change the names of function arguments and will therefore break the `$inject`
inference. For this reason, either explicitly declare the `$inject` or do not use
minifiers/obfuscators. In the future, we may provide a pre-processor which will scan the source
code and insert the `$inject` into the source code so that it can be minified/obfuscated.
### Dependency inference and variable name shadowing
During inference, the injector considers argument names with leading and trailing underscores to be
equivivalent to the name without these underscores. For example `_fooSvc_` argument name is treated
as if it was `fooSvc`, this is useful especially in tests where variable name shadowing can cause
some friction. This is best illustrated on examples:
When testing a service, it's common to need a reference to it in every single test. This can be
done in jasmine with DI inference like this:
<pre>
describe('fooSvc', function() {
it('should do this thing', inject(function(fooSvc) {
//test fooSvc
}));
it('should do that thing', inject(function(fooSvc) {
//test fooSvc
}));
// more its
});
</pre>
... but having to inject the service over and over gets easily tiresome.
It's likely better to rewrite these tests with a use of jasmine's `beforeEach`:
<pre>
describe('fooSvc', function() {
var fooSvc;
beforeEach(inject(function(fooSvc) {
fooSvc = fooSvc; // DOESN'T WORK! outer fooSvc is being shadowed
}));
it('should do this thing', function() {
//test fooSvc
});
it('should do that thing', function() {
//test fooSvc
});
// more its
});
</pre>
This obviously won't work because `fooSvc` variable in the describe block is being shadowed by the
`fooSvc` argument of the beforeEach function. So we have to resort to alternative solutions, like
for example use of array notation to annotate the beforeEach fn:
<pre>
describe('fooSvc', function() {
var fooSvc;
beforeEach(inject(['fooSvc', function(fooSvc_) {
fooSvc = fooSvc_;
}]));
it('should do this thing', function() {
//test fooSvc
});
it('should do that thing', function() {
//test fooSvc
});
});
</pre>
That's better, but it's still annoying, especially if you have many services to inject.
To resolve this shadowing problem, the injector considers `_fooSvc_` argument names equal to
`fooSvc`, so the test can be rewritten like this:
<pre>
describe('fooSvc', function() {
var fooSvc;
beforeEach(inject(function(_fooSvc_) {
fooSvc = _fooSvc_;
}));
it('should do this thing', function() {
//test fooSvc
});
it('should do that thing', function() {
//test fooSvc
});
// more its
});
</pre>
## Related Topics
* {@link dev_guide.services Angular Services}
## Related API
* {@link api/angular.module.ng Services API}
@@ -1,53 +0,0 @@
@ngdoc overview
@name Developer Guide: DI: Using DI in Controllers
@description
The most common place to use dependency injection in angular applications is in {@link
dev_guide.mvc.understanding_controller controllers}. Here is a simple example:
<pre>
function MyController($route){
// configure the route service
$route.when(...);
}
MyController.$inject = ['$route'];
</pre>
In this example, the `MyController` constructor function takes one argument, the {@link
api/angular.module.ng.$route $route} service. Angular is then responsible for supplying the instance
of `$route` to the controller when the constructor is instantiated. There are two ways to cause
controller instantiation by configuring routes with the `$route` service, or by referencing the
controller from the HTML template, as follows:
<pre>
<!doctype html>
<html ng-controller="MyController" ng-app>
<script src="http://code.angularjs.org/angular.min.js"></script>
<body>
...
</body>
</html>
</pre>
When angular is instantiating your controller, it needs to know what services, if any, should be
injected (passed in as arguments) into the controller. Since there is no reflection in JavaScript,
we have to supply this information to angular in the form of an additional property on the
controller constructor function called `$inject`. Think of it as annotations for JavaScript.
<pre>
MyController.$inject = ['$route'];
</pre>
The information in `$inject` is then used by the {@link api/angular.injector injector} to call the
function with the correct arguments.
## Related Topics
* {@link dev_guide.di About Dependency Injection}
* {@link dev_guide.di.understanding_di Understanding Dependency Injection in Angular}
* {@link dev_guide.services Angular Services}
## Related API
* {@link api/angular.injector Angular Injector API}
+148 -18
View File
@@ -11,7 +11,7 @@ that will help you verify the health of your Angular application.
# Overview
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
**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
@@ -38,14 +38,14 @@ it('should filter results', function() {
});
</pre>
This scenario describes the requirements of a Buzz Client, specifically, that it should be able to
filter the stream of the user. It starts by entering a value in the 'user' input field, clicking
filter the stream of the user. It starts by entering a value in the input field with ng-model="user", clicking
the only button on the page, and then it verifies that there are 10 items listed. It then enters
'Bees' in the 'filterText' input field and verifies that the list is reduced to a single item.
'Bees' in the input field with ng-model='filterText' and verifies that the list is reduced to a single item.
The API section below lists the available commands and expectations for the Runner.
# API
Source: {@link https://github.com/angular/angular.js/blob/master/src/scenario/dsl.js}
Source: {@link https://github.com/angular/angular.js/blob/master/src/ngScenario/dsl.js}
## pause()
Pauses the execution of the tests until you call `resume()` in the console (or click the resume
@@ -78,26 +78,27 @@ Returns the window.location.search of the currently loaded page in the test fram
Returns the window.location.hash (without `#`) of the currently loaded page in the test frame.
## browser().location().url()
Returns the {@link api/angular.module.ng.$location $location.url()} of the currently loaded page in
Returns the {@link api/ng.$location $location.url()} of the currently loaded page in
the test frame.
## browser().location().path()
Returns the {@link api/angular.module.ng.$location $location.path()} of the currently loaded page in
Returns the {@link api/ng.$location $location.path()} of the currently loaded page in
the test frame.
## browser().location().search()
Returns the {@link api/angular.module.ng.$location $location.search()} of the currently loaded page
Returns the {@link api/ng.$location $location.search()} of the currently loaded page
in the test frame.
## browser().location().hash()
Returns the {@link api/angular.module.ng.$location $location.hash()} of the currently loaded page in
Returns the {@link api/ng.$location $location.hash()} of the currently loaded page in
the test frame.
## expect(future).{matcher}
Asserts the value of the given `future` satisfies the `matcher`. All API statements return a
`future` object, which get a `value` assigned after they are executed. Matchers are defined using
`angular.scenario.matcher`, and they use the value of futures to run the expectation. For example:
`expect(browser().location().href()).toEqual('http://www.google.com')`
`expect(browser().location().href()).toEqual('http://www.google.com')`. Available matchers
are presented further down this document.
## expect(future).not().{matcher}
Asserts the value of the given `future` satisfies the negation of the `matcher`.
@@ -109,20 +110,20 @@ Scopes the next DSL element selection.
Returns the value of the first binding matching the given `name`.
## input(name).enter(value)
Enters the given `value` in the text field with the given `name`.
Enters the given `value` in the text field with the corresponding ng-model `name`.
## input(name).check()
Checks/unchecks the checkbox with the given `name`.
Checks/unchecks the checkbox with the corresponding ng-model `name`.
## input(name).select(value)
Selects the given `value` in the radio button with the given `name`.
Selects the given `value` in the radio button with the corresponding ng-model `name`.
## input(name).val()
Returns the current value of an input field with the given `name`.
Returns the current value of an input field with the corresponding ng-model `name`.
## repeater(selector, label).count()
Returns the number of rows in the repeater matching the given jQuery `selector`. The `label` is
used for test ouput.
used for test output.
## repeater(selector, label).row(index)
Returns an array with the bindings in the row at the given `index` in the repeater matching the
@@ -133,10 +134,10 @@ Returns an array with the values in the column with the given `binding` in the r
the given jQuery `selector`. The `label` is used for test output.
## select(name).option(value)
Picks the option with the given `value` on the select with the given `name`.
Picks the option with the given `value` on the select with the given ng-model `name`.
## select(name).option(value1, value2...)
Picks the options with the given `values` on the multi select with the given `name`.
## select(name).options(value1, value2...)
Picks the options with the given `values` on the multi select with the given ng-model `name`.
## element(selector, label).count()
Returns the number of elements that match the given jQuery `selector`. The `label` is used for test
@@ -175,4 +176,133 @@ 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
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
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.
# Matchers
Matchers are used in combination with the `expect(...)` function as described above and can
be negated with `not()`. For instance: `expect(element('h1').text()).not().toEqual('Error')`.
Source: {@link https://github.com/angular/angular.js/blob/master/src/ngScenario/matchers.js}
<pre>
// value and Object comparison following the rules of angular.equals().
expect(value).toEqual(value)
// a simpler value comparison using ===
expect(value).toBe(value)
// checks that the value is defined by checking its type.
expect(value).toBeDefined()
// the following two matchers are using JavaScript's standard truthiness rules
expect(value).toBeTruthy()
expect(value).toBeFalsy()
// verify that the value matches the given regular expression. The regular
// expression may be passed in form of a string or a regular expression
// object.
expect(value).toMatch(expectedRegExp)
// a check for null using ===
expect(value).toBeNull()
// Array.indexOf(...) is used internally to check whether the element is
// contained within the array.
expect(value).toContain(expected)
// number comparison using < and >
expect(value).toBeLessThan(expected)
expect(value).toBeGreaterThan(expected)
</pre>
# Example
See the {@link https://github.com/angular/angular-seed angular-seed} project for more examples.
## Conditional actions with element(...).query(fn)
E2E testing with angular scenario is highly asynchronous and hides a lot of complexity by
queueing actions and expectations that can handle futures. From time to time, you might need
conditional assertions or element selection. Even though you should generally try to avoid this
(as it is can be sign for unstable tests), you can add conditional behavior with
`element(...).query(fn)`. The following code listing shows how this function can be used to delete
added entries (where an entry is some domain object) using the application's web interface.
Imagine the application to be structured into two views:
1. *Overview view* which lists all the added entries in a table and
2. a *detail view* which shows the entries' details and contains a delete button. When clicking the
delete button, the user is redirected back to the *overview page*.
<pre>
beforeEach(function () {
var deleteEntry = function () {
browser().navigateTo('/entries');
// we need to select the <tbody> element as it might be the case that there
// are no entries (and therefore no rows). When the selector does not
// result in a match, the test would be marked as a failure.
element('table tbody').query(function (tbody, done) {
// ngScenario gives us a jQuery lite wrapped element. We call the
// `children()` function to retrieve the table body's rows
var children = tbody.children();
if (children.length > 0) {
// if there is at least one entry in the table, click on the link to
// the entry's detail view
element('table tbody a').click();
// and, after a route change, click the delete button
element('.btn-danger').click();
}
// if there is more than one entry shown in the table, queue another
// delete action.
if (children.length > 1) {
deleteEntry();
}
// remember to call `done()` so that ngScenario can continue
// test execution.
done();
});
};
// start deleting entries
deleteEntry();
});
</pre>
In order to understand what is happening, we should emphasize that ngScenario calls are not
immediately executed, but queued (in ngScenario terms, we would be talking about adding
future actions). If we had only one entry in our table, then the following future actions
would be queued:
<pre>
// delete entry 1
browser().navigateTo('/entries');
element('table tbody').query(function (tbody, done) { ... });
element('table tbody a');
element('.btn-danger').click();
</pre>
For two entries, ngScenario would have to work on the following queue:
<pre>
// delete entry 1
browser().navigateTo('/entries');
element('table tbody').query(function (tbody, done) { ... });
element('table tbody a');
element('.btn-danger').click();
// delete entry 2
// indented to represent "recursion depth"
browser().navigateTo('/entries');
element('table tbody').query(function (tbody, done) { ... });
element('table tbody a');
element('.btn-danger').click();
</pre>
# Caveats
ngScenario does not work with apps that manually bootstrap using angular.bootstrap. You must use the ng-app directive.
@@ -1,245 +0,0 @@
@ngdoc overview
@name Developer Guide: Understanding Angular Expressions
@description
Expressions are {@link dev_guide.templates.databinding bindings} that you write in HTML and embed
in templates in order to create views in angular. Angular expressions are similar but not
equivalent to JavaScript expressions.
For example, these are all valid expressions in angular:
* `1+2={{1+2}}`
* `3*10|currency`
* `Hello {{name}}!`
* `Hello {{'World'}}!`
## Angular Expressions vs. JS Expressions
It might be tempting to think of angular view expressions as JavaScript expressions, but that is
not entirely correct. Angular does not use a simple JavaScript eval of the expression text. You can
think of angular expressions as JavaScript expressions with these differences:
* **Attribute Evaluation:** evaluation of all attributes are against the current scope, not to the
global window as in JavaScript.
* **Forgiving:** expression evaluation is forgiving to undefined and null, unlike in JavaScript.
* **No Control Flow Statements:** you cannot do the following from an angular expression:
conditionals, loops, or throw.
* **Type Augmentation:** the scope expression evaluator augments built-in types.
* **Filters:** you can add filters to an expression, for example to convert raw data into a
human-readable format.
* **The $:** angular reserves this prefix to differentiate its API names from others.
If, on the other hand, you do want to run arbitrary JavaScript code, you should make it a
controller method and call that. If you want to `eval()` an angular expression from JavaScript, use
the `Scope:$eval()` method.
## Example
<doc:example>
<doc:source>
1+2={{1+2}}
</doc:source>
<doc:scenario>
it('should calculate expression in binding', function() {
expect(binding('1+2')).toEqual('3');
});
</doc:scenario>
</doc:example>
You can try evaluating different expressions here:
<doc:example>
<doc:source>
<script>
function Cntl2($scope) {
$scope.exprs = [];
$scope.expr = '3*10|currency';
$scope.addExp = function(expr) {
this.exprs.push(expr);
};
$scope.removeExp = function(index) {
this.exprs.splice(index, 1);
};
}
</script>
<div ng-controller="Cntl2" class="expressions">
Expression:
<input type='text' ng-model="expr" size="80"/>
<button ng-click="addExp(expr)">Evaluate</button>
<ul>
<li ng-repeat="expr in exprs">
[ <a href="" ng-click="removeExp($index)">X</a> ]
<tt>{{expr}}</tt> => <span ng-bind="$parent.$eval(expr)"></span>
</li>
</ul>
</div>
</doc:source>
<doc:scenario>
it('should allow user expression testing', function() {
element('.expressions :button').click();
var li = using('.expressions ul').repeater('li');
expect(li.count()).toBe(1);
expect(li.row(0)).toEqual(["3*10|currency", "$30.00"]);
});
</doc:scenario>
</doc:example>
# Attribute Evaluation
Evaluation of all attributes takes place against the current scope. Unlike JavaScript, where names
default to global window properties, angular expressions have to use `$window` to refer to the
global object. For example, if you want to call `alert()`, which is defined on `window`, an
expression must use `$window.alert()`. This is done intentionally to prevent accidental access to
the global state (a common source of subtle bugs).
<doc:example>
<doc:source>
<script>
function Cntl1($window, $scope){
$scope.name = 'World';
$scope.greet = function() {
($window.mockWindow || $window).alert('Hello ' + this.name);
}
}
</script>
<div class="example2" ng-controller="Cntl1">
Name: <input ng-model="name" type="text"/>
<button ng-click="greet()">Greet</button>
</div>
</doc:source>
<doc:scenario>
it('should calculate expression in binding', function() {
var alertText;
this.addFutureAction('set mock', function($window, $document, done) {
$window.mockWindow = {
alert: function(text){ alertText = text; }
};
done();
});
element(':button:contains(Greet)').click();
expect(this.addFuture('alert text', function(done) {
done(null, alertText);
})).toBe('Hello World');
});
</doc:scenario>
</doc:example>
## Forgiving
Expression evaluation is forgiving to undefined and null. In JavaScript, evaluating `a.b.c` throws
an exception if `a` is not an object. While this makes sense for a general purpose language, the
expression evaluations are primarily used for data binding, which often look like this:
{{a.b.c}}
It makes more sense to show nothing than to throw an exception if `a` is undefined (perhaps we are
waiting for the server response, and it will become defined soon). If expression evaluation wasn't
forgiving we'd have to write bindings that clutter the code, for example: `{{((a||{}).b||{}).c}}`
Similarly, invoking a function `a.b.c()` on undefined or null simply returns undefined.
Assignments work the same way in reverse:
a.b.c = 10
...creates the intermediary objects even if a is undefined.
## No Control Flow Statements
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
conditional (including ternary operators), loop, or to throw from a view expression, delegate to a
JavaScript method instead.
## Type Augmentation
Built-in types have methods like `[].push()`, but the richness of these methods is limited.
Consider the example below, which allows you to do a simple search over a canned set of contacts.
The example would be much more complicated if we did not have the `Array:$filter()`. There is no
built-in method on `Array` called {@link api/angular.module.ng.$filter.filter $filter} and angular doesn't add
it to `Array.prototype` because that could collide with other JavaScript frameworks.
For this reason the scope expression evaluator augments the built-in types to make them act like
they have extra methods. The actual method for `$filter()` is `angular.module.ng.$filter.filter()`. You can
call it from JavaScript.
Extensions: You can further extend the expression vocabulary by adding new methods to
`angular.module.ng.$filter` or `angular.String`, etc.
<doc:example>
<doc:source>
<div ng-init="friends = [
{name:'John', phone:'555-1212'},
{name:'Mary', phone:'555-9876'},
{name:'Mike', phone:'555-4321'},
{name:'Adam', phone:'555-5678'},
{name:'Julie', phone:'555-8765'}]"></div>
Search: <input ng-model="searchText"/>
<table class="example3">
<thead>
<tr><th>Name</th><th>Phone</th><tr>
</thead>
<tbody>
<tr ng-repeat="friend in friends | filter:searchText">
<td>{{friend.name}}</td>
<td>{{friend.phone}}</td>
</tr>
</tbody>
</table>
</doc:source>
<doc:scenario>
it('should filter the list', function() {
var tr = using('table.example3 tbody').repeater('tr');
expect(tr.count()).toBe(5);
input('searchText').enter('a');
expect(tr.count()).toBe(2);
});
</doc:scenario>
</doc:example>
## Filters
When presenting data to the user, you might need to convert the data from its raw format to a
user-friendly format. For example, you might have a data object that needs to be formatted
according to the locale before displaying it to the user. You can pass expressions through a chain
of filters like this:
name | uppercase
The expression evaluator simply passes the value of name to angular.module.ng.$filter.uppercase.
Chain filters using this syntax:
value | filter1 | filter2
You can also pass colon-delimited arguments to filters, for example, to display the number 123 with
2 decimal points:
123 | number:2
# The $
You might be wondering, what is the significance of the $ prefix? It is simply a prefix that
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.
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
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
so that angular developers and developers who use angular can develop in harmony without collisions.
## Related Topics
* {@link dev_guide.templates.filters Understanding Angular Filters}
## Related API
* {@link api/angular.module.ng.$compile Angular Compiler API}
+3 -3
View File
@@ -3,16 +3,16 @@
@description
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
building client-side web applications.
The MVC pattern greatly summarized:
The MVC pattern summarized:
* Separate applications into distinct presentation, data, and logic components
* Encourage loose coupling between these components
Along with {@link dev_guide.services services} and {@link dev_guide.di dependency injection}, MVC
Along with {@link dev_guide.services services} and {@link di dependency injection}, MVC
makes angular applications better structured, easier to maintain and more testable.
The following topics explain how angular incorporates the MVC pattern into the angular way of
@@ -2,252 +2,339 @@
@name Developer Guide: About MVC in Angular: Understanding the Controller Component
@description
In angular, a controller is a JavaScript function(type/class) that is used to augment instances of
angular {@link dev_guide.scopes Scope}, excluding the root scope. When you or angular create a new
child scope object via the {@link api/angular.module.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
controller with the new scope and to augment its behavior.
# Understanding Controllers
Use controllers to:
In Angular, a Controller is a JavaScript **constructor function** that is used to augment the
{@link scope Angular Scope}.
- Set up the initial state of a scope object.
- Add behavior to the scope object.
When a Controller is attached to the DOM via the {@link api/ng.directive:ngController ng-controller}
directive, Angular will instantiate a new Controller object, using the specified Controller's
**constructor function**. A new **child scope** will be available as an injectable parameter to the
Controller's constructor function as `$scope`.
# Setting up the initial state of a scope object
Use Controllers to:
Typically, when you create an application you need to set up an initial state for an angular scope.
- Set up the initial state of the `$scope` object.
- Add behavior to the `$scope` object.
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
creates instances of the controller type (by invoking the `new` operator on the controller
constructor). Constructors are always applied to an existing scope object.
# Setting up the initial state of a `$scope` object
You set up the initial state of a scope by creating model properties. For example:
Typically, when you create an application you need to set up the initial state for the Angular
`$scope`. You set up the initial state of a scope by attaching properties to the `$scope` object.
The properties contain the **view model** (the model that will be presented by the view). All the
`$scope` properties will be available to the template at the point in the DOM where the Controller
is registered.
function GreetingCtrl($scope) {
$scope.greeting = 'Hola!';
}
The following example shows a very simple constructor function for a Controller, `GreetingCtrl`,
which attaches a `greeting` property containing the string `'Hola!'` to the `$scope`:
The `GreetingCtrl` controller creates a `greeting` model which can be referred to in a template.
<pre>
function GreetingCtrl($scope) {
$scope.greeting = 'Hola!';
}
</pre>
Once the Controller has been attached to the DOM, the `greeting` property can be data-bound to the
template:
<pre>
<div ng-controller="GreetingCtrl">
{{ greeting }}
</div>
</pre>
**NOTE**: Although Angular allows you to create Controller functions in the global scope, this is
not recommended. In a real application you should use the `.controller` method of your
{@link module Angular Module} for your application as follows:
<pre>
var myApp = angular.module('myApp',[]);
myApp.controller('GreetingCtrl', ['$scope', function($scope) {
$scope.greeting = 'Hola!';
}]);
</pre>
We have used an **inline injection annotation** to explicitly specify the dependency
of the Controller on the `$scope` service provided by Angular. See the guide on
{@link http://docs.angularjs.org/guide/di Dependency Injection} for more information.
When a controller function is applied to an angular scope object, the `this` of the controller
function becomes the scope of the angular scope object, so any assignment to `this` within the
controller function happens on the angular 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
template/view. This behavior interacts with and modifies the application model.
In order to react to events or execute computation in the view we must provide behavior to the
scope. We add behavior the scope by attaching methods to the `$scope` object. These methods are
then available to be called from the template/view.
The following example uses a Controller to add a method to the scope, which doubles a number:
<pre>
var myApp = angular.module('myApp',[]);
myApp.controller('DoubleCtrl', ['$scope', function($scope) {
$scope.double = function(value) { return value * 2; };
}]);
</pre>
Once the Controller has been attached to the DOM, the `double` method can be invoked in an Angular
expression in the template:
<pre>
<div ng-controller="DoubleCtrl">
Two times <input ng-model="num"> equals {{ double(num) }}
</div>
</pre>
As discussed in the {@link dev_guide.mvc.understanding_model Model} section of this guide, any
objects (or primitives) assigned to the scope become model properties. Any functions assigned to
the scope, along with any prototype methods of the controller type, become functions available in
the template/view, and can be invoked via angular expressions and `ng-` event handlers (e.g. {@link
api/angular.module.ng.$compileProvider.directive.ng-click ng-click}). These controller methods are always evaluated within the
context of the angular scope object that the controller function was applied to (which means that
the `this` keyword of any controller method is always bound to the scope that the controller
augments). This is how the second task of adding behavior to the scope is accomplished.
objects (or primitives) assigned to the scope become model properties. Any methods assigned to
the scope are available in the template/view, and can be invoked via angular expressions
and `ng` event handler directives (e.g. {@link api/ng.directive:ngClick ngClick}).
# Using Controllers Correctly
In general, a controller shouldn't try to do too much. It should contain only the business logic
In general, a Controller shouldn't try to do too much. It should contain only the business logic
needed for a single view.
The most common way to keep controllers slim is by encapsulating work that doesn't belong to
controllers into services and then using these services in controllers via dependency injection.
This is discussed in the {@link dev_guide.di Dependency Injection} {@link dev_guide.services
The most common way to keep Controllers slim is by encapsulating work that doesn't belong to
controllers into services and then using these services in Controllers via dependency injection.
This is discussed in the {@link di Dependency Injection} {@link dev_guide.services
Services} sections of this guide.
Do not use controllers for:
Do not use Controllers for:
- Any kind of DOM manipulation — Controllers should contain only business logic. DOM
manipulationthe presentation logic of an applicationis well known for being hard to test.
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
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
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
{@link api/angular.module.ng.$compileProvider.directive directives}.
- Input formatting — Use {@link dev_guide.forms angular form controls} instead.
{@link guide/directive directives}.
- Input formatting — Use {@link forms angular form controls} 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
- Sharing stateless or stateful code across Controllers — Use {@link dev_guide.services angular
services} instead.
- Instantiate or manage the life-cycle of other components (for example, to create service
instances).
- Managing the life-cycle of other components (for example, to create service instances).
# Associating Controllers with Angular Scope Objects
You can associate controllers with scope objects explicitly via the {@link api/angular.module.ng.$rootScope.Scope#$new
scope.$new} api or implicitly via the {@link api/angular.module.ng.$compileProvider.directive.ng-controller ng-controller
directive} or {@link api/angular.module.ng.$route $route service}.
You can associate controllers with scope objects implicitly via the {@link api/ng.directive:ngController ngController
directive} or {@link api/ng.$route $route service}.
## Controller Constructor and Methods Example
## Simple Spicy Controller Example
To illustrate how the controller component works in angular, let's create a little app with the
To illustrate further how Controller components work in Angular, let's create a little app with the
following components:
- A {@link dev_guide.templates template} with two buttons and a simple message
- A model consisting of a string named `spice`
- A controller with two functions that set the value of `spice`
- A Controller with two functions that set the value of `spice`
The message in our template contains a binding to the `spice` model, which by default is set to the
string "very". Depending on which button is clicked, the `spice` model is set to `chili` or
`jalapeño`, and the message is automatically updated by data-binding.
<doc:example module="spicyApp1">
<doc:source>
<div ng-app="spicyApp1" ng-controller="SpicyCtrl">
<button ng-click="chiliSpicy()">Chili</button>
<button ng-click="jalapenoSpicy()">Jalapeño</button>
<p>The food is {{spice}} spicy!</p>
</div>
<script>
var myApp = angular.module('spicyApp1', []);
## A Spicy Controller Example
<pre>
<body ng-controller="SpicyCtrl">
<button ng-click="chiliSpicy()">Chili</button>
<button ng-click="jalapenoSpicy()">Jalapeño</button>
<p>The food is {{spice}} spicy!</p>
</body>
function SpicyCtrl($scope) {
$scope.spice = 'very';
$scope.chiliSpicy = function() {
this.spice = 'chili';
}
}
SpicyCtrl.prototype.jalapenoSpicy = function() {
this.spice = 'jalapeño';
}
</pre>
myApp.controller('SpicyCtrl', ['$scope', function($scope){
$scope.spicy = 'very';
$scope.chiliSpicy = function() {
$scope.spice = 'chili';
};
$scope.jalapenoSpicy = function() {
$scope.spice = 'jalapeño';
};
}]);
</script>
</doc:source>
</doc:example>
Things to notice in the example above:
- The `ng-controller` directive is used to (implicitly) create a scope for our template, and the
scope is augmented (managed) by the `SpicyCtrl` controller.
scope is augmented (managed) by the `SpicyCtrl` Controller.
- `SpicyCtrl` is just a plain JavaScript function. As an (optional) naming convention the name
starts with capital letter and ends with "Ctrl" or "Controller".
- The JavaScript keyword `this` in the `SpicyCtrl` function is bound to the scope that the
controller augments.
- Assigning a property to `this` creates or updates the model.
- Controller methods can be created through direct assignment to scope (the `chiliSpicy` method) or
as prototype methods of the controller constructor function(the `jalapenoSpicy` method)
- Both controller methods are available in the template (for the `body` element and and its
children).
- Assigning a property to `$scope` creates or updates the model.
- Controller methods can be created through direct assignment to scope (see the `chiliSpicy` method)
- The Controller methods and properties are available in the template (for the `<div>` element and
and its children).
## Spicy Arguments Example
Controller methods can also take arguments, as demonstrated in the following variation of the
previous example.
## Controller Method Arguments Example
<doc:example module="spicyApp2">
<doc:source>
<div ng-app="spicyApp2" ng-controller="SpicyCtrl">
<input ng-model="customSpice">
<button ng-click="spicy('chili')">Chili</button>
<button ng-click="spicy(customSpice)">Custom spice</button>
<p>The food is {{spice}} spicy!</p>
</div>
<script>
var myApp = angular.module('spicyApp2', []);
<pre>
<body ng-controller="SpicyCtrl">
<input ng-model="customSpice" value="wasabi">
<button ng-click="spicy('chili')">Chili</button>
<button ng-click="spicy(customSpice)">Custom spice</button>
<p>The food is {{spice}} spicy!</p>
</body>
myApp.controller('SpicyCtrl', ['$scope', function($scope){
$scope.customSpice = "wasabi";
$scope.spice = 'very';
$scope.spicy = function(spice){
$scope.spice = spice;
};
}]);
</script>
</doc:source>
</doc:example>
function SpicyCtrl($scope) {
$scope.spice = 'very';
$scope.spicy = function(spice) {
this.spice = spice;
}
}
</pre>
Notice that the `SpicyCtrl` controller now defines just one method called `spicy`, which takes one
argument called `spice`. The template then refers to this controller method and passes in a string
Notice that the `SpicyCtrl` Controller now defines just one method called `spicy`, which takes one
argument called `spice`. The template then refers to this Controller method and passes in a string
constant `'chili'` in the binding for the first button and a model property `spice` (bound to an
input box) in the second button.
## Scope Inheritance Example
## Controller Inheritance Example
It is common to attach Controllers at different levels of the DOM hierarchy. Since the
{@link api/ng.directive:ngController ng-controller} directive creates a new child scope, we get a
hierarchy of scopes that inherit from each other. The `$scope` that each Controller receives will
have access to properties and methods defined by Controllers higher up the hierarchy.
See {@link https://github.com/angular/angular.js/wiki/Understanding-Scopes Understanding Scopes} for
more information about scope inheritance.
Controller inheritance in angular is based on {@link api/angular.module.ng.$rootScope.Scope Scope} inheritance. Let's
have a look at an example:
<doc:example module="scopeInheritance">
<doc:source>
<div ng-app="scopeInheritance" class="spicy">
<div ng-controller="MainCtrl">
<p>Good {{timeOfDay}}, {{name}}!</p>
<pre>
<body ng-controller="MainCtrl">
<p>Good {{timeOfDay}}, {{name}}!</p>
<div ng-controller="ChildCtrl">
<p>Good {{timeOfDay}}, {{name}}!</p>
<p ng-controller="BabyCtrl">Good {{timeOfDay}}, {{name}}!</p>
</body>
<div ng-controller="ChildCtrl">
<p>Good {{timeOfDay}}, {{name}}!</p>
function MainCtrl($scope) {
$scope.timeOfDay = 'morning';
$scope.name = 'Nikki';
}
<div ng-controller="BabyCtrl">
<p>Good {{timeOfDay}}, {{name}}!</p>
</div>
</div>
</div>
</div>
<style>
div.spicy div {
padding: 10px;
border: solid 2px blue;
}
</style>
<script>
var myApp = angular.module('scopeInheritance', []);
myApp.controller('MainCtrl', ['$scope', function($scope){
$scope.timeOfDay = 'morning';
$scope.name = 'Nikki';
}]);
myApp.controller('ChildCtrl', ['$scope', function($scope){
$scope.name = 'Mattie';
}]);
myApp.controller('BabyCtrl', ['$scope', function($scope){
$scope.timeOfDay = 'evening';
$scope.name = 'Gingerbreak Baby';
}]);
</script>
</doc:source>
</doc:example>
function ChildCtrl($scope) {
$scope.name = 'Mattie';
}
function BabyCtrl($scope) {
$scope.timeOfDay = 'evening';
$scope.name = 'Gingerbreak Baby';
}
</pre>
Notice how we nested three `ng-controller` directives in our template. This template construct will
result in 4 scopes being created for our view:
Notice how we nested three `ng-controller` directives in our template. This will result in four
scopes being created for our view:
- The root scope
- The `MainCtrl` scope, which contains `timeOfDay` and `name` models
- The `ChildCtrl` scope, which shadows the `name` model from the previous scope and inherits the
`timeOfDay` model
- The `BabyCtrl` scope, which shadows both the `timeOfDay` model defined in `MainCtrl` and `name`
model defined in the ChildCtrl
- The `MainCtrl` scope, which contains `timeOfDay` and `name` properties
- The `ChildCtrl` scope, which inherits the `timeOfDay` property but overrides (hides) the `name`
property from the previous
- The `BabyCtrl` scope, which overrides (hides) both the `timeOfDay` property defined in `MainCtrl`
and the `name` property defined in `ChildCtrl`
Inheritance works between controllers in the same way as it does with models. So in our previous
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,
because as we mentioned earlier, controllers are not instantiated directly by angular, but rather
are applied to the scope object.
Inheritance works with methods in the same way as it does with properties. So in our previous
examples, all of the properties could be replaced with methods that return string values.
## Testing Controllers
The way to test a controller depends upon how complicated the controller is.
Although there are many ways to test a Controller, one of the best conventions, shown below,
involves injecting the {@link api/ng.$rootScope $rootScope} and {@link api/ng.$controller $controller}:
- If your controller doesn't use DI or scope methods — create the controller with the `new`
operator and test away. For example:
Controller Function:
**Controller Definition:**
<pre>
function myController() {
this.spices = [{"name":"pasilla", "spiciness":"mild"},
{"name":"jalapeno", "spiceiness":"hot hot hot!"},
{"name":"habanero", "spiceness":"LAVA HOT!!"}];
var myApp = angular.module('myApp',[]);
this.spice = "habanero";
}
myApp.controller('MyController', function($scope) {
$scope.spices = [{"name":"pasilla", "spiciness":"mild"},
{"name":"jalapeno", "spiceiness":"hot hot hot!"},
{"name":"habanero", "spiceness":"LAVA HOT!!"}];
$scope.spice = "habanero";
});
</pre>
Controller Test:
**Controller Test:**
<pre>
describe('myController function', function() {
describe('myController', function() {
var ctrl;
var $scope;
beforeEach(function() {
ctrl = new myController();
});
beforeEach(module('myApp'));
beforeEach(inject(function($rootScope, $controller) {
$scope = $rootScope.$new();
$controller('MyController', {$scope: $scope});
}));
it('should create "spices" model with 3 spices', function() {
expect(ctrl.spices.length).toBe(3);
expect($scope.spices.length).toBe(3);
});
it('should set the default value of spice', function() {
expect(ctrl.spice).toBe('habanero');
expect($scope.spice).toBe('habanero');
});
});
});
</pre>
- If your controller does use DI or scope methods — create a root scope, then create the controller
in the root scope with `scope.$new(MyController)`. Test the controller using `$eval`, if necessary.
- If you need to test a nested controller that depends on its parent's state — create a root scope,
create a parent scope, create a child scope, and test the controller using $eval if necessary.
If you need to test a nested Controller you need to create the same scope hierarchy
in your test that exists in the DOM:
<pre>
describe('state', function() {
var mainScope, childScope, babyScope;
beforeEach(module('myApp'));
beforeEach(inject(function($rootScope, $controller) {
mainScope = $rootScope.$new();
$controller('MainCtrl', {$scope: mainScope});
childScope = mainScope.$new();
$controller('ChildCtrl', {$scope: childScope});
babyScope = childScope.$new();
$controller('BabyCtrl', {$scope: babyScope});
}));
it('should have over and selected', function() {
expect(mainScope.timeOfDay).toBe('morning');
expect(mainScope.name).toBe('Nikki');
expect(childScope.timeOfDay).toBe('morning');
expect(childScope.name).toBe('Mattie');
expect(babyScope.timeOfDay).toBe('evening');
expect(babyScope.name).toBe('Gingerbreak Baby');
});
});
</pre>
## Related Topics
@@ -2,16 +2,16 @@
@name Developer Guide: About MVC in Angular: Understanding the Model Component
@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
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
dev_guide.scopes Scope} object. The name of the property is the model identifier and the value is
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
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
referenced by an angular scope as a property of that scope object. This property reference can 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
created explicitly or implicitly.
You can create models by explicitly creating scope properties referencing JavaScript objects in the
@@ -26,11 +26,11 @@ occurs in controllers:
$scope.foo = 'bar';
}
* Use an {@link dev_guide.expressions angular expression} with an assignment operator in templates:
* Use an {@link expression angular expression} with an assignment operator in templates:
<button ng-click="{{foos='ball'}}">Click me</button>
<button ng-click="{{foo='bar'}}">Click me</button>
* Use {@link api/angular.module.ng.$compileProvider.directive.ng-init ng-init directive} in templates (for toy/example apps
* Use {@link api/ng.directive:ngInit ngInit directive} in templates (for toy/example apps
only, not recommended for real applications):
<body ng-init=" foo = 'bar' ">
@@ -45,18 +45,18 @@ when processing the following template constructs:
The code above creates a model called "query" on the current scope with the value set to "fluffy
cloud".
* An iterator declaration in {@link api/angular.module.ng.$compileProvider.directive.ng-repeat ng-repeater}:
* An iterator declaration in {@link api/ng.directive:ngRepeat ngRepeater}:
<p ng-repeat="phone in phones"></p>
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.
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.
The following illustration shows a simple data model created implicitly from a simple template:
@@ -2,15 +2,15 @@
@name Developer Guide: About MVC in Angular: Understanding the View Component
@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.
<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
controller through angular directives, such as {@link api/angular.module.ng.$compileProvider.directive.ng-controller
ng-controller} and {@link api/angular.module.ng.$compileProvider.directive.ng-view ng-view}, and through bindings of this form:
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:
`{{someControllerFunction()}}`. In these ways, the view can call functions in an associated
controller function.
-236
View File
@@ -1,236 +0,0 @@
@ngdoc overview
@name Developer Guide: Overview
@description
# 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 depends on where you're coming from...
* If you're a web designer, you might perceive angular to be a sweet {@link dev_guide.templates
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
dev_guide.compiler compiler} that runs in your browser. The angular compiler teaches your browser
new tricks.
Angular is not just a templating system, but you can create fantastic templates with it. Angular is
not just a web framework, but it features a very nice framework. Angular is not just an extensible
HTML compiler, but the compiler is at the core of Angular. Angular includes all of these
components, along with others. Angular is far greater than the sum of its parts. It is a new,
better way to develop web applications!
## An Introductory Angular 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 manipulating the DOM, writing listeners and
input validators, all just to implement a simple form? No. You either don't want to go there in
the first place or you've been there and the thrill is gone.
So look over the following simple example written using angular. Note that it features only the
templating aspect of angular, but this should suffice for now to quickly demonstrate how much
easier a web developer's life can if they're using angular:
<doc:example>
<doc:source>
<script>
function InvoiceCntl($scope) {
$scope.qty = 1;
$scope.cost = 19.95;
}
</script>
<div ng-controller="InvoiceCntl">
<b>Invoice:</b>
<br />
<br />
<table>
<tr><td> </td><td> </td>
<tr><td>Quantity</td><td>Cost</td></tr>
<tr>
<td><input type="integer" min="0" ng-model="qty" required ></td>
<td><input type="number" ng-model="cost" required ></td>
</tr>
</table>
<hr />
<b>Total:</b> {{qty * cost | currency}}
</div>
</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>
Try out the Live Preview above, and then let's walk through the example and describe what's going
on.
In the `<html>` tag we specify that this is an angular application with the `ng-app` directive.
The `ng-app' will cause the angular to {@link dev_guide.bootstrap auto initialize} your application.
<html ng-app>
We load the angular using the `<script>` tag:
<script src="http://code.angularjs.org/angular-?.?.?.min.js"></script>
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:
Quantity: <input type="integer" min="0" ng-model="qty" required >
Cost: <input type="number" ng-model="cost" required >
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
variables of the same name. Think of those variables as the "Model" component of the
Model-View-Controller design pattern.
* Note the angular/HTML widget, {@link api/angular.module.ng.$compileProvider.directive.input input}.
You may have noticed that when you enter invalid data
or leave the the input fields blank, the borders turn red color, and the display value disappears.
These widgets make it easier to implement field validation than coding them in JavaScript,
no? Yes.
And finally, the mysterious `{{ double curly braces }}`:
Total: {{qty * cost | currency}}
This notation, `{{ _expression_ }}`, is a bit of built-in angular binding markup, a shortcut for
displaying data to the user. The expression within curly braces is monitored and its evaluated value
is updated into the view by angular's template compiler. Alternatively, one could use angular's
{@link api/angular.module.ng.$compileProvider.directive.ng-bind ng-bind}) directive. The expression
itself can be a combination of both an expression and a {@link dev_guide.templates.filters filter}:
`{{ expression | filter }}`. Angular provides filters for formatting display data.
In the example above, the expression in double-curly braces directs angular to, "Bind the data we
got from the input widgets to the display, multiply them together, and format the resulting number
into output that looks like money."
# The Angular Philosophy
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 excellent for
expressing business logic.
Not to put too fine a point on it, but 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:
<pre>
<span class="label">Hello</span>
</pre>
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();
label.setText('Hello');
label.setClass('label');
parent.addChild(label);
</pre>
That's one line of markup versus four times as much code.
## More Angular Philosophy
* 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.
Now that we're homing in on what angular is, perhaps now would be a good time to list a few things
that angular is not:
* 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 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.
# 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.
* **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, 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.
# 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>
</object>
{@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}
@@ -1,230 +0,0 @@
@ngdoc overview
@name Developer Guide: Scopes: Scope Internals
@description
## What is a scope?
A scope is an execution context for {@link dev_guide.expressions expressions}. You can think of a
scope as a JavaScript object that has an extra set of APIs for registering change listeners and for
managing its own life cycle. In Angular's implementation of the model-view-controller design
pattern, a scope's properties comprise both the model and the controller methods.
### Scope characteristics
- Scopes provide APIs ({@link api/angular.module.ng.$rootScope.Scope#$watch $watch}) to observe model mutations.
- Scopes provide APIs ({@link api/angular.module.ng.$rootScope.Scope#$apply $apply}) to propagate any model changes
through the system into the view from outside of the "Angular realm" (controllers, services,
Angular event handlers).
- Scopes can be nested to isolate application components while providing access to shared model
properties. A scope (prototypically) inherits properties from its parent scope.
- In some parts of the system (such as controllers, services and directives), the scope is made
available as `this` within the given context. (Note: This api will change before 1.0 is released.)
### Root scope
Every application has a root scope, which is the ancestor of all other scopes.
### What is scope used for?
{@link dev_guide.expressions Expressions} in the view are {@link api/angular.module.ng.$rootScope.Scope#$eval evaluated}
against the current scope. When HTML DOM elements are attached to a scope, expressions in those
elements are evaluated against the attached scope.
There are two kinds of expressions:
- Binding expressions, which are observations of property changes. Property changes are reflected
in the view during the {@link api/angular.module.ng.$rootScope.Scope#$digest digest cycle}.
- Action expressions, which are expressions with side effects. Typically, the side effects cause
execution of a method in a controller in response to a user action, such as clicking on a button.
### Scope inheritance
A scope (prototypically) inherits properties from its parent scope. Since a given property may not
reside on a child scope, if a property read does not find the property on a scope, the read will
recursively check the parent scope, grandparent scope, etc. all the way to the root scope before
defaulting to undefined.
{@link api/angular.module.ng.$compileProvider.directive directives} associated with elements
(ng-controller, ng-repeat, ng-include, etc.) create new child scopes that inherit properties from
the current parent scope. Any code in Angular is free to create a new scope. Whether or not your
code does so is an implementation detail of the directive, that is, you can decide when or if this
happens. Inheritance typically mimics HTML DOM element nesting, but does not do so with the same
granularity.
A property write will always write to the current scope. This means that a write can hide a parent
property within the scope it writes to, as shown in the following example.
<pre>
it('should inherit properties', inject(function($rootScope)) {
var root = $rootScope;
var child = root.$new();
root.name = 'angular';
expect(child.name).toEqual('angular');
expect(root.name).toEqual('angular');
child.name = 'super-heroic framework';
expect(child.name).toEqual('super-heroic framework');
expect(root.name).toEqual('angular');
});
</pre>
### Scope life cycle
1. **Creation**
* The root scope is created by the {@link api/angular.module.ng.$rootScope $rootScope} service.
* To create a child scopes, you should call {@link api/angular.module.ng.$rootScope.Scope#$new parentScope.$new()}.
2. **Watcher registration**
Watcher registration can happen at any time and on any scope (root or child) via {@link
api/angular.module.ng.$rootScope.Scope#$watch scope.$watch()} API.
3. **Model mutation**
For mutations to be properly observed, you should make them only within the execution of the
function passed into {@link api/angular.module.ng.$rootScope.Scope#$apply scope.$apply()} call. (Angular apis do this
implicitly, so no extra `$apply` call is needed when doing synchronous work in controllers, or
asynchronous work with {@link api/angular.module.ng.$http $http} or {@link api/angular.module.ng.$defer
$defer} services.
4. **Mutation observation**
At the end of each `$apply` call {@link api/angular.module.ng.$rootScope.Scope#$digest $digest} cycle is started on
the root scope, which then propagates throughout all child scopes.
During the `$digest` cycle, all `$watch-ers` expressions or functions are checked for model
mutation and if a mutation is detected, the `$watch-er` listener is called.
5. **Scope destruction**
When child scopes are no longer needed, it is the responsibility of the child scope creator to
destroy them via {@link api/angular.module.ng.$rootScope.Scope#$destroy scope.$destroy()} API. This will stop
propagation of `$digest` calls into the child scope and allow for memory used by the child scope
models to be reclaimed by the garbage collector.
The root scope can't be destroyed via the `$destroy` API. Instead, it is enough to remove all
references from your application to the scope object and garbage collector will do its magic.
## Scopes in Angular applications
To understand how Angular applications work, you need to understand how scopes work within an
application. This section describes the typical life cycle of an application so you can see how
scopes come into play throughout and get a sense of their interactions.
### How scopes interact in applications
1. At application compile time, a root scope is created and is attached to the root `<HTML>` DOM
element.
2. During the compilation phase, the {@link dev_guide.compiler compiler} matches {@link
api/angular.module.ng.$compileProvider.directive directives} against the DOM template. The directives
usually fall into one of two categories:
- Observing {@link api/angular.module.ng.$compileProvider.directive directives}, such as double-curly
expressions `{{expression}}`, register listeners using the {@link
api/angular.module.ng.$rootScope.Scope#$watch $watch()} method. This type of directive needs to
be notified whenever the expression changes so that it can update the view.
- Listener directives, such as {@link api/angular.module.ng.$compileProvider.directive.ng-click
ng-click}, register a listener with the DOM. When the DOM listener fires, the directive executes
the associated expression and updates the view using the {@link
api/angular.module.ng.$rootScope.Scope#$apply $apply()} method.
3. When an external event (such as a user action, timer or XHR) is received, the associated {@link
dev_guide.expressions expression} must be applied to the scope through the {@link
api/angular.module.ng.$rootScope.Scope#$apply $apply()} method so that all listeners are updated correctly.
### Directives that create scopes
In most cases, {@link api/angular.module.ng.$compileProvider.directive directives} and scopes interact but do not create new
instances of scope. However, some directives, such as {@link api/angular.module.ng.$compileProvider.directive.ng-controller
ng-controller} and {@link api/angular.module.ng.$compileProvider.directive.ng-repeat ng-repeat}, create new child scopes using
the {@link api/angular.module.ng.$rootScope.Scope#$new $new()} method and then attach the child scope to the
corresponding DOM element. You can retrieve a scope for any DOM element by using an
`angular.element(aDomElement).scope()` method call.)
### Controllers and scopes
Scopes and controllers interact with each other in the following situations:
- Controllers use scopes to expose controller methods to templates (see {@link
api/angular.module.ng.$compileProvider.directive.ng-controller ng-controller}).
- Controllers define methods (behavior) that can mutate the model (properties on the scope).
- Controllers may register {@link api/angular.module.ng.$rootScope.Scope#$watch watches} on the model. These watches
execute immediately after the controller behavior executes, but before the DOM gets updated.
See the {@link dev_guide.mvc.understanding_controller controller docs} for more information.
### Updating scope properties
You can update a scope by calling its {@link api/angular.module.ng.$rootScope.Scope#$apply $apply()} method with an
expression or a function as the function argument. However it is typically not necessary to do this
explicitly. In most cases, angular intercepts all external events (such as user interactions, XHRs,
and timers) and wraps their callbacks into the `$apply()` method call on the scope object for you
at the right time. The only time you might need to call `$apply()` explicitly is when you create
your own custom asynchronous widget or service.
The reason it is unnecessary to call `$apply()` from within your controller functions when you use
built-in angular widgets and services is because your controllers are typically called from within
an `$apply()` call already.
When a user inputs data, angularized widgets invoke `$apply()` on the current scope and evaluate an
angular expression or execute a function on this scope. Afterwards `$apply` will trigger `$digest`
call on the root scope, to propagate your changes through the entire system, which results in
$watch-ers firing and view getting updated. Similarly, when a request to fetch data from a server
is made and the response comes back, the data is written into the model (scope) within an $apply,
which then pushes updates through to the view and any other dependents.
A widget that creates scopes (such as {@link api/angular.module.ng.$compileProvider.directive.ng-repeat ng-repeat}) via `$new`,
doesn't need to worry about propagating the `$digest` call from the parent scope to child scopes.
This happens automatically.
## Scopes in unit-testing
You can create scopes, including the root scope, in tests by having the $rootScope injected into
your spec. This allows you to mimic the run-time environment and have full control over
the life cycle of the scope so that you can assert correct model transitions. Since these scopes
are created outside the normal compilation process, their life cycles must be managed by the test.
### Using scopes in unit-testing
The following example demonstrates how the scope life cycle needs to be manually triggered from
within the unit-tests.
<pre>
// example of a test
it('should trigger a watcher', inject(function($rootScope) {
var scope = $rootScope;
scope.$watch('name', function(name) {
scope.greeting = 'Hello ' + name + '!';
});
scope.name = 'angular';
// The watch does not fire yet since we have to manually trigger the digest phase.
expect(scope.greeting).toEqual(undefined);
// manually trigger digest phase from the test
scope.$digest();
expect(scope.greeting).toEqual('Hello Angular!');
}
</pre>
### Dependency injection in Tests
When you find it necessary to inject your own mocks in your tests, use a scope to override the
service instances, as shown in the following example.
<pre>
it('should allow override of providers', inject(
function($provide) {
$provide.value('$location', {mode:'I am a mock'});
},
function($location){
expect($location.mode).toBe('I am a mock');
}
)};
</pre>
## Related Topics
* {@link dev_guide.scopes Angular Scope Objects}
* {@link dev_guide.scopes.understanding_scopes Understanding Scopes}
## Related API
* {@link api/angular.module.ng.$rootScope.Scope Angular Scope API}
-35
View File
@@ -1,35 +0,0 @@
@ngdoc overview
@name Developer Guide: Scopes
@description
An Angular scope is a JavaScript object with additional APIs useful for watching property changes,
Angular scope is the model in Model-View-Controller paradigm. Instances of scope serve as the
context within which all {@link dev_guide.expressions expressions} get evaluated.
You can think of Angular scope objects as the medium through which the model, view, and controller
communicate. Scopes are linked during the compilation process with the view. This linkage provides
the contexts in which Angular creates data-bindings between the model and the view.
In addition to providing the context in which data is evaluated, Angular scope objects watch for
model changes. The scope objects also notify all components interested in any model changes (for
example, functions registered through {@link api/angular.module.ng.$rootScope.Scope#$watch $watch}, bindings created by
{@link api/angular.module.ng.$compileProvider.directive.ng-bind ng-bind}, or HTML input elements).
Angular scope objects:
* Link the model, controller and view template together.
* Provide the mechanism to watch for model changes ({@link api/angular.module.ng.$rootScope.Scope#$watch $watch}).
* Apply model changes to the system ({@link api/angular.module.ng.$rootScope.Scope#$apply $apply}).
* Provide the context in which expressions are evaluated ({@link api/angular.module.ng.$rootScope.Scope#$eval $eval}).
## Related Topics
* {@link dev_guide.scopes.understanding_scopes Understanding Scopes}
* {@link dev_guide.scopes.internals Scopes Internals}
## Related API
* {@link api/angular.module.ng.$rootScope.Scope Angular Scope API}
@@ -1,66 +0,0 @@
@ngdoc overview
@name Developer Guide: Scopes: Understanding Scopes
@description
Angular automatically creates a root scope during initialization, and attaches it to the page's
root DOM element (usually `<html>`). The root scope object, along with any of its child scope
objects, serves as the infrastructure on which your data model is built. The data model (JavaScript
objects, arrays, or primitives) is attached to angular scope properties. Angular binds the property
values to the DOM where bindings are specified in the template. Angular attaches any controller
functions you have created to their respective scope objects.
<img src="img/guide/simple_scope_final.png">
Angular scopes can be nested, so a child scope has a parent scope upstream in the DOM. When you
display an angular expression in the view, angular walks the DOM tree looking in the closest
attached scope object for the specified data. If it doesn't find the data in the closest attached
scope, it looks further up the scope hierarchy until it finds the data.
A child scope object inherits properties from its parents. For example, in the following snippet of
code, observe how the value of `name` changes, based on the HTML element it is displayed in:
<doc:example>
<doc:source>
<ul ng-init="name='Hank'; names=['Igor', 'Misko', 'Gail', 'Kai']">
<li ng-repeat="name in names">
Name = {{name}}!
</li>
</ul>
<pre>Name={{name}}</pre>
</doc:source>
<doc:scenario>
it('should override the name property', function() {
expect(using('.doc-example-live').repeater('li').row(0)).
toEqual(['Igor']);
expect(using('.doc-example-live').repeater('li').row(1)).
toEqual(['Misko']);
expect(using('.doc-example-live').repeater('li').row(2)).
toEqual(['Gail']);
expect(using('.doc-example-live').repeater('li').row(3)).
toEqual(['Kai']);
expect(using('.doc-example-live').element('pre').text()).
toBe('Name=Hank');
});
</doc:scenario>
</doc:example>
The angular {@link api/angular.module.ng.$compileProvider.directive.ng-repeat ng-repeat} directive creates a new scope for each
element that it repeats (in this example the elements are list items). In the `<ul>` element, we
initialized `name` to "Hank", and we created an array called `names` to use as the data source for
the list items. In each `<li>` element, `name` is overridden. Outside of the `<li>` repeater, the
original value of `name` is displayed.
The following illustration shows the DOM and angular scopes for the example above:
<img src="img/guide/dom_scope_final.png">
## Related Topics
* {@link dev_guide.scopes Angular Scope Objects}
* {@link dev_guide.scopes.internals Scopes Internals}
## Related API
* {@link api/angular.module.ng.$rootScope.Scope Angular Scope API}
@@ -14,22 +14,22 @@ changes to $location are reflected into the browser address bar.
- Exposes the current URL in the browser address bar, so you can
- Watch and observe the URL.
- Change the URL.
- Synchronizes the URL with the browser when the user
- Changes the address bar.
- Clicks the back or forward button (or clicks a History link).
- Clicks on a link.
- Maintains synchronization between itself and the browser's URL when the user
- Changes the address in the browser's address bar.
- Clicks the back or forward button in the browser (or clicks a History link).
- Clicks on a link in the page.
- Represents the URL object as a set of methods (protocol, host, port, path, search, hash).
## Comparing $location to window.location
<table>
<table class="table">
<thead>
<tr>
<td class="empty-corner-lt"></td>
<td>window.location</td>
<td>$location service</td>
<th class="empty-corner-lt"></th>
<th>window.location</th>
<th>$location service</th>
</tr>
</thead>
@@ -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.
## 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`.
# General overview of the API
The `$location` service can behave differently, depending on the configuration that was provided to
@@ -89,7 +88,7 @@ setter methods that allow you to get or change the current URL in the browser.
## $location service configuration
To configure the `$location` service, retrieve the
{@link api/angular.module.ng.$locationProvider $locationProvider} and set the parameters as follows:
{@link api/ng.$locationProvider $locationProvider} and set the parameters as follows:
- **html5Mode(mode)**: {boolean}<br />
@@ -99,7 +98,7 @@ To configure the `$location` service, retrieve the
- **hashPrefix(prefix)**: {string}<br />
prefix used for Hashbang URLs (used in Hashbang mode or in legacy browser in Html5 mode)<br />
default: `'!'`
default: `""`
### Example configuration
<pre>
@@ -122,6 +121,8 @@ All of the setter methods return the same `$location` object to allow chaining.
change multiple segments in one go, chain setters like this:
<pre>$location.path('/newValue').search({key: value});</pre>
## Replace method
There is a special `replace` method which can be used to tell the $location service that the next
time the $location service is synced with the browser, the last history record should be replaced
instead of creating a new one. This is useful when you want to implement redirection, which would
@@ -133,12 +134,12 @@ current URL without creating a new browser history record you can call:
// or you can chain these as: $location.path('/someNewPath').replace();
</pre>
Note that the setters don't update `window.location` immediately. Instead, `$location` service is
aware of the {@link api/angular.module.ng.$rootScope.Scope scope} life-cycle and coalesces multiple `$location`
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`
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
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,
unless `replace()` is called again.
@@ -165,13 +166,13 @@ facilitate the browser URL change and history management.
<img src="img/guide/hashbang_vs_regular_url.jpg">
<table>
<table class="table">
<thead>
<tr>
<td class="empty-corner-lt"></td>
<td>Hashbang mode</td>
<td>HTML5 mode</td>
<th class="empty-corner-lt"></th>
<th>Hashbang mode</th>
<th>HTML5 mode</th>
</tr>
</thead>
@@ -212,8 +213,8 @@ In this mode, `$location` uses Hashbang URLs in all browsers.
<pre>
it('should show example', inject(
function($locationProvider) {
$locationProvider.html5mode = false;
$locationProvider.hashPrefix = '!';
$locationProvider.html5Mode(false);
$locationProvider.hashPrefix('!');
},
function($location) {
// open http://host.com/base/index.html#!/a
@@ -261,8 +262,8 @@ having to worry about whether the browser displaying your app supports the histo
<pre>
it('should show example', inject(
function($locationProvider) {
$locationProvider.html5mode = true;
$locationProvider.hashPrefix = '!';
$locationProvider.html5Mode(true);
$locationProvider.hashPrefix('!');
},
function($location) {
// in browser with HTML5 history support:
@@ -304,8 +305,8 @@ history API or not; the `$location` service makes this transparent to you.
### Html link rewriting
When you use the history API mode, you will need different links in different browser, but all you
have to do is specify regular URL links, such as: `&lt;a href="/some?foo=bar"&gt;link&lt;/a&gt;`
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>`
When a user clicks on this link,
@@ -316,12 +317,21 @@ When a user clicks on this link,
In cases like the following, links are not rewritten; instead, the browser will perform a full page
reload to the original link.
- Links with an `ng-ext-link` directive<br />
Example: `<a href="/ext/link?a=b" ng-ext-link>link</a>`
- Links that contain `target="_blank"`<br />
Example: `<a href="/ext/link?a=b" target="_blank">link</a>`
- Absolute links that go to a different domain<br />
- Links that contain `target` element<br>
Example: `<a href="/ext/link?a=b" target="_self">link</a>`
- Absolute links that go to a different domain<br>
Example: `<a href="http://angularjs.org/">link</a>`
- Links starting with '/' that lead to a different base path when base is defined<br>
Example: `<a href="/not-my-base/link">link</a>`
When running Angular in the root of a domain, along side perhaps a normal application in the same
directory, the "otherwise" route handler will try to handle all the URLs, including ones that map
to static files.
To prevent this, you can set your base href for the app to `<base href=".">` and then prefix links
to URLs that should be handled with `.`. Now, links to locations, which are not to be routed by Angular,
are not prefixed with `.` and will not be intercepted by the `otherwise` rule in your `$routeProvider`.
### Server side
@@ -330,22 +340,24 @@ to entry point of your application (e.g. index.html)
### Crawling your app
If you want your AJAX application to be indexed by web crawlers, you rill need to add the following
If you want your AJAX application to be indexed by web crawlers, you will need to add the following
meta tag to the HEAD section of your document:
<pre><meta name="fragment" content="!" /></pre>
This statement causes a crawler to request links with empty `_escaped_fragment_` parameter so that
This statement causes a crawler to request links with an empty `_escaped_fragment_` parameter so that
your server can recognize the crawler and serve it HTML snapshots. For more information about this
technique, see {@link http://code.google.com/web/ajaxcrawling/docs/specification.html Making AJAX
Applications Crawlable}.
### Relative links
Be sure to check all relative links, images, scripts etc. You must use an absolute path because the
path is going to be rewritten. You can use `<base href="" />` tag as well.
Be sure to check all relative links, images, scripts etc. You must either specify the url base in
the head of your main html file (`<base href="/my-base">`) or you must use absolute urls
(starting with `/`) everywhere because relative urls will be resolved to absolute urls using the
initial absolute url of the document, which is often different from the root of the application.
Running Angular apps with the History API enabled from document root is strongly encouraged as it
takes care of all relative link issues. **Otherwise you have to specify &lt;base href="" /&gt; !**
takes care of all relative link issues.
### Sending links among different browsers
@@ -372,34 +384,34 @@ In this examples we use `<base href="/base/index.html" />`
<div ng-non-bindable class="html5-hashbang-example">
<div id="html5-mode" ng-controller="Html5Cntl">
<h3>Browser with History API</h3>
<ng-address-bar browser="html5"></ng-address-bar><br /><br />
$location.protocol() = {{$location.protocol()}}<br />
$location.host() = {{$location.host()}}<br />
$location.port() = {{$location.port()}}<br />
$location.path() = {{$location.path()}}<br />
$location.search() = {{$location.search()}}<br />
$location.hash() = {{$location.hash()}}<br />
<a href="/base/first?a=b">/base/first?a=b</a> |
<a href="sec/ond?flag#hash">sec/ond?flag#hash</a> |
<a href="/base/another?search" ng-ext-link>external</a>
<div ng-address-bar browser="html5"></div><br><br>
$location.protocol() = {{$location.protocol()}}<br>
$location.host() = {{$location.host()}}<br>
$location.port() = {{$location.port()}}<br>
$location.path() = {{$location.path()}}<br>
$location.search() = {{$location.search()}}<br>
$location.hash() = {{$location.hash()}}<br>
<a href="http://www.host.com/base/first?a=b">/base/first?a=b</a> |
<a href="http://www.host.com/base/sec/ond?flag#hash">sec/ond?flag#hash</a> |
<a href="/other-base/another?search">external</a>
</div>
<div id="hashbang-mode" ng-controller="HashbangCntl">
<h3>Browser without History API</h3>
<ng-address-bar browser="hashbang"></ng-address-bar><br /><br />
$location.protocol() = {{$location.protocol()}}<br />
$location.host() = {{$location.host()}}<br />
$location.port() = {{$location.port()}}<br />
$location.path() = {{$location.path()}}<br />
$location.search() = {{$location.search()}}<br />
$location.hash() = {{$location.hash()}}<br />
<a href="/base/first?a=b">/base/first?a=b</a> |
<a href="sec/ond?flag#hash">sec/ond?flag#hash</a> |
<a href="/base/another?search" ng-ext-link>external</a>
<div ng-address-bar browser="hashbang"></div><br><br>
$location.protocol() = {{$location.protocol()}}<br>
$location.host() = {{$location.host()}}<br>
$location.port() = {{$location.port()}}<br>
$location.path() = {{$location.path()}}<br>
$location.search() = {{$location.search()}}<br>
$location.hash() = {{$location.hash()}}<br>
<a href="http://www.host.com/base/first?a=b">/base/first?a=b</a> |
<a href="http://www.host.com/base/sec/ond?flag#hash">sec/ond?flag#hash</a> |
<a href="/other-base/another?search">external</a>
</div>
</div>
<script type="text/javascript">
<script>
function FakeBrowser(initUrl, baseHref) {
this.onUrlChange = function(fn) {
this.urlChange = fn;
@@ -417,7 +429,6 @@ In this examples we use `<base href="/base/index.html" />`
return baseHref;
};
this.hover = angular.noop;
this.notifyWhenOutstandingRequests = angular.noop;
}
@@ -426,20 +437,19 @@ In this examples we use `<base href="/base/index.html" />`
hashbang: new FakeBrowser('http://www.host.com/base/index.html#!/path?a=b#h', '/base/index.html')
};
function Html5Cntl($location) {
this.$location = $location;
function Html5Cntl($scope, $location) {
$scope.$location = $location;
}
function HashbangCntl($location) {
this.$location = $location;
function HashbangCntl($scope, $location) {
$scope.$location = $location;
}
function initEnv(name) {
var root = angular.element(document.getElementById(name + '-mode'));
angular.bootstrap(root, [function($compileProvider, $locationProvider, $provide){
$locationProvider.html5Mode = true;
$locationProvider.hashPrefix = '!';
$locationProvider.html5Mode(true).hashPrefix('!');
$provide.value('$browser', browsers[name]);
$provide.value('$document', root);
$provide.value('$sniffer', {history: name == 'html5'});
@@ -447,7 +457,7 @@ In this examples we use `<base href="/base/index.html" />`
$compileProvider.directive('ngAddressBar', function() {
return function(scope, elm, attrs) {
var browser = browsers[attrs.browser],
input = angular.element('<input type="text" />').val(browser.url()),
input = angular.element('<input type="text">').val(browser.url()),
delay;
input.bind('keypress keyup keydown', function() {
@@ -488,11 +498,11 @@ In this examples we use `<base href="/base/index.html" />`
The `$location` service allows you to change only the URL; it does not allow you to reload the
page. When you need to change the URL and reload the page or navigate to a different page, please
use a lower level API, {@link api/angular.module.ng.$window $window.location.href}.
use a lower level API, {@link api/ng.$window $window.location.href}.
## Using $location outside of the scope life-cycle
`$location` knows about Angular's {@link api/angular.module.ng.$rootScope.Scope scope} life-cycle. When a URL changes in
`$location` knows about Angular's {@link api/ng.$rootScope.Scope scope} life-cycle. When a URL changes in
the browser it updates the `$location` and calls `$apply` so that all $watchers / $observers are
notified.
When you change the `$location` inside the `$digest` phase everything is ok; `$location` will
@@ -512,7 +522,7 @@ hashPrefix.
# Testing with the $location service
When using `$location` service during testing, you are outside of the angular's {@link
api/angular.module.ng.$rootScope.Scope scope} life-cycle. This means it's your responsibility to call `scope.$apply()`.
api/ng.$rootScope.Scope scope} life-cycle. This means it's your responsibility to call `scope.$apply()`.
<pre>
describe('serviceUnderTest', function() {
@@ -542,95 +552,106 @@ then uses the information it obtains to compose hashbang URLs (such as
## Changes to your code
<table>
<tr class="head">
<td>Navigation inside the app</td>
<td>Change to</td>
</tr>
<table class="table">
<thead>
<tr class="head">
<th>Navigation inside the app</th>
<th>Change to</th>
</tr>
</thead>
<tr>
<td>$location.href = value<br />$location.hash = value<br />$location.update(value)<br
<tbody>
<tr>
<td>$location.href = value<br />$location.hash = value<br />$location.update(value)<br
/>$location.updateHash(value)</td>
<td>$location.path(path).search(search)</td>
</tr>
<td>$location.path(path).search(search)</td>
</tr>
<tr>
<td>$location.hashPath = path</td>
<td>$location.path(path)</td>
</tr>
<tr>
<td>$location.hashPath = path</td>
<td>$location.path(path)</td>
</tr>
<tr>
<td>$location.hashSearch = search</td>
<td>$location.search(search)</td>
</tr>
<tr>
<td>$location.hashSearch = search</td>
<td>$location.search(search)</td>
</tr>
<tr class="head">
<td>Navigation outside the app</td>
<td>Use lower level API</td>
</tr>
<tr class="head">
<td>Navigation outside the app</td>
<td>Use lower level API</td>
</tr>
<tr>
<td>$location.href = value<br />$location.update(value)</td>
<td>$window.location.href = value</td>
</tr>
<tr>
<td>$location.href = value<br />$location.update(value)</td>
<td>$window.location.href = value</td>
</tr>
<tr>
<td>$location[protocol | host | port | path | search]</td>
<td>$window.location[protocol | host | port | path | search]</td>
</tr>
<tr>
<td>$location[protocol | host | port | path | search]</td>
<td>$window.location[protocol | host | port | path | search]</td>
</tr>
<tr class="head">
<td>Read access</td>
<td>Change to</td>
</tr>
<tr class="head">
<td>Read access</td>
<td>Change to</td>
</tr>
<tr>
<td>$location.hashPath</td>
<td>$location.path()</td>
</tr>
<tr>
<td>$location.hashPath</td>
<td>$location.path()</td>
</tr>
<tr>
<td>$location.hashSearch</td>
<td>$location.search()</td>
</tr>
<tr>
<td>$location.hashSearch</td>
<td>$location.search()</td>
</tr>
<tr>
<td>$location.href<br />$location.protocol<br />$location.host<br />$location.port<br
<tr>
<td>$location.href<br />$location.protocol<br />$location.host<br />$location.port<br
/>$location.hash</td>
<td>$location.absUrl()<br />$location.protocol()<br />$location.host()<br />$location.port()<br
<td>$location.absUrl()<br />$location.protocol()<br />$location.host()<br />$location.port()<br
/>$location.path() + $location.search()</td>
</tr>
</tr>
<tr>
<td>$location.path<br />$location.search</td>
<td>$window.location.path<br />$window.location.search</td>
</tr>
<tr>
<td>$location.path<br />$location.search</td>
<td>$window.location.path<br />$window.location.search</td>
</tr>
</tbody>
</table>
## Two-way binding to $location
The Angular's compiler currently does not support two-way binding for methods (see {@link
https://github.com/angular/angular.js/issues/404 issue}). If you should require two-way binding,
you will need to specify an extra property that has two watchers. For example:
<pre>
<!-- html -->
<input type="text" ng-model="locationPath" />
</pre>
<pre>
// js - controller
this.$watch('locationPath', function(path) {
$location.path(path);
});
this.$watch('$location.path()', function(path) {
scope.locationPath = path;
});
</pre>
https://github.com/angular/angular.js/issues/404 issue}). If you should require two-way binding
to the $location object (using {@link api/ng.directive:input.text
ngModel} directive on an input field), you will need to specify an extra model property
(e.g. `locationPath`) with two watchers which push $location updates in both directions. For
example:
<example>
<file name="index.html">
<div ng-controller="LocationController">
<input type="text" ng-model="locationPath" />
</div>
</file>
<file name="script.js">
function LocationController($scope, $location) {
$scope.$watch('locationPath', function(path) {
$location.path(path);
});
$scope.$watch(function() {
return $location.path();
}, function(path) {
$scope.locationPath = path;
});
}
</file>
</example>
# Related API
* {@link api/angular.module.ng.$location $location API}
* {@link api/ng.$location $location API}
@@ -2,12 +2,12 @@
@name Developer Guide: Angular Services: Creating Services
@description
While angular offers several useful services, for any nontrivial application you'll find it useful
While Angular offers several useful services, for any nontrivial application you'll find it useful
to write your own custom services. To do this you begin by registering a service factory function
with a module either via the {@link api/angular.module Module#factory api} or directly
via the {@link api/angular.module.AUTO.$provide $provide} api inside of module config function.
via the {@link api/AUTO.$provide $provide} api inside of module config function.
All angular services participate in {@link dev_guide.di dependency injection (DI)} by registering
All Angular services participate in {@link di dependency injection (DI)} by registering
themselves with Angular's DI system (injector) under a `name` (id) as well as by declaring
dependencies which need to be provided for the factory function of the registered service. The
ability to swap dependencies for mocks/stubs/dummies in tests allows for services to be highly
@@ -18,7 +18,7 @@ testable.
To register a service, you must have a module that this service will be part of. Afterwards, you
can register the service with the module either via the {@link api/angular.Module Module api} or
by using the {@link api/angular.module.AUTO.$provide $provide} service in the module configuration
by using the {@link api/AUTO.$provide $provide} service in the module configuration
function.The following pseudo-code shows both approaches:
Using the angular.Module api:
@@ -48,9 +48,9 @@ create this instance when called.
# Dependencies
Services can not only be depended upon, but also have its own dependencies. These can be specified
as arguments of the factory function. {@link dev_guide.di.understanding_di Read more} about the DI
in Angular and the use of array notation and $inject property to make DI annotation
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 dependency injection (DI)
in Angular and the use of array notation and the $inject property to make DI annotation
minification-proof.
Following is an example of a very simple service. This service depends on the `$window` service
@@ -76,17 +76,17 @@ angular.module('myModule', [], function($provide) {
# Instantiating Angular Services
All services in Angular are instantiates services 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.
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.
# Services as singletons
Lastly, it is important to realize that all angular services are application singletons. This means
that there is only one instance of a given service per injector. Since angular is lethally allergic
to the global state, it is possible to create multiple injectors, each with its own instance of a
Lastly, it is important to realize that all Angular services are application singletons. This means
that there is only one instance of a given service per injector. Since Angular is lethally allergic
to global state, it is possible to create multiple injectors, each with its own instance of a
given service, but that is rarely needed, except in tests where this property is crucially
important.
@@ -101,4 +101,4 @@ important.
## Related API
* {@link api/angular.module.ng Angular Service API}
* {@link api/ng Angular Service API}
@@ -30,7 +30,7 @@ myController.$inject = ['$location', '$log'];
<doc:example module="MyServiceModule">
<doc:source>
<script type="text/javascript">
<script>
angular.
module('MyServiceModule', []).
factory('notify', ['$window', function(win) {
@@ -57,6 +57,7 @@ myController.$inject = ['$scope','notify'];
<p>Let's try this simple notify service, injected into the controller...</p>
<input ng-init="message='test'" ng-model="message" >
<button ng-click="callNotify(message);">NOTIFY</button>
<p>(you have to click 3 times to see an alert)</p>
</div>
</doc:source>
<doc:scenario>
@@ -74,7 +75,7 @@ Let's rewrite the above example to show the use of this implicit dependency inje
<doc:example module="MyServiceModuleDI">
<doc:source>
<script type="text/javascript">
<script>
angular.
module('MyServiceModuleDI', []).
factory('notify', function($window) {
@@ -98,6 +99,7 @@ function myController($scope, notify) {
<p>Let's try the notify service, that is implicitly injected into the controller...</p>
<input ng-init="message='test'" ng-model="message">
<button ng-click="callNotify(message);">NOTIFY</button>
<p>(you have to click 3 times to see an alert)</p>
</div>
</doc:source>
</doc:example>
@@ -115,4 +117,4 @@ dependencies with the `$inject` property.
## Related API
{@link api/angular.module.ng Angular Service API}
{@link api/ng Angular Service API}
@@ -39,8 +39,8 @@ function myModuleCfgFn($provide) {
</pre>
Here is an example of two services that depend on each other, as well as on other services that are
provided by Angular's web framework:
Here is an example of two services, one of which depends on the other and both
of which depend on other services that are provided by the Angular framework:
<pre>
/**
@@ -50,7 +50,7 @@ provided by Angular's web framework:
* @param {*} message Message to be logged.
*/
function batchLogModule($provide){
$provide.factory('batchLog', ['$defer', '$log', function($defer, $log) {
$provide.factory('batchLog', ['$timeout', '$log', function($timeout, $log) {
var messageQueue = [];
function log() {
@@ -58,7 +58,7 @@ provided by Angular's web framework:
$log('batchLog messages: ', messageQueue);
messageQueue = [];
}
$defer(log, 50000);
$timeout(log, 50000);
}
// start periodic checking
@@ -76,7 +76,7 @@ provided by Angular's web framework:
$provide.factory('routeTemplateMonitor',
['$route', 'batchLog', '$rootScope',
function($route, batchLog, $rootScope) {
$rootScope.$on('$afterRouteChange', function() {
$rootScope.$on('$routeChangeSuccess', function() {
batchLog($route.current ? $route.current.template : null);
});
}]);
@@ -88,10 +88,10 @@ provided by Angular's web framework:
Things to notice in this example:
* The `batchLog` service depends on the built-in {@link api/angular.module.ng.$defer $defer} and
{@link api/angular.module.ng.$log $log} services, and allows messages to be logged into the
* The `batchLog` service depends on the built-in {@link api/ng.$timeout $timeout} and
{@link api/ng.$log $log} services, and allows messages to be logged into the
`console.log` in batches.
* The `routeTemplateMonitor` service depends on the built-in {@link api/angular.module.ng.$route
* The `routeTemplateMonitor` service depends on the built-in {@link api/ng.$route
$route} service as well as our custom `batchLog` service.
* Both of our services use the factory function signature and array notation for inject annotations
to declare their dependencies. It is important that the order of the string identifiers in the array
@@ -110,5 +110,5 @@ that the injector uses to determine which services and in which order to inject.
## Related API
* {@link api/angular.module.ng Angular Service API}
* {@link api/ng Angular Service API}
* {@link api/angular.injector Angular Injector API}
+4 -5
View File
@@ -2,10 +2,9 @@
@name Developer Guide: Angular Services
@description
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
objects that are wired together using {@link dev_guide.di dependency injection (DI)}. Services are
most often used with {@link dev_guide.di dependency injection}, also a key feature of angular apps.
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
objects that are wired together using {@link di dependency injection (DI)}.
## Related Topics
@@ -18,4 +17,4 @@ most often used with {@link dev_guide.di dependency injection}, also a key featu
## Related API
* {@link api/angular.module.ng Angular Service API}
* {@link api/ng Angular Service API}
@@ -2,7 +2,7 @@
@name Developer Guide: Angular Services: Testing Angular Services
@description
Following is a unit test for the service in the example in {@link
The following is a unit test for the 'notify' service in the 'Dependencies' example in {@link
dev_guide.services.creating_services Creating Angular Services}. The unit test example uses Jasmine
spy (mock) instead of a real browser alert.
@@ -55,8 +55,8 @@ it('should clear messages after alert', function() {
* {@link dev_guide.services.understanding_services Understanding Angular Services}
* {@link dev_guide.services.creating_services Creating Angular Services}
* {@link dev_guide.services.managing_dependencies Managing Service Dependencies}
* {@link dev_guide.services.injecting_controllers Injecting Services Into Conrollers}
* {@link dev_guide.services.injecting_controllers Injecting Services Into Controllers}
## Related API
* {@link api/angular.module.ng Angular Service API}
* {@link api/ng Angular Service API}
@@ -3,12 +3,12 @@
@description
Angular services are singletons that carry out specific tasks common to web apps, such as the
{@link api/angular.module.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.
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
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.
Angular injects dependencies using "constructor" injection (the service is passed in via a factory
@@ -18,19 +18,19 @@ must explicitly define its dependencies by using the `$inject` property. For ex
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
above). You can also create your own custom services.
## Related Topics
* {@link dev_guide.di About Angular Dependency Injection}
* {@link di About Angular Dependency Injection}
* {@link dev_guide.services.creating_services Creating Angular Services}
* {@link dev_guide.services.managing_dependencies Managing Service Dependencies}
* {@link dev_guide.services.testing_services Testing Angular Services}
## Related API
* {@link api/angular.module.ng Angular Service API}
* {@link api/ng Angular Service API}
* {@link api/angular.injector Injector API}
@@ -7,12 +7,20 @@ Angular sets these CSS classes. It is up to your application to provide useful s
# CSS classes used by angular
* `ng-scope`
- **Usage:** angular applies this class to any element that where a new {@link api/ng.$rootScope.Scope scope}
is defined. (see {@link guide/scope scope} guide for more information about scopes)
* `ng-binding`
- **Usage:** angular applies this class to any element that is attached to a data binding, via `ng-bind` or
{{}} curly braces, for example. (see {@link guide/dev_guide.templates.databinding databinding} guide)
* `ng-invalid`, `ng-valid`
- **Usage:** angular applies this class to an input widget element if that element's input does
notpass validation. (see {@link api/angular.module.ng.$compileProvider.directive.input input} widget).
not pass validation. (see {@link api/ng.directive:input input} directive)
* `ng-pristine`, `ng-dirty`
- **Usage:** angular {@link api/angular.module.ng.$compileProvider.directive.input input} widget applies `ng-pristine` class
- **Usage:** angular {@link api/ng.directive:input input} directive applies `ng-pristine` class
to a new input widget element which did not have user interaction. Once the user interacts with
the input widget the class is changed to `ng-dirty`.
@@ -20,4 +28,4 @@ Angular sets these CSS classes. It is up to your application to provide useful s
## Related Topics
* {@link dev_guide.templates Angular Templates}
* {@link dev_guide.forms Angular Forms}
* {@link forms Angular Forms}
@@ -2,8 +2,8 @@
@name Developer Guide: Templates: Data Binding in Angular
@description
Data-binding in angular web apps is the automatic syncing of data between the model and view
components. The way that angular implements data-binding lets you treat the model as the
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
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.
@@ -19,12 +19,12 @@ to write code that constantly syncs the view with the model and the model with t
## Data Binding in Angular Templates
<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
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
the model are propagated to the view. This makes the model always the single-source-of-truth for
the application state, greatly simplifying the programing model for the developer. You can think of
the application state, greatly simplifying the programming model for the developer. You can think of
the view as simply an instant projection of your model.
Because the view is just a projection of the model, the controller is completely separated from the
@@ -34,5 +34,5 @@ isolation without the view and the related DOM/browser dependency.
## Related Topics
* {@link dev_guide.scopes Angular Scopes}
* {@link scope Angular Scopes}
* {@link dev_guide.templates Angular Templates}
@@ -2,23 +2,17 @@
@name Developer Guide: Templates: Filters: Creating Angular Filters
@description
Writing your own filter is very easy: just define a JavaScript function on the `angular.module.ng.$filter`
object.
The framework passes in the input value as the first argument to your function. Any filter
arguments are passed in as additional function arguments.
You can use these variables in the function:
* `this` — The current scope.
* `this.$element` — The DOM element containing the binding. The `$element` variable allows the
filter to manipulate the DOM.
Writing your own filter is very easy: just register a new filter (injectable) factory function with
your module. This factory function should return a new filter function which takes the input value
as the first argument. Any filter arguments are passed in as additional arguments to the filter
function.
The following sample filter reverses a text string. In addition, it conditionally makes the
text upper-case and assigns color.
text upper-case.
<doc:example module="MyReverseModule">
<doc:source>
<script type="text/javascript">
<script>
angular.module('MyReverseModule', []).
filter('reverse', function() {
return function(input, uppercase) {
@@ -59,8 +53,8 @@ text upper-case and assigns color.
## Related Topics
* {@link dev_guide.templates.filters Understanding Angular Filters}
* {@link dev_guide.compiler Angular HTML Compiler}
* {@link compiler Angular HTML Compiler}
## Related API
* {@link api/angular.module.ng.$filter Angular Filter API}
* {@link api/ng.$filter Angular Filter API}
@@ -2,9 +2,7 @@
@name Developer Guide: Templates: Understanding Angular Filters
@description
Angular filters format data for display to the user. In addition to formatting data, filters can
also modify the DOM. This allows filters to handle tasks such as conditionally applying CSS styles
to filtered output.
Angular filters format data for display to the user.
For example, you might have a data object that needs to be formatted according to the locale before
displaying it to the user. You can pass expressions through a chain of filters like this:
@@ -12,10 +10,7 @@ displaying it to the user. You can pass expressions through a chain of filters l
name | uppercase
The expression evaluator simply passes the value of name to
{@link api/angular.module.ng.$filter.uppercase uppercase filter}.
In addition to formatting data, filters can also modify the DOM. This allows filters to handle
tasks such as conditionally applying CSS styles to filtered output.
{@link api/ng.filter:uppercase uppercase filter}.
## Related Topics
@@ -25,4 +20,4 @@ tasks such as conditionally applying CSS styles to filtered output.
## Related API
* {@link api/angular.module.ng.$filter Angular Filter API}
* {@link api/ng.$filter Angular Filter API}
@@ -2,7 +2,7 @@
@name Developer Guide: Templates: Filters: Using Angular Filters
@description
Filters can be part of any {@link api/angular.module.ng.$rootScope.Scope} evaluation but are typically used to format
Filters can be part of any {@link api/ng.$rootScope.Scope} evaluation but are typically used to format
expressions in bindings in your templates:
{{ expression | filter }}
@@ -19,6 +19,10 @@ You can also pass colon-delimited arguments to filters, for example, to display
123 | number:2
Use the same syntax for multiple arguments:
myArray | orderBy:'timestamp':true
Here are some examples that show values before and after applying different filters to an
expression in a binding:
@@ -37,4 +41,4 @@ argument that specifies how many digits to display to the right of the decimal p
## Related API
* {@link api/angular.module.ng.$filter Angular Filter API}
* {@link api/ng.$filter Angular Filter API}
+13 -13
View File
@@ -2,31 +2,31 @@
@name Developer Guide: Understanding Angular Templates
@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,
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.
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 api/angular.module.ng.$compileProvider.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.
* {@link api/angular.module.ng.$interpolate Markup} — The double
* {@link api/ng.$interpolate Markup} — The double
curly brace notation `{{ }}` to bind expressions to elements is built-in angular markup.
* {@link dev_guide.templates.filters Filter} — Formats your data for display to the user.
* {@link dev_guide.forms Form controls} — Lets you validate user input.
* {@link forms Form controls} — Lets you validate user input.
Note: In addition to declaring the elements above in templates, you can also access these elements
in JavaScript code.
The following code snippet shows a simple angular template made up of standard HTML tags along with
angular {@link api/angular.module.ng.$compileProvider.directive directives} and curly-brace bindings
with {@link dev_guide.expressions expressions}:
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
with {@link expression expressions}:
<pre>
<html ng-app>
<!-- Body tag augmented with ng-controller directive -->
<!-- Body tag augmented with ngController directive -->
<body ng-controller="MyController">
<input ng-model="foo" value="bar">
<!-- Button tag with ng-click directive, and
@@ -41,8 +41,8 @@ with {@link dev_guide.expressions expressions}:
In a simple single-page app, the template consists of HTML, CSS, and angular directives contained
in just one HTML file (usually `index.html`). In a more complex app, you can display multiple views
within one main page using "partials", which are segments of template located in separate HTML
files. You "include" the partials in the main page using the {@link api/angular.module.ng.$route
$route} service in conjunction with the {@link api/angular.module.ng.$compileProvider.directive.ng-view ng-view} directive. An
files. You "include" the partials in the main page using the {@link api/ng.$route
$route} service in conjunction with the {@link api/ng.directive:ngView ngView} directive. An
example of this technique is shown in the {@link tutorial/ angular tutorial}, in steps seven and
eight.
@@ -50,7 +50,7 @@ eight.
## Related Topics
* {@link dev_guide.templates.filters Angular Filters}
* {@link dev_guide.forms Angular Forms}
* {@link forms Angular Forms}
## Related API
+119 -59
View File
@@ -3,37 +3,49 @@
@description
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
comes 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
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
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
in the right order. In order to answer such question it is very important that we can isolate it.
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
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 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
typical project. The reason is that the developers often time 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
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 crated abstraction which
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
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,
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
DOM in the right way. 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, you may very well end up with an untestable application.
DOM in the right way.
## 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:
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
the registry? Must likely by looking it up in a well know place. See #2)
4. You could expect that the it be handed to you.
the registry? Most likely by looking it up in a well known place. See #2)
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 four options in the list above, only the last one is testable. Let's look at why:
### Using the `new` operator
@@ -52,10 +64,10 @@ function MyClass() {
}
</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
permanently bound to the actual one, 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.
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 are outside the scope of this document.
The class above is hard to test since we have to resort to monkey patching:
<pre>
@@ -69,7 +81,7 @@ XHR = oldXHR; // if you forget this bad things will happen
### 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>
function MyClass() {
@@ -83,17 +95,17 @@ function MyClass() {
}
</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
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 a 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
http://misko.hevery.com/code-reviewers-guide/flaw-brittle-global-state-singletons/ Brittle Global
State & Singletons}
The class above is hard to test since we have to change global state:
<pre>
var oldXHR = glabal.xhr;
glabal.xhr = function mockXHR() {};
var oldXHR = global.xhr;
global.xhr = function mockXHR() {};
var myClass = new MyClass();
myClass.doWork();
// assert that mockXHR got called with the right arguments
@@ -119,19 +131,19 @@ function MyClass() {
}
</pre>
However, where dose the serviceRegistry come from? if it is:
However, where does the serviceRegistry come from? if it is:
* `new`-ed up, the the test has no chance to reset the services for testing
* global look-up, then the service returned is global as well (but resetting is easier, since
there is only one global variable to be reset).
The class above is hard to test since we have to change global state:
<pre>
var oldServiceLocator = glabal.serviceLocator;
glabal.serviceLocator.set('xhr', function mockXHR() {});
var oldServiceLocator = global.serviceLocator;
global.serviceLocator.set('xhr', function mockXHR() {});
var myClass = new MyClass();
myClass.doWork();
// assert that mockXHR got called with the right arguments
glabal.serviceLocator = oldServiceLocator; // if you forget this bad things will happen
global.serviceLocator = oldServiceLocator; // if you forget this bad things will happen
</pre>
@@ -164,7 +176,7 @@ myClass.doWork();
Notice that no global variables were harmed in the writing of this test.
Angular comes with {@link dev_guide.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.
## Controllers
@@ -173,7 +185,7 @@ for your application is mixed in with DOM manipulation, it will be hard to test
below:
<pre>
function PasswordController() {
function PasswordCtrl() {
// get references to DOM elements
var msg = $('.ex1 span');
var input = $('.ex1 input');
@@ -197,7 +209,7 @@ function PasswordController() {
}
</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:
<pre>
@@ -207,7 +219,7 @@ $('body').html('<div class="ex1">')
.find('div')
.append(input)
.append(span);
var pc = new PasswordController();
var pc = new PasswordCtrl();
input.val('abc');
pc.grade();
expect(span.text()).toEqual('weak');
@@ -218,36 +230,36 @@ In angular the controllers are strictly separated from the DOM manipulation logi
a much easier testability story as can be seen in this example:
<pre>
function PasswordCntrl() {
this.password = '';
this.grade = function() {
var size = this.password.length;
function PasswordCtrl($scope) {
$scope.password = '';
$scope.grade = function() {
var size = $scope.password.length;
if (size > 8) {
this.strength = 'strong';
$scope.strength = 'strong';
} else if (size > 3) {
this.strength = 'medium';
$scope.strength = 'medium';
} else {
this.strength = 'weak';
$scope.strength = 'weak';
}
};
}
</pre>
and the tests is straight forward
and the test is straight forward
<pre>
var pc = new PasswordController();
pc.password('abc');
pc.grade();
expect(span.strength).toEqual('weak');
var $scope = {};
var pc = $controller('PasswordCtrl', { $scope: $scope });
$scope.password = 'abc';
$scope.grade();
expect($scope.strength).toEqual('weak');
</pre>
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.
## Filters
{@link api/angular.module.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
logic, further simplifying the application logic.
@@ -264,18 +276,66 @@ expect(length('abc')).toEqual(3);
</pre>
## Directives
Directives in angular are responsible for updating the DOM when the state of the model changes.
Directives in angular are responsible for encapsulating complex functionality within custom HTML tags,
attributes, classes or comments. Unit tests are very important for directives because the components
you create with directives may be used throughout your application and in many different contexts.
### Simple HTML Element Directive
Lets start with an angular app with no dependencies.
<pre>
var app = angular.module('myApp', []);
</pre>
Now we can add a directive to our app.
<pre>
app.directive('aGreatEye', function () {
return {
restrict: 'E',
replace: true,
template: '<h1>lidless, wreathed in flame, {{1 + 1}} times</h1>'
};
});
</pre>
This directive is used as a tag `<a-great-eye></a-great-eye>`. It replaces the entire tag with the
template `<h1>lidless, wreathed in flame, {{1 + 1}} times</h1>`. Now we are going to write a jasmine unit test to
verify this functionality. Note that the expression `{{1 + 1}}` times will also be evaluated in the rendered content.
<pre>
describe('Unit testing great quotes', function() {
var $compile;
var $rootScope;
// Load the myApp module, which contains the directive
beforeEach(module('myApp'));
// Store references to $rootScope and $compile
// so they are available to all tests in this describe block
beforeEach(inject(function(_$compile_, _$rootScope_){
// The injector unwraps the underscores (_) from around the parameter names when matching
$compile = _$compile_;
$rootScope = _$rootScope_;
}));
it('Replaces the element with the appropriate content', function() {
// Compile a piece of HTML containing the directive
var element = $compile("<a-great-eye></a-great-eye>")($rootScope);
// fire all the watches, so the scope expression {{1 + 1}} will be evaluated
$rootScope.$digest();
// Check that the compiled element contains the templated content
expect(element.html()).toContain("lidless, wreathed in flame, 2 times");
});
});
</pre>
We inject the $compile service and $rootScope before each jasmine test. The $compile service is used
to render the aGreatEye directive. After rendering the directive we ensure that the directive has
replaced the content and "lidless, wreathed in flame, 2 times" is present.
## Mocks
oue
## Global State Isolation
oue
# Preferred way of Testing
uo
## JavaScriptTestDriver
ou
## Jasmine
ou
## Sample project
uoe
See the {@link https://github.com/angular/angular-seed angular-seed} project for an example.
+239
View File
@@ -0,0 +1,239 @@
@ngdoc overview
@name Developer Guide: Dependency Injection
@description
# Dependency Injection
Dependency Injection (DI) is a software design pattern that deals with how code gets hold of its
dependencies.
For in-depth discussion about DI, see {@link http://en.wikipedia.org/wiki/Dependency_injection
Dependency Injection} at Wikipedia, {@link http://martinfowler.com/articles/injection.html
Inversion of Control} by Martin Fowler, or read about DI in your favorite software design pattern
book.
## DI in a nutshell
There are only three ways an object or a function can get a hold of its dependencies:
1. The dependency can be created, typically using the `new` operator.
2. The dependency can be looked up by referring to a global variable.
3. The dependency can be passed in to where it is needed.
The first two options of creating or looking up dependencies are not optimal because they hard
code the dependency. This makes it difficult, if not impossible, to modify the dependencies.
This is especially problematic in tests, where it is often desirable to provide mock dependencies
for test isolation.
The third option is the most viable, since it removes the responsibility of locating the
dependency from the component. The dependency is simply handed to the component.
<pre>
function SomeClass(greeter) {
this.greeter = greeter;
}
SomeClass.prototype.doSomething = function(name) {
this.greeter.greet(name);
}
</pre>
In the above example `SomeClass` is not concerned with locating the `greeter` dependency, it
is simply handed the `greeter` at runtime.
This is desirable, but it puts the responsibility of getting hold of the dependency on the
code that constructs `SomeClass`.
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
construction and lookup of dependencies.
Here is an example of using the injector service:
<pre>
// Provide the wiring information in a module
angular.module('myModule', []).
// Teach the injector how to build a 'greeter'
// Notice that greeter itself is dependent on '$window'
factory('greeter', function($window) {
// This is a factory function, and is responsible for
// creating the 'greet' service.
return {
greet: function(text) {
$window.alert(text);
}
};
});
// New injector is created from the module.
// (This is usually done automatically by angular bootstrap)
var injector = angular.injector(['myModule', 'ng']);
// Request any dependency from the injector
var greeter = injector.get('greeter');
</pre>
Asking for dependencies solves the issue of hard coding, but it also means that the injector needs
to be passed throughout the application. Passing the injector breaks the {@link
http://en.wikipedia.org/wiki/Law_of_Demeter Law of Demeter}. To remedy this, we turn the
dependency lookup responsibility to the injector by declaring the dependencies as in this example:
<pre>
<!-- Given this HTML -->
<div ng-controller="MyController">
<button ng-click="sayHello()">Hello</button>
</div>
</pre>
<pre>
// And this controller definition
function MyController($scope, greeter) {
$scope.sayHello = function() {
greeter.greet('Hello World');
};
}
// The 'ng-controller' directive does this behind the scenes
injector.instantiate(MyController);
</pre>
Notice that by having the `ng-controller` instantiate the class, it can satisfy all of the
dependencies of `MyController` without the controller ever knowing about the injector. This is
the best outcome. The application code simply asks for the dependencies it needs, without having to
deal with the injector. This setup does not break the Law of Demeter.
## Dependency Annotation
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
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
the function. Below are three equivalent ways of annotating your code with service name
information. These can be used interchangeably as you see fit and are equivalent.
### Inferring Dependencies
The simplest way to get hold of the dependencies, is to assume that the function parameter names
are the names of the dependencies.
<pre>
function MyController($scope, greeter) {
...
}
</pre>
Given a function the injector can infer the names of the service to inject by examining the
function declaration and extracting the parameter names. In the above example `$scope`, and
`greeter` are two services which need to be injected into the function.
While straightforward, this method will not work with JavaScript minifiers/obfuscators as they
rename the method parameter names. This makes this way of annotating only useful for {@link
http://www.pretotyping.org/ pretotyping}, and demo applications.
### `$inject` Annotation
To allow the minifers to rename the function parameters and still be able to inject right services
the function needs to be annotated with the `$inject` property. The `$inject` property is an array
of service names to inject.
<pre>
var MyController = function(renamed$scope, renamedGreeter) {
...
}
MyController.$inject = ['$scope', 'greeter'];
</pre>
In this scenario the ordering of the values in the '$inject' array must match the ordering of the arguments to inject.
Using above code snippet as an example, '$scope' will be injected into 'renamed$scope' and 'greeter' into 'renamedGreeter'.
Care must be taken that the `$inject` annotation is kept in sync with the actual arguments in the
function declaration.
This method of annotation is useful for controller declarations since it assigns the annotation
information with the function.
### Inline Annotation
Sometimes using the `$inject` annotation style is not convenient such as when annotating
directives.
For example:
<pre>
someModule.factory('greeter', function($window) {
...
});
</pre>
Results in code bloat due to needing a temporary variable:
<pre>
var greeterFactory = function(renamed$window) {
...
};
greeterFactory.$inject = ['$window'];
someModule.factory('greeter', greeterFactory);
</pre>
For this reason the third annotation style is provided as well.
<pre>
someModule.factory('greeter', ['$window', function(renamed$window) {
...
}]);
</pre>
Keep in mind that all of the annotation styles are equivalent and can be used anywhere in Angular
where injection is supported.
## Where can I use DI?
DI is pervasive throughout Angular. It is typically used in controllers and factory methods.
### DI in controllers
Controllers are classes which are responsible for application behavior. The recommended way of
declaring controllers is using the array notation:
<pre>
someModule.controller('MyController', ['$scope', 'dep1', 'dep2', function($scope, dep1, dep2) {
...
$scope.aMethod = function() {
...
}
...
}]);
</pre>
This avoids the creation of global functions for controllers and also protects against minification.
### Factory methods
Factory methods are responsible for creating most objects in Angular. Examples are directives,
services, and filters. The factory methods are registered with the module, and the recommended way
of declaring factories is:
<pre>
angular.module('myModule', []).
config(['depProvider', function(depProvider){
...
}]).
factory('serviceId', ['depService', function(depService) {
...
}]).
directive('directiveName', ['depService', function(depService) {
...
}]).
filter('filterName', ['depService', function(depService) {
...
}]).
run(['depService', function(depService) {
...
}]);
</pre>
@@ -1,5 +1,5 @@
@ngdoc overview
@name angular.module.ng.$compileProvider.directive
@name Directives
@description
Directives are a way to teach HTML new tricks. During DOM compilation directives are matched
@@ -10,7 +10,7 @@ can be extended such that HTML can be turned into a declarative domain specific
# Invoking directives from HTML
Directives have camel cased names such as 'ngBind'. The directive can be invoked by translating
Directives have camel cased names such as `ngBind`. The directive can be invoked by translating
the camel case name into snake case with these special characters `:`, `-`, or `_`. Optionally the
directive can be prefixed with `x-`, or `data-` to make it HTML validator compliant. Here is a
list of some of the possible directive names: `ng:bind`, `ng-bind`, `ng_bind`, `x-ng-bind` and
@@ -27,43 +27,43 @@ attribute only.)
<!-- directive: my-dir exp -->
</pre>
Directives can be invoked in many different ways, but are equivalent in the end result as shown in
the following example.
The following demonstrates the various ways a Directive (ngBind in this case) can be referenced from within a template.
<doc:example>
<doc:source >
<script>
function Ctrl1($scope) {
$scope.name = 'angular';
$scope.name = 'Max Karl Ernst Ludwig Planck (April 23, 1858 October 4, 1947)';
}
</script>
<div ng-controller="Ctrl1">
Hello <input ng-model='name' ng-model-instant> <hr/>
&ltspan ng:bind="name"&gt <span ng:bind="name"></span> <br/>
&ltspan ng_bind="name"&gt <span ng_bind="name"></span> <br/>
&ltspan ng-bind="name"&gt <span ng-bind="name"></span> <br/>
&ltspan data-ng-bind="name"&gt <span data-ng-bind="name"></span> <br/>
&ltspan x-ng-bind="name"&gt <span x-ng-bind="name"></span> <br/>
Hello <input ng-model='name'> <hr/>
&lt;span ng-bind="name"&gt; <span ng-bind="name"></span> <br/>
&lt;span ng:bind="name"&gt; <span ng:bind="name"></span> <br/>
&lt;span ng_bind="name"&gt; <span ng_bind="name"></span> <br/>
&lt;span data-ng-bind="name"&gt; <span data-ng-bind="name"></span> <br/>
&lt;span x-ng-bind="name"&gt; <span x-ng-bind="name"></span> <br/>
</div>
</doc:source>
<doc:scenario>
it('should load template1.html', function() {
expect(element('div[ng-controller="Ctrl1"] span[ng-bind]').text()).toBe('angular');
it('should show off bindings', function() {
expect(element('div[ng-controller="Ctrl1"] span[ng-bind]').text())
.toBe('Max Karl Ernst Ludwig Planck (April 23, 1858 October 4, 1947)');
});
</doc:scenario>
</doc:example>
# String interpolation
During the compilation process the {@link angular.module.ng.$compile compiler} matches text and
attributes using the {@link angular.module.ng.$interpolate $interpolate} service to see if they
During the compilation process the {@link api/ng.$compile compiler} matches text and
attributes using the {@link api/ng.$interpolate $interpolate} service to see if they
contain embedded expressions. These expressions are registered as {@link
angular.module.ng.$rootScope.Scope#$watch watches} and will update as part of normal {@link
angular.module.ng.$rootScope.Scope#$digest digest} cycle. An example of interpolation is shown
api/ng.$rootScope.Scope#$watch watches} and will update as part of normal {@link
api/ng.$rootScope.Scope#$digest digest} cycle. An example of interpolation is shown
here:
<pre>
<img src="img/{{username}}.jpg">Hello {{username}}!</img>
<a href="img/{{username}}.jpg">Hello {{username}}!</a>
</pre>
# Compilation process, and directive matching
@@ -72,30 +72,30 @@ Compilation of HTML happens in three phases:
1. First the HTML is parsed into DOM using the standard browser API. This is important to
realize because the templates must be parsable HTML. This is in contrast to most templating
systems that operate on strings, rather then on DOM elements.
systems that operate on strings, rather than on DOM elements.
2. The compilation of the DOM is performed by the call to {@link angular.module.ng.$compile
2. The compilation of the DOM is performed by the call to the {@link api/ng.$compile
$compile()} method. The method traverses the DOM and matches the directives. If a match is found
it is added to the list of directives associated with the given DOM element. Once all directives
for a given DOM element have been identified they are sorted by priority and their `compile()`
functions are executed. The directive compile function has a chance to modify the DOM structure
and is responsible for producing a `link()` function explained next. The {@link
angular.module.ng.$compile $compile()} method returns a combined linking function, which is a
api/ng.$compile $compile()} method returns a combined linking function, which is a
collection of all of the linking functions returned from the individual directive compile
functions.
3. Link the template with scope by calling the liking function returned from the previous step.
3. Link the template with scope by calling the linking function returned from the previous step.
This in turn will call the linking function of the individual directives allowing them to
register any listeners on the elements and set up any {@link
angular.module.ng.$rootScope.Scope#$watch watches} with the {@link
angular.module.ng.$rootScope.Scope scope}. The result of this is a live binding between the
api/ng.$rootScope.Scope#$watch watches} with the {@link
api/ng.$rootScope.Scope scope}. The result of this is a live binding between the
scope and the DOM. A change in the scope is reflected in the DOM.
<pre>
var $compile = ...; // injected into your code
var scope = ...;
var html = '<div ng-bind='exp'></div>';
var html = '<div ng-bind="exp"></div>';
// Step 1: parse HTML into DOM element
var template = angular.element(html);
@@ -109,8 +109,8 @@ Compilation of HTML happens in three phases:
## Reasons behind the compile/link separation
At this point you may wonder why is the compile process broken down to a compile and link phase.
To understand this, lets look at a real world example with repeater:
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 a repeater:
<pre>
Hello {{user}}, you have these actions:
@@ -125,49 +125,49 @@ The short answer is that compile and link separation is needed any time a change
a change in DOM structure such as in repeaters.
When the above example is compiled, the compiler visits every node and looks for directives. The
`{{user}}` is an example of {@link angular.module.ng.$interpolate interpolation} directive. {@link
angular.module.ng.$compileProvider.directive.ng-repeat ng-repeat} is another directive. But {@link
angular.module.ng.$compileProvider.directive.ng-repeat ng-repeat} has a dilemma. It needs to be
`{{user}}` is an example of an {@link api/ng.$interpolate interpolation} directive. {@link
api/ng.directive:ngRepeat ngRepeat} is another directive. But {@link
api/ng.directive:ngRepeat ngRepeat} has a dilemma. It needs to be
able to quickly stamp out new `li`s for every `action` in `user.actions`. This means that it needs
to save a clean copy of the `li` element for cloning purposes and as new `action`s are inserted,
the template `li` element needs to be cloned and inserted into `ul`. But cloning the `li` element
is not enough. It also needs to compile the `li` so that its directives such as
`{{action.descriptions}}` evaluate against the right {@link angular.module.ng.$rootScope.Scope
scope}. A naive method would be to simply insert a copy of the `li` elemnt and then compile it.
`{{action.description}}` evaluate against the right {@link api/ng.$rootScope.Scope
scope}. A naive method would be to simply insert a copy of the `li` element and then compile it.
But compiling on every `li` element clone would be slow, since the compilation requires that we
traverse the DOM tree and look for directives and execute them. If we put the compilation inside a
repeater which needs to unroll 100 items we would quickly run into performance problem.
repeater which needs to unroll 100 items we would quickly run into performance problems.
The solution is to break the compilation process into two phases the compile phase where all of
The solution is to break the compilation process into two phases; the compile phase where all of
the directives are identified and sorted by priority, and a linking phase where any work which
links a specific instance of the {@link angular.module.ng.$rootScope.Scope scope} and the specific
links a specific instance of the {@link api/ng.$rootScope.Scope scope} and the specific
instance of an `li` is performed.
{@link angular.module.ng.$compileProvider.directive.ng-repeat ng-repeat} works by preventing the
compilation process form descending into `li` element. Instead the {@link
angular.module.ng.$compileProvider.directive.ng-repeat ng-repeat} directive compiles `li`
seperatly. The result of of the `li` element compilation is a linking function which contains all
of the directives contained in the `li` element ready to be attached to a specific clone of `li`
element. At runtime the {@link angular.module.ng.$compileProvider.directive.ng-repeat ng-repeat}
{@link api/ng.directive:ngRepeat ngRepeat} works by preventing the
compilation process from descending into the `li` element. Instead the {@link
api/ng.directive:ngRepeat ngRepeat} directive compiles `li`
separately. The result of the `li` element compilation is a linking function which contains all
of the directives contained in the `li` element, ready to be attached to a specific clone of the `li`
element. At runtime the {@link api/ng.directive:ngRepeat ngRepeat}
watches the expression and as items are added to the array it clones the `li` element, creates a
new {@link angular.module.ng.$rootScope.Scope scope} for the cloned `li` element and calls the
new {@link api/ng.$rootScope.Scope scope} for the cloned `li` element and calls the
link function on the cloned `li`.
Summary:
* *compile function* - The compile function is relatively rare in directives, since most
directives are concerned with working with a specific DOM element instance rather then
directives are concerned with working with a specific DOM element instance rather than
transforming the template DOM element. Any operation which can be shared among the instance of
directives should be moved to the compile function for performance reasons.
* *link function* - It is rare for the directive not to have a link function. Link function
* *link function* - It is rare for the directive not to have a link function. A link function
allows the directive to register listeners to the specific cloned DOM element instance as well
as to copy content into the DOM from the scope.
# Writing directives (short version)
In this example we will build a directive which displays the current time.
In this example we will build a directive that displays the current time.
<doc:example module="time">
<doc:source>
@@ -178,12 +178,12 @@ In this example we will build a directive which displays the current time.
angular.module('time', [])
// Register the 'myCurrentTime' directive factory method.
// We inject $defer and dateFilter service since the factory method is DI.
.directive('myCurrentTime', function($defer, dateFilter) {
// We inject $timeout and dateFilter service since the factory method is DI.
.directive('myCurrentTime', function($timeout, dateFilter) {
// return the directive link function. (compile function not needed)
return function(scope, element, attrs) {
var format, // date format
deferId; // deferId, so that we can cancel the time updates
timeoutId; // timeoutId, so that we can cancel the time updates
// used to update the UI
function updateTime() {
@@ -198,36 +198,39 @@ In this example we will build a directive which displays the current time.
// schedule update in one second
function updateLater() {
// save the deferId for canceling
deferId = $defer(function() {
// save the timeoutId for canceling
timeoutId = $timeout(function() {
updateTime(); // update DOM
updateLater(); // schedule another update
}, 1000);
}
// listen on DOM destroy (removal) event, and cancel the next UI update
// to prevent updating time ofter the DOM element was removed.
// to prevent updating time after the DOM element was removed.
element.bind('$destroy', function() {
$defer.cancel(deferId);
$timeout.cancel(timeoutId);
});
updateLater(); // kick of the UI update process.
updateLater(); // kick off the UI update process.
}
});
</script>
<div ng-controller="Ctrl2">
Date format: <input ng-model='format'> <hr/>
Current time is: <span my-current-time="format"></span
Date format: <input ng-model="format"> <hr/>
Current time is: <span my-current-time="format"></span>
</div>
</doc:source>
<doc:scenario>
</doc:scenario>
</doc:example>
# Writing directives (long version)
The full skeleton of the directive is shown here:
There are different ways to declare a directive. The difference resides in the return
value of the factory function. You can either return a Directive Definition Object
(see below) that defines the directive properties, or just the postLink function
of such an object (all other properties will have the default values).
Here's an example directive declared with a Directive Definition Object:
<pre>
var myModule = angular.module(...);
@@ -241,6 +244,8 @@ The full skeleton of the directive is shown here:
transclude: false,
restrict: 'A',
scope: false,
controller: ["$scope", "$element", "$attrs", "$transclude", "otherInjectables",
function($scope, $element, $attrs, $transclude, otherInjectables) { ... }],
compile: function compile(tElement, tAttrs, transclude) {
return {
pre: function preLink(scope, iElement, iAttrs, controller) { ... },
@@ -253,12 +258,11 @@ The full skeleton of the directive is shown here:
});
</pre>
In most cases you will not need such fine control and so the above can be simplified. All of the
different parts of this skeleton are explained in following sections. In this section we are
interested only isomers of this skeleton.
In most cases you will not need such fine control and so the above can be simplified. You can still
return a Directive Definition Object, but only setting the 'compile' function property of the Object,
and rely on the default values for other properties.
The first step in simplyfing the code is to rely on the deafult values. Therefore the above can be
simplified as:
Therefore the above can be simplified as:
<pre>
var myModule = angular.module(...);
@@ -273,8 +277,10 @@ simplified as:
});
</pre>
Most directives concern themselves only with instances not with template transformations allowing
further simplification:
Finally, most directives concern themselves only with instances, not with template transformations, allowing
further simplification.
Here we only define the postLink function:
<pre>
var myModule = angular.module(...);
@@ -288,22 +294,23 @@ further simplification:
## Factory method
The factory method is responsible for creating the directive. It is invoked only once, when the
{@link angular.module.ng.$compile compiler} matches the directive for the first time. You can
{@link api/ng.$compile compiler} matches the directive for the first time. You can
perform any initialization work here. The method is invoked using the {@link
http://localhost:8000/build/docs/api/angular.module.AUTO.$injector#invoke $injector.invoke} which
api/AUTO.$injector#invoke $injector.invoke} which
makes it injectable following all of the rules of injection annotation.
## Directive Definition Object
The directive definition object provides instructions to the {@link angular.module.ng.$compile
The directive definition object provides instructions to the {@link api/ng.$compile
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
is necessary to specify the order in which the directives are applied. The `priority` is used
to sort the directives before their `compile` functions get called. Higher `priority` goes
first. The order of directives within the same priority is undefined.
to sort the directives before their `compile` functions get called. Priority is defined as a
number. Directives with greater numerical `priority` are compiled first. The order of directives with
the same priority is undefined. The default priority is `0`.
* `terminal` - If set to true then the current `priority` will be the last set of directives
which will execute (any directives at the current priority will still execute
@@ -312,55 +319,61 @@ compiler}. The attributes are:
* `scope` - If set to:
* `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.
* `{}` (object hash) - then a new 'isolate' scope is created. The 'isolate' scope differs from
normal scope that it does not prototypically inherit from the parent scope. This is useful
when creating reusable components, which should not accidentally read or modify data in
normal scope in that it does not prototypically inherit from the parent scope. This is useful
when creating reusable components, which should not accidentally read or modify data in the
parent scope. <br/>
The 'isolate' scope takes an object hash which defines a set of local scope properties
derived from the parent scope. These local properties are useful for aliasing values for
templates. Locals definition is a hash of normalized element attribute name to their
corresponding binding strategy. Valid binding strategies are:
templates. Locals definition is a hash of local scope property to its source:
* `attribute` - one time read of element attribute value and save it to widget scope. <br/>
Given `<widget my-attr='abc'>` and widget definition of `scope: {myAttr:'attribute'}`,
then widget scope property `myAttr` will be `"abc"`.
* `@` or `@attr` - bind a local scope property to the value of DOM attribute. The result is
always a string since DOM attributes are strings. If no `attr` name is specified then the
attribute name is assumed to be the same as the local name.
Given `<widget my-attr="hello {{name}}">` and widget definition
of `scope: { localName:'@myAttr' }`, then widget scope property `localName` will reflect
the interpolated value of `hello {{name}}`. As the `name` attribute changes so will the
`localName` property on the widget scope. The `name` is read from the parent scope (not
component scope).
* `evaluate` - one time evaluation of expression stored in the attribute. <br/> Given
`<widget my-attr='name'>` and widget definition of `scope: {myAttr:'evaluate'}`, and
parent scope `{name:'angular'}` then widget scope property `myAttr` will be `"angular"`.
* `=` or `=attr` - set up bi-directional binding between a local scope property and the
parent scope property of name defined via the value of the `attr` attribute. If no `attr`
name is specified then the attribute name is assumed to be the same as the local name.
Given `<widget my-attr="parentModel">` and widget definition of
`scope: { localModel:'=myAttr' }`, then widget scope property `localModel` will reflect the
value of `parentModel` on the parent scope. Any changes to `parentModel` will be reflected
in `localModel` and any changes in `localModel` will reflect in `parentModel`.
* `bind` - Set up one way binding from the element attribute to the widget scope. <br/>
Given `<widget my-attr='{{name}}'>` and widget definition of `scope: {myAttr:'bind'}`,
and parent scope `{name:'angular'}` then widget scope property `myAttr` will be
`"angular"`, but any changes in the parent scope will be reflected in the widget scope.
* `accessor` - Set up getter/setter function for the expression in the widget element
attribute to the widget scope. <br/> Given `<widget my-attr='name'>` and widget definition
of `scope: {myAttr:'prop'}`, and parent scope `{name:'angular'}` then widget scope
property `myAttr` will be a function such that `myAttr()` will return `"angular"` and
`myAttr('new value')` will update the parent scope `name` property. This is useful for
treating the element as a data-model for reading/writing.
* `expression` - Treat element attribute as an expression to be executed on the parent scope.
<br/>
Given `<widget my-attr='doSomething()'>` and widget definition of `scope:
{myAttr:'expression'}`, and parent scope `{doSomething:function() {}}` then calling the
widget scope function `myAttr` will execute the expression against the parent scope.
* `&` or `&attr` - provides a way to execute an expression in the context of the parent scope.
If no `attr` name is specified then the attribute name is assumed to be the same as the
local name. Given `<widget my-attr="count = count + value">` and widget definition of
`scope: { localFn:'&myAttr' }`, then isolate scope property `localFn` will point to
a function wrapper for the `count = count + value` expression. Often it's desirable to
pass data from the isolated scope via an expression and to the parent scope, this can be
done by passing a map of local variable names and values into the expression wrapper fn.
For example, if the expression is `increment(amount)` then we can specify the amount value
by calling the `localFn` as `localFn({amount: 22})`.
* `controller` - Controller constructor function. The controller is instantiated before the
pre-linking phase and it is shared with other directives if they request it by name (see
`require` attribute). This allows the directives to communicate with each other and augment
each other behavior. The controller is injectable with the following locals:
each other's behavior. The controller is injectable with the following locals:
* `$scope` - Current scope associated with the element
* `$element` - Current element
* `$attrs` - Current attributes obeject for the element
* `$attrs` - Current attributes object for the element
* `$transclude` - A transclude linking function pre-bound to the correct transclusion scope:
`function(cloneLinkingFn)`.
To avoid errors after minification the bracket notation should be used:
<pre>
controller: ['$scope', '$element', '$attrs', '$transclude', function($scope, $element, $attrs, $transclude) { ... }]
</pre>
* `require` - Require another controller be passed into current directive linking function. The
`require` takes a name of the directive controller to pass in. If no such controller can be
found an error is raised. The name can be prefixed with:
@@ -369,32 +382,6 @@ compiler}. The attributes are:
* `^` - Look for the controller on parent elements as well.
* `inject` (object hash) - Specifies a way to inject bindings into a controller. Injection
definition is a hash of normalized element attribute names to their corresponding binding
strategy. Valid binding strategies are:
* `attribute` - inject attribute value. <br/>
Given `<widget my-attr='abc'>` and widget definition of `inject: {myAttr:'attribute'}`, then
`myAttr` will inject `"abc"`.
* `evaluate` - inject one time evaluation of expression stored in the attribute. <br/>
Given `<widget my-attr='name'>` and widget definition of `inject: {myAttr:'evaluate'}`, and
parent scope `{name:'angular'}` then `myAttr` will inject `"angular"`.
* `accessor` - inject a getter/setter function for the expression in the widget element
attribute to the widget scope. <br/>
Given `<widget my-attr='name'>` and widget definition of `inject: {myAttr:'prop'}`, and
parent scope `{name:'angular'}` then injecting `myAttr` will inject a function such
that `myAttr()` will return `"angular"` and `myAttr('new value')` will update the parent
scope `name` property. This is usefull for treating the element as a data-model for
reading/writing.
* `expression` - Inject expression function. <br/>
Given `<widget my-attr='doSomething()'>` and widget definition of
`inject: {myAttr:'expression'}`, and parent scope `{doSomething:function() {}}` then
injecting `myAttr` will inject a function which when called will execute the expression
against the parent scope.
* `restrict` - String of subset of `EACM` which restricts the directive to a specific directive
declaration style. If omitted directives are allowed on attributes only.
@@ -404,19 +391,19 @@ compiler}. The attributes are:
* `M` - Comment: `<!-- directive: my-directive exp -->`
* `template` - replace the current element with the contents of the HTML. The replacement process
migrates all of the attributes / classes from the old element to the new one. See Creating
Widgets section below for more information.
migrates all of the attributes / classes from the old element to the new one. See the
{@link guide/directive#Components Creating Components} section below for more information.
* `templateURL` - Same as `template` but the template is loaded from the specified URL. Because
* `templateUrl` - Same as `template` but the template is loaded from the specified URL. Because
the template loading is asynchronous the compilation/linking is suspended until the template
is loaded.
* `replace` - if set to `true` then the template will replace the current element, rather then
* `replace` - if set to `true` then the template will replace the current element, rather than
append the template to the element.
* `transclude` - compile the content of the element and make it available to the directive.
Typically used with {@link api/angular.module.ng.$compileProvider.directive.ng-transclude
ng-transclude}. The advantage of transclusion is that the linking function receives a
Typically used with {@link api/ng.directive:ngTransclude
ngTransclude}. The advantage of transclusion is that the linking function receives a
transclusion function which is pre-bound to the correct scope. In a typical setup the widget
creates an `isolate` scope, but the transclusion is not a child, but a sibling of the `isolate`
scope. This makes it possible for the widget to have private state, and the transclusion to
@@ -437,31 +424,31 @@ compiler}. The attributes are:
function compile(tElement, tAttrs, transclude) { ... }
</pre>
Compile function deals with transforming the template DOM. Since most directives do not do
template transformation, it is not used often. Examples which require compile functions are
directives which transform template DOM such as {@link
angular.module.ng.$compileProvider.directive.ng-repeat ng-repeat} or load the contents
asynchronously such as {@link angular.module.ng.$compileProvider.directive.ng-view ng-view}. The
compile functions takes the following arguments.
The compile function deals with transforming the template DOM. Since most directives do not do
template transformation, it is not used often. Examples that require compile functions are
directives that transform template DOM, such as {@link
api/ng.directive:ngRepeat ngRepeat}, or load the contents
asynchronously, such as {@link api/ng.directive:ngView ngView}. The
compile function takes the following arguments.
* `tElement` - template element - The element where the directive has been declared. It is
safe to do template transformation on the element and child elements only.
* `tAttrs` - template attributes - Normalized list of attributes declared on this element shared
between all directive compile functions. See {@link
#Attributes Attributes}
guide/directive#Attributes Attributes}.
* `transclude` - A transclude linking function: `function(scope, cloneLinkingFn)`.
NOTE: The template instance and the link instance may not be the same objects if the template has
been cloned. For this reason it is not safe in the compile function to do anything other the DOM
been cloned. For this reason it is not safe in the compile function to do anything other than DOM
transformation that applies to all DOM clones. Specifically, DOM listener registration should be
done in a linking function rather than in a compile function.
A compile function can have a return value which can be either a function or an object.
* returning a function - is equivalent to registering the linking function via the `link` property
of the config object when the compile function is empty.
* returning a (post-link) function - is equivalent to registering the linking function via the
`link` property of the config object when the compile function is empty.
* returning an object with function(s) registered via `pre` and `post` properties - allows you to
control when a linking function should be called during the linking phase. See info about
@@ -474,19 +461,20 @@ A compile function can have a return value which can be either a function or an
function link(scope, iElement, iAttrs, controller) { ... }
</pre>
Link function is responsible for registering DOM listeners as well as updating the DOM. It is
The link function is responsible for registering DOM listeners as well as updating the DOM. It is
executed after the template has been cloned. This is where most of the directive logic will be
put.
* `scope` - {@link angular.module.ng.$rootScope.Scope Scope} - The scope to be used by the
directive for registering {@link angular.module.ng.$rootScope.Scope#$watch watches}.
* `scope` - {@link api/ng.$rootScope.Scope Scope} - The scope to be used by the
directive for registering {@link api/ng.$rootScope.Scope#$watch watches}.
* `iElement` - instance element - The element where the directive is to be used. It is safe to
manipulate the children of the element only in `postLink` function since the children have
already been linked.
* `iAttrs` - instance attributes - Normalized list of attributes declared on this element shared
between all directive linking functions. See {@link #Attributes Attributes}
between all directive linking functions. See {@link
guide/directive#Attributes Attributes}.
* `controller` - a controller instance - A controller instance if at least one directive on the
element defines a controller. The controller is shared among all the directives, which allows
@@ -501,16 +489,16 @@ compiler linking function will fail to locate the correct elements for linking.
### 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>
## Attributes
The attributes object - passed as a parameter in the link() or compile() functions - is a way of
accessing:
The {@link api/ng.$compile.directive.Attributes Attributes} object - passed as a parameter in the
link() or compile() functions - is a way of accessing:
* *normalized attribute names:* Since a directive such as 'ngBind' can be expressed in many ways
sucha s as 'ng:bind', or 'x-ng-bind', the attributes object allows for a normalize accessed to
such as 'ng:bind', or 'x-ng-bind', the attributes object allows for normalized access to
the attributes.
* *directive inter-communication:* All directives share the same instance of the attributes
@@ -555,6 +543,7 @@ dialog component may work.
on-ok="show = false; doSomething()">
Body goes here: {{username}} is {{title}}.
</dialog>
</div>
</pre>
Clicking on the "show" button will open the dialog. The dialog will have a title, which is
@@ -564,7 +553,7 @@ into the dialog.
Here is an example of what the template definition for the `dialog` widget may look like.
<pre>
<div ng-show="show()">
<div ng-show="visible">
<h3>{{title}}</h3>
<div class="body" ng-transclude></div>
<div class="footer">
@@ -576,18 +565,18 @@ Here is an example of what the template definition for the `dialog` widget may l
This will not render properly, unless we do some scope magic.
The first issue we have to solve is that the dialog box template expect `title` to be defined, but
the place of instantiation would like to bind to `username`. Furthermore the buttons expect `onOk`
as well as `onCancel` functions to be present in the scope. This limits the usefulness of the
The first issue we have to solve is that the dialog box template expects `title` to be defined, but
the place of instantiation would like to bind to `username`. Furthermore the buttons expect the
`onOk` and `onCancel` functions to be present in the scope. This limits the usefulness of the
widget. To solve the mapping issue we use the `locals` to create local variables which the template
expects as follows:
<pre>
scope: {
title: 'bind', // set up title to accept data-binding
onOk: 'exp', // create a delegate onOk function
onCancel: 'exp', // create a delegate onCancel function
show: 'prop' // create a getter/setter function for visibility.
title: '@', // the title uses the data-binding from the parent scope
onOk: '&', // create a delegate onOk function
onCancel: '&', // create a delegate onCancel function
visible: '=' // set up visible to accept data-binding
}
</pre>
@@ -605,12 +594,12 @@ To solve the issue of lack of isolation, the directive declares a new `isolated`
isolated scope does not prototypically inherit from the child scope, and therefore we don't have
to worry about accidentally clobbering any properties.
However 'isolated' scope creates a new problem: if a transcluded DOM is a child of the widget
However `isolated` scope creates a new problem: if a transcluded DOM is a child of the widget
isolated scope then it will not be able to bind to anything. For this reason the transcluded scope
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.
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.
Therefore the final directive definition looks something like this:
@@ -618,13 +607,16 @@ Therefore the final directive definition looks something like this:
<pre>
transclude: true,
scope: {
title: 'bind', // set up title to accept data-binding
onOk: 'exp', // create a delegate onOk function
onCancel: 'exp', // create a delegate onCancel function
show: 'prop' // create a getter/setter function for visibility.
}
title: '@', // the title uses the data-binding from the parent scope
onOk: '&', // create a delegate onOk function
onCancel: '&', // create a delegate onCancel function
visible: '=' // set up visible to accept data-binding
},
restrict: 'E',
replace: true
</pre>
<a name="Components"></a>
# Creating Components
It is often desirable to replace a single directive with a more complex DOM structure. This
@@ -633,7 +625,6 @@ can be built.
Following is an example of building a reusable widget.
<doc:example module="zippyModule">
<doc:source>
<script>
@@ -649,17 +640,17 @@ Following is an example of building a reusable widget.
// This HTML will replace the zippy directive.
replace: true,
transclude: true,
scope: { zippyTitle:'bind' },
scope: { title:'@zippyTitle' },
template: '<div>' +
'<div class="title">{{zippyTitle}}</div>' +
'<div class="title">{{title}}</div>' +
'<div class="body" ng-transclude></div>' +
'</div>',
// The linking function will add behavior to the template
link: function(scope, element, attrs) {
// Title element
// Title element
var title = angular.element(element.children()[0]),
// Opened / closed state
opened = true;
// Opened / closed state
opened = true;
// Clicking on title should open/close the zippy
title.bind('click', toggle);
+186
View File
@@ -0,0 +1,186 @@
@ngdoc overview
@name Developer Guide: Expressions
@description
Expressions are JavaScript-like code snippets that are usually placed in bindings such as `{{
expression }}`. Expressions are processed by the {@link api/ng.$parse $parse}
service.
For example, these are all valid expressions in angular:
* `1+2`
* `3*10 | currency`
* `user.name`
## Angular Expressions vs. JS Expressions
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.
You can think of Angular expressions as JavaScript expressions with following differences:
* **Attribute Evaluation:** evaluation of all properties are against the scope, doing the
evaluation, unlike in JavaScript where the expressions are evaluated against the global
`window`.
* **Forgiving:** expression evaluation is forgiving to `undefined` and `null`, unlike in JavaScript,
where trying to evaluate undefined properties can generate `ReferenceError` or `TypeError`.
* **No Control Flow Statements:** you cannot do any of the following in angular expression:
conditionals, loops, or throw.
* **Filters:** you can pass result of expression evaluations through filter chains. For example
to convert date object into a local specific human-readable format.
If, on the other hand, you do want to run arbitrary JavaScript code, you should make it a
controller method and call the method. If you want to `eval()` an angular expression from
JavaScript, use the {@link api/ng.$rootScope.Scope#$eval `$eval()`} method.
## Example
<doc:example>
<doc:source>
1+2={{1+2}}
</doc:source>
<doc:scenario>
it('should calculate expression in binding', function() {
expect(binding('1+2')).toEqual('3');
});
</doc:scenario>
</doc:example>
You can try evaluating different expressions here:
<doc:example>
<doc:source>
<script>
function Cntl2($scope) {
var exprs = $scope.exprs = [];
$scope.expr = '3*10|currency';
$scope.addExp = function(expr) {
exprs.push(expr);
};
$scope.removeExp = function(index) {
exprs.splice(index, 1);
};
}
</script>
<div ng-controller="Cntl2" class="expressions">
Expression:
<input type='text' ng-model="expr" size="80"/>
<button ng-click="addExp(expr)">Evaluate</button>
<ul>
<li ng-repeat="expr in exprs">
[ <a href="" ng-click="removeExp($index)">X</a> ]
<tt>{{expr}}</tt> => <span ng-bind="$parent.$eval(expr)"></span>
</li>
</ul>
</div>
</doc:source>
<doc:scenario>
it('should allow user expression testing', function() {
element('.expressions :button').click();
var li = using('.expressions ul').repeater('li');
expect(li.count()).toBe(1);
expect(li.row(0)).toEqual(["3*10|currency", "$30.00"]);
});
</doc:scenario>
</doc:example>
# Property Evaluation
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
`$window`} to refer to the global `window` object. For example, if you want to call `alert()`, which is
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).
<doc:example>
<doc:source>
<script>
function Cntl1($window, $scope){
$scope.name = 'World';
$scope.greet = function() {
($window.mockWindow || $window).alert('Hello ' + $scope.name);
}
}
</script>
<div class="example2" ng-controller="Cntl1">
Name: <input ng-model="name" type="text"/>
<button ng-click="greet()">Greet</button>
</div>
</doc:source>
<doc:scenario>
it('should calculate expression in binding', function() {
var alertText;
this.addFutureAction('set mock', function($window, $document, done) {
$window.mockWindow = {
alert: function(text){ alertText = text; }
};
done();
});
element(':button:contains(Greet)').click();
expect(this.addFuture('alert text', function(done) {
done(null, alertText);
})).toBe('Hello World');
});
</doc:scenario>
</doc:example>
## Forgiving
Expression evaluation is forgiving to undefined and null. In JavaScript, evaluating `a.b.c` throws
an exception if `a` is not an object. While this makes sense for a general purpose language, the
expression evaluations are primarily used for data binding, which often look like this:
{{a.b.c}}
It makes more sense to show nothing than to throw an exception if `a` is undefined (perhaps we are
waiting for the server response, and it will become defined soon). If expression evaluation wasn't
forgiving we'd have to write bindings that clutter the code, for example: `{{((a||{}).b||{}).c}}`
Similarly, invoking a function `a.b.c()` on undefined or null simply returns undefined.
## No Control Flow Statements
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
conditional, loop, or to throw from a view expression, delegate to a JavaScript method instead.
## Filters
When presenting data to the user, you might need to convert the data from its raw format to a
user-friendly format. For example, you might have a data object that needs to be formatted
according to the locale before displaying it to the user. You can pass expressions through a chain
of filters like this:
name | uppercase
The expression evaluator simply passes the value of name to {@link
api/ng.filter:uppercase `uppercase`} filter.
Chain filters using this syntax:
value | filter1 | filter2
You can also pass colon-delimited arguments to filters, for example, to display the number 123
with 2 decimal points:
123 | number:2
# The $
You might be wondering, what is the significance of the $ prefix? It is simply a prefix that
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.
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
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
so that angular developers and developers who use Angular can develop in harmony without collisions.
@@ -1,9 +1,9 @@
@ngdoc overview
@name Developer Guide: Forms
@name Forms
@description
Controls (`input`, `select`, `textarea`) are a way for user to enter data.
Form is a collection of controls for the purpose of grouping related controls together.
Controls (`input`, `select`, `textarea`) are ways for a user to enter data.
A Form is a collection of controls for the purpose of grouping related controls together.
Form and controls provide validation services, so that the user can be notified of invalid input.
This provides a better user experience, because the user gets instant feedback on how to correct the error.
@@ -12,15 +12,15 @@ Server-side validation is still necessary for a secure application.
# Simple form
The key directive in understanding two-way data-binding is {@link api/angular.module.ng.$compileProvider.directive.ng-model ng-model}.
The `ng-model` 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/angular.module.ng.$compileProvider.directive.ng-model.NgModelController API} for other directives to augment its behavior.
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.
In addition it provides an {@link api/ng.directive:ngModel.NgModelController API} for other directives to augment its behavior.
<doc:example>
<doc:source>
<div ng-controller="Controller">
<form novalidate class="simple-form">
Name: <input type="text" ng-model="user.name" ng-model-instant /><br />
Name: <input type="text" ng-model="user.name" /><br />
E-mail: <input type="email" ng-model="user.email" /><br />
Gender: <input type="radio" ng-model="user.gender" value="male" />male
<input type="radio" ng-model="user.gender" value="female" />female<br />
@@ -31,7 +31,7 @@ In addition it provides {@link api/angular.module.ng.$compileProvider.directive.
<pre>master = {{master | json}}</pre>
</div>
<script type="text/javascript">
<script>
function Controller($scope) {
$scope.master= {};
@@ -50,24 +50,20 @@ In addition it provides {@link api/angular.module.ng.$compileProvider.directive.
</doc:example>
Note that:
* the {@link api/angular.module.ng.$compileProvider.directive.ng-model-instant ng-model-instant} causes the `user.name` to be updated immediately.
* `novalidate` is used to disable browser's native form validation.
Note that `novalidate` is used to disable browser's native form validation.
# Using CSS classes
To allow styling of form as well as controls, `ng-model` add these CSS classes:
To allow styling of form as well as controls, `ngModel` add these CSS classes:
- `ng-valid`
- `ng-invalid`
- `ng-pristine`
- `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.
This ensures that the user is not distracted with an error until after interacting with the control, and failing to satisfy its validity.
@@ -76,7 +72,7 @@ This ensures that the user is not distracted with an error until after interacti
<div ng-controller="Controller">
<form novalidate class="css-form">
Name:
<input type="text" ng-model="user.name" ng-model-instant required /><br />
<input type="text" ng-model="user.name" required /><br />
E-mail: <input type="email" ng-model="user.email" required /><br />
Gender: <input type="radio" ng-model="user.gender" value="male" />male
<input type="radio" ng-model="user.gender" value="female" />female<br />
@@ -95,12 +91,12 @@ This ensures that the user is not distracted with an error until after interacti
}
</style>
<script type="text/javascript">
<script>
function Controller($scope) {
$scope.master= {};
$scope.master = {};
$scope.update = function(user) {
$scope.master= angular.copy(user);
$scope.master = angular.copy(user);
};
$scope.reset = function() {
@@ -117,9 +113,9 @@ This ensures that the user is not distracted with an error until after interacti
# Binding to form and control state
A form is in instance of {@link api/angular.module.ng.$compileProvider.directive.form.FormController FormController}.
A form is an instance of {@link api/ng.directive:form.FormController FormController}.
The form instance can optionally be published into the scope using the `name` attribute.
Similarly control is an instance of {@link api/angular.module.ng.$compileProvider.directive.ng-model.NgModelController NgModelController}.
Similarly control is an instance of {@link api/ng.directive:ngModel.NgModelController NgModelController}.
The control instance can similarly be published into the form instance using the `name` attribute.
This implies that the internal state of both the form and the control is available for binding in the view using the standard binding primitives.
@@ -147,21 +143,21 @@ This allows us to extend the above example with these features:
<input type="checkbox" ng-model="user.agree" name="userAgree" required />
I agree: <input ng-show="user.agree" type="text" ng-model="user.agreeSign"
ng-model-instant required /><br />
required /><br />
<div ng-show="!user.agree || !user.agreeSign">Please agree and sign.</div>
<button ng-click="reset()" disabled="{{isUnchanged(user)}}">RESET</button>
<button ng-click="reset()" ng-disabled="isUnchanged(user)">RESET</button>
<button ng-click="update(user)"
disabled="{{form.$invalid || isUnchanged(user)}}">SAVE</button>
ng-disabled="form.$invalid || isUnchanged(user)">SAVE</button>
</form>
</div>
<script type="text/javascript">
<script>
function Controller($scope) {
$scope.master= {};
$scope.master = {};
$scope.update = function(user) {
$scope.master= angular.copy(user);
$scope.master = angular.copy(user);
};
$scope.reset = function() {
@@ -182,30 +178,30 @@ This allows us to extend the above example with these features:
# Custom Validation
Angular provides basic implementation for most common html5 {@link api/angular.module.ng.$compileProvider.directive.input input}
types: ({@link api/angular.module.ng.$compileProvider.directive.input.text text}, {@link api/angular.module.ng.$compileProvider.directive.input.number number}, {@link api/angular.module.ng.$compileProvider.directive.input.url url}, {@link api/angular.module.ng.$compileProvider.directive.input.email email}, {@link api/angular.module.ng.$compileProvider.directive.input.radio radio}, {@link api/angular.module.ng.$compileProvider.directive.input.checkbox checkbox}), as well as some directives for validation (`required`, `pattern`, `minlength`, `maxlength`, `min`, `max`).
Angular provides basic implementation for most common html5 {@link api/ng.directive:input input}
types: ({@link api/ng.directive:input.text text}, {@link api/ng.directive:input.number number}, {@link api/ng.directive:input.url url}, {@link api/ng.directive:input.email email}, {@link api/ng.directive:input.radio radio}, {@link api/ng.directive:input.checkbox checkbox}), as well as some directives for validation (`required`, `pattern`, `minlength`, `maxlength`, `min`, `max`).
Defining your own validator can be done by defining your own directive which adds a custom validation function to the `ng-model` {@link api/angular.module.ng.$compileProvider.directive.ng-model.NgModelController controller}.
Defining your own validator can be done by defining your own directive which adds a custom validation function to the `ngModel` {@link api/ng.directive:ngModel.NgModelController controller}.
To get a hold of the controller the directive specifies a dependency as shown in the example below.
The validation can occur in two places:
* **Model to View update** -
Whenever the bound model changes, all functions in {@link api/angular.module.ng.$compileProvider.directive.ng-model.NgModelController#$formatters NgModelController#$formatters} array are pipe-lined, so that each of these functions has an opportunity to format the value and change validity state of the form control through {@link api/angular.module.ng.$compileProvider.directive.ng-model.NgModelController#$setValidity NgModelController#$setValidity}.
Whenever the bound model changes, all functions in {@link api/ng.directive:ngModel.NgModelController#$formatters NgModelController#$formatters} array are pipe-lined, so that each of these functions has an opportunity to format the value and change validity state of the form control through {@link api/ng.directive:ngModel.NgModelController#$setValidity NgModelController#$setValidity}.
* **View to Model update** -
In a similar way, whenever a user interacts with a control, the controll calls {@link api/angular.module.ng.$compileProvider.directive.ng-model.NgModelController#$setViewValue NgModelController#$setViewValue}.
This in turn pipelines all functions in {@link api/angular.module.ng.$compileProvider.directive.ng-model.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/angular.module.ng.$compileProvider.directive.ng-model.NgModelController#$setValidity NgModelController#$setValidity}.
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 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.
* 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.
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.
* The second directive is a `smart-float`.
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">
@@ -231,7 +227,7 @@ In the following example we create two directives.
</form>
</div>
<script type="text/javascript">
<script>
var app = angular.module('form-example1', []);
var INTEGER_REGEXP = /^\-?\d*$/;
@@ -276,22 +272,22 @@ In the following example we create two directives.
</doc:example>
# Implementing custom form control (using ng-model)
Angular implements all of the basic HTML form controls ({@link api/angular.module.ng.$compileProvider.directive.input input}, {@link api/angular.module.ng.$compileProvider.directive.select select}, {@link api/angular.module.ng.$compileProvider.directive.textarea textarea}), which should be sufficient for most cases.
# 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.
However, if you need more flexibility, you can write your own form control as a directive.
In order for custom control to work with `ng-model` and to achieve two-way data-binding it needs to:
In order for custom control to work with `ngModel` and to achieve two-way data-binding it needs to:
- implement `render` method, which is responsible for rendering the data after it passed the {@link api/angular.module.ng.$compileProvider.directive.ng-model.NgModelController#$formatters NgModelController#$formatters},
- implement `$render` method, which is responsible for rendering the data after it passed the {@link api/ng.directive:ngModel.NgModelController#$formatters NgModelController#$formatters},
- call `$setViewValue` method, whenever the user interacts with the control and model needs to be updated. This is usually done inside a DOM Event listener.
See {@link api/angular.module.ng.$compileProvider.directive $compileProvider.directive} for more info.
See {@link guide/directive $compileProvider.directive} for more info.
The following example shows how to add two-way data-binding to contentEditable elements.
<doc:example module="form-example2">
<doc:source>
<script type="text/javascript">
<script>
angular.module('form-example2', []).directive('contenteditable', function() {
return {
require: 'ngModel',
@@ -304,8 +300,8 @@ The following example shows how to add two-way data-binding to contentEditable e
});
// model -> view
ctrl.render = function(value) {
elm.html(value);
ctrl.$render = function() {
elm.html(ctrl.$viewValue);
};
// load init value from DOM
@@ -17,15 +17,15 @@ abstracted bits.
**What level of support for i18n/l10n is currently in Angular?**
Currently, Angular supports i18n/l10n for {@link
http://docs.angularjs.org/#!/api/angular.module.ng.$filter.date datetime}, {@link
http://docs.angularjs.org/#!/api/angular.module.ng.$filter.number number} and {@link
http://docs.angularjs.org/#!/api/angular.module.ng.$filter.currency currency} filters.
http://docs.angularjs.org/#!/api/ng.filter:date datetime}, {@link
http://docs.angularjs.org/#!/api/ng.filter:number number} and {@link
http://docs.angularjs.org/#!/api/ng.filter:currency currency} filters.
Additionally, Angular supports localizable pluralization support provided by the {@link
api/angular.module.ng.$compileProvider.directive.ng-pluralize ng-pluralize directive}.
api/ng.directive:ngPluralize ngPluralize directive}.
All localizable Angular components depend on locale-specific rule sets managed by the {@link
api/angular.module.ng.$locale $locale service}.
api/ng.$locale $locale service}.
For readers who want to jump straight into examples, we have a few web pages that showcase how to
use Angular filters with various locale rule sets. You can find these examples either on {@link
@@ -53,25 +53,25 @@ There are two approaches to providing locale rules to Angular:
You can pre-bundle the desired locale file with Angular by concatenating the content of the
locale-specific file to the end of `angular.js` or `angular.min.js` file.
For example on *nix, to create a an angular.js file that contains localization rules for german
For example on *nix, to create an angular.js file that contains localization rules for german
locale, you can do the following:
`cat angular.js i18n/angular-locale_de-ge.js > angular_de-ge.js`
`cat angular.js i18n/angular-locale_de-de.js > angular_de-de.js`
When the application containing `angular_de-ge.js` script instead of the generic angular.js script
When the application containing `angular_de-de.js` script instead of the generic angular.js script
starts, Angular is automatically pre-configured with localization rules for the german locale.
**2. Including locale js script in index.html page**
You can also include the locale specific js file in the index.html page. For example, if one client
requires German locale, you would serve index_de-ge.html which will look something like this:
requires German locale, you would serve index_de-de.html which will look something like this:
<pre>
<html ng-app>
<head>
….
<script src="angular.js"></script>
<script src="i18n/angular-locale_de-ge.js"></script>
<script src="i18n/angular-locale_de-de.js"></script>
….
</head>
</html>
@@ -90,8 +90,8 @@ because an extra script needs to be loaded.
**Currency symbol "gotcha"**
Angular's {@link http://docs.angularjs.org/#!/api/angular.module.ng.$filter.currency currency filter} allows
you to use the default currency symbol from the {@link api/angular.module.ng.$locale locale service},
Angular's {@link http://docs.angularjs.org/#!/api/ng.filter:currency currency filter} allows
you to use the default currency symbol from the {@link api/ng.$locale locale service},
or you can provide the filter with a custom currency symbol. If your app will be used only in one
locale, it is fine to rely on the default currency symbol. However, if you anticipate that viewers
in other locales might use your app, you should provide your own currency symbol to make sure the
@@ -104,7 +104,7 @@ browser will specify the locale as ja, and the balance of '¥1000.00' will be sh
will really upset your client.
In this case, you need to override the default currency symbol by providing the {@link
http://docs.angularjs.org/#!/api/angular.module.ng.$filter.currency currency filter} with a currency symbol as
http://docs.angularjs.org/#!/api/ng.filter:currency currency filter} with a currency symbol as
a parameter when you configure the filter, for example, {{ 1000 | currency:"USD$"}}. This way,
Angular will always show a balance of 'USD$1000' and disregard any locale changes.
+59 -34
View File
@@ -5,43 +5,68 @@
# Overview
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.
# 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 **do not** use custom element tags such as `<ng:view>` (use the attribute version `<div
ng-view>` instead), or
1. You polyfill JSON.stringify if necessary (IE7 will need this). You can use
[JSON2](https://github.com/douglascrockford/JSON-js) or
[JSON3](http://bestiejs.github.com/json3/) polyfills for this.
<pre>
<!doctype html>
<html xmlns:ng="http://angularjs.org">
<head>
<!--[if lte IE 8]>
<script src="/path/to/json2.js"></script>
<![endif]-->
</head>
<body>
...
</body>
</html>
</pre>
2. if you **do use** custom element tags, then you must take these steps to make IE happy:
2. add `id="ng-app"` to the root element in conjunction with `ng-app` attribute
<pre>
<!doctype html>
<html xmlns:ng="http://angularjs.org" id="ng-app" ng-app="optionalModuleName">
...
</html>
</pre>
<pre>
<html xmlns:ng="http://angularjs.org">
<head>
<!--[if lte IE 8]>
<script>
document.createElement('ng-include');
document.createElement('ng-pluralize');
document.createElement('ng-view');
// Optionally these for CSS
document.createElement('ng:include');
document.createElement('ng:pluralize');
document.createElement('ng:view');
</script>
<![endif]-->
</head>
<body>
...
</body>
</html>
</pre>
3. you **do not** use custom element tags such as `<ng:view>` (use the attribute version
`<div ng-view>` instead), or
4. if you **do use** custom element tags, then you must take these steps to make IE happy:
<pre>
<!doctype html>
<html xmlns:ng="http://angularjs.org" id="ng-app" ng-app="optionalModuleName">
<head>
<!--[if lte IE 8]>
<script>
document.createElement('ng-include');
document.createElement('ng-pluralize');
document.createElement('ng-view');
// Optionally these for CSS
document.createElement('ng:include');
document.createElement('ng:pluralize');
document.createElement('ng:view');
</script>
<![endif]-->
</head>
<body>
...
</body>
</html>
</pre>
The **important** parts are:
* `xmlns:ng` - *namespace* - you need one namespace for each custom tay you are planning on
* `xmlns:ng` - *namespace* - you need one namespace for each custom tag you are planning on
using.
* `document.createElement(yourTagName)` - *creation of custom tag names* - Since this is an
@@ -52,7 +77,7 @@ The **important** parts are:
# Long Version
IE has an issues with element tag names which are not standard HTML tag names. These fall into two
IE has issues with element tag names which are not standard HTML tag names. These fall into two
categories, and each category has its own fix.
* If the tag name starts with `my:` prefix than it is considered an XML namespace and must
@@ -61,13 +86,13 @@ categories, and each category has its own fix.
* If the tag has no `:` but it is not a standard HTML tag, then it must be pre-created using
`document.createElement('my-tag')`
* If you have are planning on styling the custom tag with CSS selectors, then it must be
* If you are planning on styling the custom tag with CSS selectors, then it must be
pre-created using `document.createElement('my-tag')` regardless of XML namespace.
## The Good News
The good news is that these restrictions only apply to element tag names, and not to element
The good news is that these restrictions only apply to element tag names, and not to element
attribute names. So this requires no special handling in IE: `<div my-tag your:tag></div>`.
@@ -84,7 +109,7 @@ result):
</html>
</pre>
It should pares into the following DOM:
It should parse into the following DOM:
<pre>
#document
@@ -118,12 +143,12 @@ In IE, the behavior is that the `BODY` element has three children:
3. A corrupt self closing `/mytag`. This is corrupt since element names are not allowed to have
the `/` character. Furthermore this closing element should not be part of the DOM since it is
only used to delimitate the structure of the DOM.
only used to delineate the structure of the DOM.
## CSS Styling of Custom Tag Names
The to make CSS selector work with custom elements the custom element name must be shived with the
To make CSS selectors work with custom elements, the custom element name must be pre-created with
`document.createElement('my-tag')` regardless of XML namespace.
<pre>
@@ -133,7 +158,7 @@ The to make CSS selector work with custom elements the custom element name must
<script>
// needed to make ng-include parse properly
document.createElement('ng-include');
// needed to enable CSS reference
document.createElement('ng:view');
</script>
+1 -42
View File
@@ -2,7 +2,7 @@
@name Developer Guide
@description
Welcome to the angular Developer Guide. If you are here to learn the details of how to use angular
Welcome to the angular Developer Guide. If you are here to learn the details of how to use angular
to develop web apps, you've come to the right place.
If you are completely or relatively unfamiliar with angular, you may want to check out one or both
@@ -10,44 +10,3 @@ of the following documents before returning here to the Developer Guide:
* {@link misc/started Getting Started}
* {@link tutorial/index Angular Tutorial}
<hr>
## {@link dev_guide.overview Overview of Angular}
## {@link dev_guide.bootstrap Initializing Angular}
* {@link dev_guide.bootstrap.auto_bootstrap Understanding Automatic Initialization}
* {@link dev_guide.bootstrap.manual_bootstrap Understanding Manual Initialization}
## {@link dev_guide.mvc About MVC in Angular}
* {@link dev_guide.mvc.understanding_model Understanding the Model Component}
* {@link dev_guide.mvc.understanding_controller Understanding the Controller Component}
* {@link dev_guide.mvc.understanding_view Understanding the View Component}
## {@link dev_guide.scopes Angular Scope Objects}
* {@link dev_guide.scopes.understanding_scopes Understanding Angular Scope Objects}
* {@link dev_guide.scopes.internals Angular Scope Internals}
## {@link dev_guide.compiler Angular HTML Compiler}
* {@link api/angular.module.ng.$compileProvider.directive Understanding Angular Directives}
## {@link dev_guide.templates Angular Templates}
* {@link dev_guide.templates.filters Understanding Angular Filters}
* {@link dev_guide.forms Understanding Angular Forms}
## {@link dev_guide.services Angular Services}
* {@link dev_guide.services.understanding_services Understanding Angular Services}
* {@link dev_guide.services.creating_services Creating Angular Services}
* {@link dev_guide.services.managing_dependencies Managing Service Dependencies}
* {@link dev_guide.services.testing_services Testing Angular Services}
## {@link dev_guide.di About Dependency Injection}
* {@link dev_guide.di.understanding_di Understanding DI in Angular}
* {@link dev_guide.di.using_di_controllers Using DI in Controllers}
@@ -3,40 +3,40 @@
@description
Angular is pure client-side technology, written entirely in JavaScript. It works with the
long-established technologies of the web (HTML, CSS, and JavaScript) to make the development of web
apps easier and faster than ever before.
long-established technologies of the web (HTML, CSS, and JavaScript) to make the development of
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
care of many of these tasks, including:
* DOM Manipulation
* Setting Up Listeners and Notifiers
* Input Validation
* DOM Manipulation
* Setting Up Listeners and Notifiers
* 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.
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:
* Separation of data, application logic, and presentation components
* Data Binding between data and presentation components
* Services (common web app operations, implemented as substitutable objects)
* Dependency Injection (used primarily for wiring together services)
* An extensible HTML compiler (written entirely in JavaScript)
* Ease of Testing
* Separation of data, application logic, and presentation components
* Data Binding between data and presentation components
* Services (common web app operations, implemented as substitutable objects)
* Dependency Injection (used primarily for wiring together services)
* An extensible HTML compiler (written entirely in JavaScript)
* Ease of Testing
These techniques have been for the most part absent from the client-side for far too long.
## 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
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
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
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'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
to a single-page angular app.
to a single-page Angular app.
+37 -20
View File
@@ -5,9 +5,8 @@
# What is a Module?
Most applications have a main method which instantiates, wires, and bootstraps the application.
Angular apps don't have a main method, instead the modules serves the purpose of declaratively
specifying how an application should be bootstrapped. There are several advantages to this
approach:
Angular apps don't have a main method. Instead modules declaratively specify how an application
should be bootstrapped. There are several advantages to this approach:
* The process is more declarative which is easier to understand
* In unit-testing there is no need to load all modules, which may aid in writing unit-tests.
@@ -19,7 +18,7 @@ approach:
# The Basics
Ok, I'm in a hurry how do i get a Hello World module working?
Ok, I'm in a hurry. How do I get a Hello World module working?
Important things to notice:
@@ -27,15 +26,15 @@ Important things to notice:
* Notice the reference to the `myApp` module in the `<html ng-app="myApp">`, it is what
bootstraps the app using your module.
<doc:example module='simpleApp'>
<doc:example module='myApp'>
<doc:source>
<script>
// declare a module
var simpleAppModule = angular.module('simpleApp', []);
var myAppModule = angular.module('myApp', []);
// configure the module.
// in this example we will create a greeting filter
simpleAppModule.filter('greet', function() {
myAppModule.filter('greet', function() {
return function(name) {
return 'Hello, ' + name + '!';
};
@@ -62,9 +61,9 @@ that you break your application to multiple modules like this:
initialization code.
The reason for this breakup is that in your tests, it is often necessary to ignore the
initialization code, which tends to be difficult to test. By putting it into separate module it
initialization code, which tends to be difficult to test. By putting it into a separate module it
can be easily ignored in tests. The tests can also be more focused by only loading the modules
which are relevant to tests.
that are relevant to tests.
The above is only a suggestion, so feel free to tailor it to your needs.
@@ -139,7 +138,7 @@ angular.module('myModule', []).
// This is an example of a run block.
// You can have as many of these as you want.
// You can only inject instances (not Providers)
// int the run blocks
// into the run blocks
});
</pre>
@@ -159,9 +158,9 @@ angular.module('myModule', []).
angular.module('myModule', []).
config(function($provide, $compileProvider, $filterProvider) {
$provide.value('a', 123)
$provide.factory('a', function() { return 123; })
$compileProvider.directive('directiveName', ...).
$provide.value('a', 123);
$provide.factory('a', function() { return 123; });
$compileProvider.directive('directiveName', ...);
$filterProvider.register('filterName', ...);
});
</pre>
@@ -181,7 +180,7 @@ ignored in the unit-tests.
Modules can list other modules as their dependencies. Depending on a module implies that required
module needs to be loaded before the requiring module is loaded. In other words the configuration
blocks of the required modules execute before the configuration blocks or the requiring module.
blocks of the required modules execute before the configuration blocks of the requiring module.
The same is true for the run blocks. Each module can only be loaded once, even if multiple other
modules require it.
@@ -190,12 +189,30 @@ modules require it.
Modules are a way of managing $injector configuration, and have nothing to do with loading of
scripts into a VM. There are existing projects which deal with script loading, which may be used
with Angular. Because modules do nothing at load time they can be loaded into the VM in any order
and thus script loaders can take advantage of this property and paralyze the loading process.
and thus script loaders can take advantage of this property and parallelize the loading process.
## Creation versus Retrieval
Beware that using `angular.module('myModule', [])` will create the module `myModule` and overwrite any
existing module named `myModule`. Use `angular.module('myModule')` to retrieve an existing module.
<pre>
var myModule = angular.module('myModule', []);
// add some directives and services
myModule.service('myService', ...);
myModule.directive('myDirective', ...);
// overwrites both myService and myDirective by creating a new module
var myModule = angular.module('myModule', []);
// throws an error because myOtherModule has yet to be defined
var myModule = angular.module('myOtherModule');
</pre>
# 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
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
@@ -223,8 +240,8 @@ In all of these examples we are going to assume this module definition:
Let's write some tests:
<pre>
describe('myApp', function() {
// load the application relevant modules then load a special
// test module which overrides the $window with mock version,
// load the relevant application modules then load a special
// test module which overrides the $window with a mock version,
// so that calling window.alert() will not block the test
// runner with a real alert box. This is an example of overriding
// configuration information in tests.
@@ -232,7 +249,7 @@ describe('myApp', function() {
$provide.value('$window', {
alert: jasmine.createSpy('alert')
});
});
}));
// The inject() will create the injector and inject the greet and
// $window into the tests. The test need not concern itself with
@@ -251,7 +268,7 @@ describe('myApp', function() {
});
inject(function(greet) {
greet('World');
expect(alertSpy).toHaveBeenCalledWith('World');
expect(alertSpy).toHaveBeenCalledWith('Hello World!');
});
});
});
+207
View File
@@ -0,0 +1,207 @@
@ngdoc overview
@name Developer Guide: Overview
@description
# What Is Angular?
AngularJS is a structural framework for dynamic web apps. It lets you use HTML as your template
language and lets you extend HTML's syntax to express your application's components clearly and
succinctly. Out of the box, it eliminates much of the code you currently write through data
binding and dependency injection. And it all happens in JavaScript within the browser, making it
an ideal partner with any server technology.
Angular is what HTML would have been had it been designed for applications. HTML is a great
declarative language for static documents. It does not contain much in the way of creating
applications, and as a result building web applications is an exercise in *what do I have to do
to trick the browser into doing what I want.*
The impedance mismatch between dynamic applications and static documents is often solved with:
* **a 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`.
* **frameworks** - a particular implementation of a web application, where your code fills in
the details. The framework is in charge and it calls into your code when it needs something
app specific. E.g., `knockout`, `ember`, etc.
Angular takes another approach. It attempts to minimize the impedance mismatch between document
centric HTML and what an application needs by creating new HTML constructs. Angular teaches the
browser new syntax through a construct we call directives. Examples include:
* Data binding, as in `{{}}`.
* DOM control structures for repeating/hiding DOM fragments.
* Support for forms and form validation.
* Attaching code-behind to DOM elements.
* Grouping of HTML into reusable components.
## A complete client-side solution
Angular is not a single piece in the overall puzzle of building the client-side of a web
application. It handles all of the DOM and AJAX glue code you once wrote by hand and puts it in a
well-defined structure. This makes Angular opinionated about how a CRUD application should be
built. But while it is opinionated, it also tries to make sure that its opinion is just a
starting point you can easily change. Angular comes with the following out-of-the-box:
* Everything you need to build a CRUD app in a cohesive set: data-binding, basic templating
directives, form validation, routing, deep-linking, reusable components, dependency injection.
* Testability story: unit-testing, end-to-end testing, mocks, test harnesses.
* Seed application with directory layout and test scripts as a starting point.
## Angular Sweet Spot
Angular simplifies application development by presenting a higher level of abstraction to the
developer. Like any abstraction, it comes at a cost of flexibility. In other words not every app
is a good fit for Angular. Angular was built for the CRUD application in mind. Luckily CRUD
applications represent the majority of web applications. But to understand what Angular is
good at one also has to understand when an app is not a good fit for Angular.
Games and GUI editors are examples of applications with intensive and tricky DOM manipulation.
These kinds of apps are different from CRUD apps, and as a result are probably not a good fit for Angular.
In these cases it may be better to use a library with a lower level of abstraction, such as `jQuery`.
# An Introductory Angular Example
Below is a typical CRUD application which contains a form. The form values are validated, and
are used to compute the total, which is formatted to a particular locale. These are some common
concepts which the application developer may face:
* attaching data-model to the UI.
* writing, reading and validating user input.
* computing new values based on the model.
* formatting output in a user specific locale.
<example>
<file name="script.js">
function InvoiceCntl($scope) {
$scope.qty = 1;
$scope.cost = 19.95;
}
</file>
<file name="index.html">
<div ng-controller="InvoiceCntl">
<b>Invoice:</b>
<br>
<br>
<table>
<tr><td>Quantity</td><td>Cost</td></tr>
<tr>
<td><input type="number" ng-pattern="/\d+/" step="1" min="0" ng-model="qty" required ></td>
<td><input type="number" ng-model="cost" required ></td>
</tr>
</table>
<hr>
<b>Total:</b> {{qty * cost | currency}}
</div>
</file>
<file name="scenario.js">
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');
});
</file>
</example>
Try out the Live Preview above, and then let's walk through the example and describe what's going
on.
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
bootstrap auto initialize} your application.
<html ng-app>
We load Angular using the `<script>` tag:
<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
binding, and we also demonstrate some easy input validation:
Quantity: <input type="number" ng-pattern="/\d+/" step="1" min="0" ng-model="qty" required >
Cost: <input type="number" ng-model="cost" required >
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
variables of the same name. Think of those variables as the "Model" component of the
Model-View-Controller design pattern.
* Note that the HTML widget {@link api/ng.directive:input input}
has special powers. The input invalidates itself by turning red when you enter invalid data or
leave the input fields blank. These new widget behaviors make it easier to implement field
validation common in CRUD applications.
And finally, the mysterious `{{ double curly braces }}`:
Total: {{qty * cost | currency}}
This notation, `{{ _expression_ }}`, is Angular markup for data-binding. The expression itself can
be a combination of both an expression and a {@link dev_guide.templates.filters filter}: `{{
expression | filter }}`. Angular provides filters for formatting display data.
In the example above, the expression in double-curly braces directs Angular to "bind the data we
got from the input widgets to the display, multiply them together, and format the resulting number
into output that looks like money."
Notice that we achieved this application behavior not by calling Angular methods, nor by
implementing application specific behavior as a framework. We achieved the behavior because the
browser behaved more in line with what is needed for a dynamic web application rather than what is
needed for a static document. Angular has lowered the impedance mismatch to the point where no
library/framework calls are needed.
# The Zen of 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 excellent for
expressing business logic.
* 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.
Angular frees you from the following pains:
* **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 programmatically:** 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 programmatically manipulate the
DOM, although you can if you want to.
* **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, 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.
# Watch a Presentation About Angular
Here is a presentation on Angular from May 2012. The {@link http://mhevery.github.io/angular-demo-slides/index.html#/list corresponding slides} are also available.
<iframe width="560" height="315" src="http://www.youtube.com/embed/bfrn5VNpwsg" frameborder="0" allowfullscreen></iframe>
+331
View File
@@ -0,0 +1,331 @@
@ngdoc overview
@name Developer Guide: Scopes
@description
# What are Scopes?
{@link api/ng.$rootScope.Scope scope} is an object that refers to the application
model. It is an execution context for {@link expression expressions}. Scopes are
arranged in hierarchical structure which mimic the DOM structure of the application. Scopes can
watch {@link guide/expression expressions} and propagate events.
## Scope characteristics
- Scopes provide APIs ({@link api/ng.$rootScope.Scope#$watch $watch}) to observe
model mutations.
- Scopes provide APIs ({@link api/ng.$rootScope.Scope#$apply $apply}) to
propagate any model changes through the system into the view from outside of the "Angular
realm" (controllers, services, Angular event handlers).
- Scopes can be nested to isolate application components while providing access to shared model
properties. A scope (prototypically) inherits properties from its parent scope.
- Scopes provide context against which {@link guide/expression expressions} are evaluated. For
example `{{username}}` expression is meaningless, unless it is evaluated against a specific
scope which defines the `username` property.
## Scope as Data-Model
Scope is the glue between application controller and the view. During the template {@link compiler
linking} phase the {@link api/ng.$compileProvider#directive directives} set up
{@link api/ng.$rootScope.Scope#$watch `$watch`} expressions on the scope. The
`$watch` allows the directives to be notified of property changes, which allows the directive to
render the updated value to the DOM.
Both controllers and directives have reference to the scope, but not to each other. This
arrangement isolates the controller from the directive as well as from DOM. This is an important
point since it makes the controllers view agnostic, which greatly improves the testing story of
the applications.
<example>
<file name="script.js">
function MyController($scope) {
$scope.username = 'World';
$scope.sayHello = function() {
$scope.greeting = 'Hello ' + $scope.username + '!';
};
}
</file>
<file name="index.html">
<div ng-controller="MyController">
Your name:
<input type="text" ng-model="username">
<button ng-click='sayHello()'>greet</button>
<hr>
{{greeting}}
</div>
</file>
</example>
In the above example notice that the `MyController` assigns `World` to the `username` property of
the scope. The scope then notifies the `input` of the assignment, which then renders the input
with username pre-filled. This demonstrates how a controller can write data into the scope.
Similarly the controller can assign behavior to scope as seen by the `sayHello` method, which is
invoked when the user clicks on the 'greet' button. The `sayHello` method can read the `username`
property and create a `greeting` property. This demonstrates that the properties on scope update
automatically when they are bound to HTML input widgets.
Logically the rendering of `{{greeting}}` involves:
* retrieval of the scope associated with DOM node where `{{greeting}}` is defined in template.
In this example this is the same scope as the scope which was passed into `MyController`. (We
will discuss scope hierarchies later.)
* Evaluate the `greeting` {@link guide/expression expression} against the scope retrieved above,
and assign the result to the text of the enclosing DOM element.
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.
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.
<pre>
it('should say hello', function() {
var scopeMock = {};
var cntl = new MyController(scopeMock);
// Assert that username is pre-filled
expect(scopeMock.username).toEqual('World');
// Assert that we read new username and greet
scopeMock.username = 'angular';
scopeMock.sayHello();
expect(scopeMock.greeting).toEqual('Hello angular!');
});
</pre>
## Scope Hierarchies
Each Angular application has exactly one {@link api/ng.$rootScope root scope}, but
may have several child scopes.
The application can have multiple scopes, because some {@link guide/directive directives} create
new child scopes (refer to directive documentation to see which directives create new scopes).
When new scopes are created, they are added as children of their parent scope. This creates a tree
structure which parallels the DOM where they're attached
When Angular evaluates `{{username}}`, it first looks at the scope associated with the given
element for the `username` property. If no such property is found, it searches the parent scope
and so on until the root scope is reached. In JavaScript this behavior is known as prototypical
inheritance, and child scopes prototypically inherit from their parents.
This example illustrates scopes in application, and prototypical inheritance of properties.
<example>
<file name="style.css">
/* remove .doc-example-live in jsfiddle */
.doc-example-live .ng-scope {
border: 1px dashed red;
}
</file>
<file name="script.js">
function EmployeeController($scope) {
$scope.department = 'Engineering';
$scope.employee = {
name: 'Joe the Manager',
reports: [
{name: 'John Smith'},
{name: 'Mary Run'}
]
};
}
</file>
<file name="index.html">
<div ng-controller="EmployeeController">
Manager: {{employee.name}} [ {{department}} ]<br>
Reports:
<ul>
<li ng-repeat="employee in employee.reports">
{{employee.name}} [ {{department}} ]
</li>
</ul>
<hr>
{{greeting}}
</div>
</file>
</example>
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
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
evaluation of `{{department}}` prototypically inherits from root scope, as it is the only place
where the `department` property is defined.
## Retrieving Scopes from the DOM.
Scopes are attached to the DOM as `$scope` data property, and can be retrieved for debugging
purposes. (It is unlikely that one would need to retrieve scopes in this way inside the
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
`ng-app` is placed on 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.
To examine the scope in the debugger:
1. right click on the element of interest in your browser and select 'inspect element'. You
should see the browser debugger with the element you clicked on highlighted.
2. The debugger allows you to access the currently selected element in the console as `$0`
variable.
3. To retrieve the associated scope in console execute: `angular.element($0).scope()`
## Scope Events Propagation
Scopes can propagate events in similar fashion to DOM events. The event can be {@link
api/ng.$rootScope.Scope#$broadcast broadcasted} to the scope children or {@link
api/ng.$rootScope.Scope#$emit emitted} to scope parents.
<example>
<file name="script.js">
function EventController($scope) {
$scope.count = 0;
$scope.$on('MyEvent', function() {
$scope.count++;
});
}
</file>
<file name="index.html">
<div ng-controller="EventController">
Root scope <tt>MyEvent</tt> count: {{count}}
<ul>
<li ng-repeat="i in [1]" ng-controller="EventController">
<button ng-click="$emit('MyEvent')">$emit('MyEvent')</button>
<button ng-click="$broadcast('MyEvent')">$broadcast('MyEvent')</button>
<br>
Middle scope <tt>MyEvent</tt> count: {{count}}
<ul>
<li ng-repeat="item in [1, 2]" ng-controller="EventController">
Leaf scope <tt>MyEvent</tt> count: {{count}}
</li>
</ul>
</li>
</ul>
</div>
</file>
</example>
## Scope Life Cycle
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
more events.
When the browser calls into JavaScript the code executes outside the Angular execution context,
which means that Angular is unaware of model modifications. To properly process model
modifications the execution has to enter the Angular execution context using the {@link
api/ng.$rootScope.Scope#$apply `$apply`} method. Only model modifications which
execute inside the `$apply` method will be properly accounted for by Angular. For example if a
directive listens on DOM events, such as {@link
api/ng.directive:ngClick `ng-click`} it must evaluate the
expression inside the `$apply` method.
After evaluating the expression, the `$apply` method performs a {@link
api/ng.$rootScope.Scope#$digest `$digest`}. In the $digest phase the scope examines all
of the `$watch` expressions and compares them with the previous value. This dirty checking is done
asynchronously. This means that assignment such as `$scope.username="angular"` will not
immediately cause a `$watch` to be notified, instead the `$watch` notification is delayed until
the `$digest` phase. This delay is desirable, since it coalesces multiple model updates into one
`$watch` notification as well as it guarantees that during the `$watch` notification no other
`$watch`es are running. If a `$watch` changes the value of the model, it will force additional
`$digest` cycle.
1. **Creation**
The {@link api/ng.$rootScope root scope} is created during the application
bootstrap by the {@link api/AUTO.$injector $injector}. During template
linking, some directives create new child scopes.
2. **Watcher registration**
During template linking directives register {@link
api/ng.$rootScope.Scope#$watch watches} on the scope. These watches will be
used to propagate model values to the DOM.
3. **Model mutation**
For mutations to be properly observed, you should make them only within the {@link
api/ng.$rootScope.Scope#$apply scope.$apply()}. (Angular APIs do this
implicitly, so no extra `$apply` call is needed when doing synchronous work in controllers,
or asynchronous work with {@link api/ng.$http $http} or {@link
api/ng.$timeout $timeout} services.
4. **Mutation observation**
At the end `$apply`, Angular performs a {@link api/ng.$rootScope.Scope#$digest
$digest} cycle on the root scope, which then propagates throughout all child scopes. During
the `$digest` cycle, all `$watch`ed expressions or functions are checked for model mutation
and if a mutation is detected, the `$watch` listener is called.
5. **Scope destruction**
When child scopes are no longer needed, it is the responsibility of the child scope creator
to destroy them via {@link api/ng.$rootScope.Scope#$destroy scope.$destroy()}
API. This will stop propagation of `$digest` calls into the child scope and allow for memory
used by the child scope models to be reclaimed by the garbage collector.
### Scopes and Directives
During the compilation phase, the {@link compiler compiler} matches {@link
api/ng.$compileProvider#directive directives} against the DOM template. The directives
usually fall into one of two categories:
- Observing {@link api/ng.$compileProvider#directive directives}, such as
double-curly expressions `{{expression}}`, register listeners using the {@link
api/ng.$rootScope.Scope#$watch $watch()} method. This type of directive needs
to be notified whenever the expression changes so that it can update the view.
- Listener directives, such as {@link api/ng.directive:ngClick
ng-click}, register a listener with the DOM. When the DOM listener fires, the directive
executes the associated expression and updates the view using the {@link
api/ng.$rootScope.Scope#$apply $apply()} method.
When an external event (such as a user action, timer or XHR) is received, the associated {@link
expression expression} must be applied to the scope through the {@link
api/ng.$rootScope.Scope#$apply $apply()} method so that all listeners are updated
correctly.
### Directives that Create Scopes
In most cases, {@link api/ng.$compileProvider#directive directives} and scopes interact
but do not create new instances of scope. However, some directives, such as {@link
api/ng.directive:ngController ng-controller} and {@link
api/ng.directive:ngRepeat ng-repeat}, create new child scopes
and attach the child scope to the corresponding DOM element. You can retrieve a scope for any DOM
element by using an `angular.element(aDomElement).scope()` method call.
### Controllers and Scopes
Scopes and controllers interact with each other in the following situations:
- Controllers use scopes to expose controller methods to templates (see {@link
api/ng.directive:ngController ng-controller}).
- Controllers define methods (behavior) that can mutate the model (properties on the scope).
- Controllers may register {@link api/ng.$rootScope.Scope#$watch watches} on
the model. These watches execute immediately after the controller behavior executes.
See the {@link api/ng.directive:ngController ng-controller} for more
information.
### Scope `$watch` Performance Considerations
Dirty checking the scope for property changes is a common operation in Angular and for this reason
the dirty checking function must be efficient. Care should be taken that the dirty checking
function does not do any DOM access, as DOM access is orders of magnitude slower then property
access on JavaScript object.
+104 -77
View File
@@ -13,19 +13,19 @@
<a name="H1_1"></a>
# License
`Angular` is an open source project licensed under the {@link
AngularJS is an open source project licensed under the {@link
http://github.com/angular/angular.js/blob/master/LICENSE MIT license}. Your contributions are
always welcome. When working with `angular` source base, please follow the guidelines provided on
always welcome. When working with AngularJS code base, please follow the guidelines provided on
this page.
<a name="H1_2"></a>
# Contributing to Source Code
We'd love for you to contribute to our source code and to make `angular` even better than it is
today! Here are the guidelines we'd like you to use:
We'd love for you to contribute to our source code and to make AngularJS even better than it is
today! Here are the guidelines we'd like you to follow:
* Major changes that you intend to contribute to the project must be discussed first on our {@link
* Major changes that you intend to contribute to the project should be discussed first on our {@link
https://groups.google.com/forum/?hl=en#!forum/angular mailing list} so that we can better
coordinate our efforts, prevent duplication of work, and help you to craft the change so that it
is successfully accepted upstream.
@@ -64,46 +64,44 @@ inheritance only when absolutely necessary.
external API. See our existing code to see what we mean.
* We don't go crazy with type annotations for private internal APIs unless it's an internal API
that is used throughout `angular`. The best guidance is to do what makes the most sense.
that is used throughout AngularJS. The best guidance is to do what makes the most sense.
<a name="H1_4"></a>
# Checking Out and Building Angular
The `angular` source code is hosted at {@link http://github.com Github}, which we also use to
accept code contributions. Several steps are needed to check out and build `angular`:
The AngularJS source code is hosted at {@link http://github.com Github}, which we also use to
accept code contributions. The AngularJS repository can be found at **<https://github.com/angular/angular.js>**.
Several steps are needed to check out and build AngularJS:
## Installation Dependencies
Before you can build `angular`, you must install or configure the following dependencies on your
Before you can build AngularJS, you must install or configure the following dependencies on your
machine:
* {@link http://rake.rubyforge.org Rake}: We use Rake as our build system, which is pre-installed
on most Macintosh and Linux machines. If that is not true in your case, you can grab it from the
Rake website.
* {@link http://nodejs.org Node.js}: We use Node to generate the documentation and to run a
development web server. Depending on your system, you can install Node either from source or as a
pre-packaged bundle.
You'll also need npm and the following npm modules:
* install npm: `curl http://npmjs.org/install.sh | sh`
* install q: `npm install q`
* install qq: `npm install qq`
* install q-fs: `npm install q-fs`
* install jasmine-node: `npm install jasmine`
* Java: The Java runtime is used to run {@link http://code.google.com/p/js-test-driver
JsTestDriver} (JSTD), which we use to run our unit test suite. JSTD binaries are part of the
`angular` source base, which means there is no need to install or configure it separately.
* Git: The {@link http://help.github.com/mac-git-installation Github Guide to Installing Git} is
quite a good source for information on Git.
* {@link http://nodejs.org Node.js}: We use Node to generate the documentation, run a
development web server, run tests, and generate a build. Depending on your system, you can install Node either from source or as a
pre-packaged bundle.
* {@link http://www.java.com Java}: JavaScript is minified using
{@link https://developers.google.com/closure/ Closure Tools} jar. Make sure you have Java (version 6 or higher) installed
and included in your {@link http://docs.oracle.com/javase/tutorial/essential/environment/paths.html PATH} variable.
Once installed, you'll also need several npms (node packages), which you can install once you checked out a local copy
of the Angular repository (see below) with:
* `cd angular.js`
* `npm install`
* {@link http://gruntjs.com Grunt}: We use Grunt as our build system. Install the grunt command-line tool globally with:
* `sudo npm install -g grunt-cli`
## Creating a Github Account and Forking Angular
@@ -112,31 +110,39 @@ Afterwards, go ahead and {@link http://help.github.com/forking fork} the {@link
https://github.com/angular/angular.js main angular repository}.
## Building `Angular`
## Building AngularJS
To build `angular`, you check out the source code and use Rake to generate the non-minified and
minified `angular` files:
To build AngularJS, you check out the source code and use Grunt to generate the non-minified and
minified AngularJS files:
1. To clone your Github repository, run:
git clone git@github.com:<github username>/angular.js.git
2. To go to the `angular` directory, run:
2. To go to the AngularJS directory, run:
cd angular.js
3. To add the main `angular` repository as an upstream remote to your repository, run:
3. To add the main AngularJS repository as an upstream remote to your repository, run:
git remote add upstream https://github.com/angular/angular.js.git
4. To build `angular`, run:
4. To add node.js dependencies
npm install
5. To build AngularJS, run:
grunt package
NOTE: If you're using Windows you must run your command line with administrative privileges (right click, run as
Administrator).
rake package
The build output can be located under the `build` directory. It consists of the following files and
directories:
* `angular-<version>.tgz` — This is the complete tarball, which contains all of the release build
* `angular-<version>.zip` — This is the complete zip file, which contains all of the release build
artifacts.
* `angular.js` — The non-minified `angular` script.
@@ -145,8 +151,6 @@ artifacts.
* `angular-scenario.js` — The `angular` End2End test runner.
* `angular-ie-compat.js` — The Internet Explorer compatibility patch file.
* `docs/` — A directory that contains all of the files needed to run `docs.angularjs.org`.
* `docs/index.html` — The main page for the documentation.
@@ -154,60 +158,78 @@ artifacts.
* `docs/docs-scenario.html` — The End2End test runner for the documentation application.
<a name="webserver"></a>
## Running a Local Development Web Server
To debug or test code, it is often useful to have a local HTTP server. For this purpose, we have
To debug code and run end-to-end tests, it is often useful to have a local HTTP server. For this purpose, we have
made available a local web server based on Node.js.
1. To start the web server, run:
./nodeserver.sh
grunt webserver
2. To access the local server, go to this website:
http://localhost:8000/
By default, it serves the contents of the `angular` project directory.
By default, it serves the contents of the AngularJS project directory.
<a name="unit-tests"></a>
## Running the Unit Test Suite
Our unit and integration tests are written with Jasmine and executed with JsTestDriver. To run the
tests:
Our unit and integration tests are written with Jasmine and executed with Karma. To run all of the
tests once on Chrome run:
1. To start the JSTD server, run:
grunt test:unit
./server.sh
To run the tests on other browsers (Chrome, ChromeCanary, Firefox, Opera and Safari are pre-configured) use:
2. To capture one or more browsers, go to this website:
grunt test:unit --browsers Opera,Firefox
Note there should be _no spaces between browsers_. `Opera, Firefox` is INVALID.
During development it's however more productive to continuously run unit tests every time the source or test files
change. To execute tests in this mode run:
1. To start the Karma server, capture Chrome browser and run unit tests, run:
grunt autotest:jqlite
2. To capture more browsers, open this url in the desired browser (url might be different if you have multiple instance
of Karma running, read Karma's console output for the correct url):
http://localhost:9876/
3. To trigger a test execution, run:
./test.sh
4. To automatically run the test suite each time one or more of the files in the project directory
is changed, you can install `watchr` and then run:
watchr watchr.rb
5. To view the output of each test run, you can tail this log file:
./logs/jstd.log
3. To re-run tests just change any source or test file.
## Running the End2End Test Suite
To learn more about all of the preconfigured Grunt tasks run:
To run the End2End test suite:
grunt --help
## Running the end-to-end Test Suite
To run the E2E test suite:
1. Start the local web server if it's not running already.
grunt webserver
1. Start the local web server.
2. In a browser, go to:
http://localhost:8000/build/docs/docs-scenario.html
The tests are executed automatically.
or in terminal run:
grunt test:end2end
For convenience you can also simply run:
grunt test:e2e
This will start the webserver for you and run the tests.
@@ -216,31 +238,36 @@ To run the End2End test suite:
To create and submit a change:
1. Create a new branch off the master for your changes:
1. <a name="CLA"></a>
Please sign our Contributor License Agreement (CLA) before sending pull requests. For any code changes to be
accepted, the CLA must be signed. It's a quick process, we promise!
git branch my-fix-branch
For individuals we have a [simple click-through form](http://code.google.com/legal/individual-cla-v1.0.html). For
corporations we'll need you to
[print, sign and one of scan+email, fax or mail the form](http://code.google.com/legal/corporate-cla-v1.0.html).
2. Check out the branch:
git checkout my-fix-branch
2. Create and checkout a new branch off the master branch for your changes:
git checkout -b my-fix-branch master
3. Create your patch, make sure to have plenty of tests (that pass).
4. Commit your changes:
4. Commit your changes and create a descriptive commit message (the commit message is used to generate release notes,
please check out our
[commit message conventions](https://docs.google.com/document/d/1QrDFcIiPjSLDn3EL15IJygNPiHORgU1_OOAqWjiDU5Y/edit#)
and our commit message presubmit hook `validate-commit-msg.js`):
git commit -a
5. Run JavaScript Lint and be sure to address all new warnings and errors:
rake lint
6. Push your branch to Github:
5. Push your branch to Github:
git push origin my-fix-branch
7. In Github, send a pull request to `angular:master`.
6. In Github, send a pull request to `angular:master`.
8. When the patch is reviewed and merged, delete your branch and pull yours — and other — changes
7. When the patch is reviewed and merged, delete your branch and pull yours — and other — changes
from the main (upstream) repository:
1. To delete the branch in Github, run:
+24 -19
View File
@@ -2,10 +2,9 @@
@name Downloading
@description
# Including angular scripts from the angular server
The quickest way to get started is to point your html `<script>` tag to a
<http://code.angularjs.org/> URL. This way, you don't have to download anything or maintain a
local copy.
# Including angular scripts from the Google CDN
The quickest way to get started is to point your html `<script>` tag to a Google CDN URL.
This way, you don't have to download anything or maintain a local copy.
There are two types of angular script URLs you can point to, one for development and one for
production:
@@ -15,21 +14,25 @@ development.
* __angular-<version>.min.js__ — This is the minified version, which we strongly suggest you use in
production.
To point your code to an angular script on the angular server, use the following template. This
example points to (non-minified) version 0.10.6:
To point your code to an angular script on the Google CDN server, use the following template. This
example points to the minified version 1.0.2:
<pre>
<!doctype html>
<html ng-app>
<head>
<title>My Angular App</title>
<script src="http://code.angularjs.org/angular-0.10.6.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.0.2/angular.min.js"></script>
</head>
<body>
</body>
</html>
</pre>
Note that only versions 1.0.1 and above are available on the CDN, if you need an earlier version
you can use the <http://code.angularjs.org/> URL which was the previous recommended location for
hosted code source. If you're still using the angular server you should switch to the CDN version
for even faster loading times.
# Downloading and hosting angular files locally
This option is for those who want to work with angular offline, or those who want to host the
@@ -42,29 +45,31 @@ Download the version you want and have fun.
Each directory under <http://code.angularjs.org/> includes the following set of files:
* __`angular-<version>.js`__ — This file is non-obfuscated, non-minified, and human-readable by
* __`angular.js`__ — This file is non-obfuscated, non-minified, and human-readable by
opening it it any editor or browser. In order to get better error messages during development, you
should always use this non-minified angular script.
* __`angular-<version>.min.js`__ — This is a minified and obfuscated version of
`angular-<version>.js` created with the Closure compiler. Use this version for production in order
* __`angular.min.js`__ — This is a minified and obfuscated version of
`angular.js` created with the Closure compiler. Use this version for production in order
to minimize the size of the application that is downloaded by your user's browser.
* __`angular-<version>.tgz`__ — This is a tarball archive that contains all of the files released
* __`angular.zip`__ — This is a zip archive that contains all of the files released
for this angular version. Use this file to get everything in a single download.
* __`angular-ie-compat-<version>.js`__ — This is a special file that contains code and data
specifically tailored for getting Internet Explorer to work with angular. If you host your own copy
of angular files, make sure that this file is available for download, and that it resides under the
same parent path as `angular-<version>.js` or `angular-<version>.min.js`.
* __`angular-mocks-<version>.js`__ — This file contains an implementation of mocks that makes
* __`angular-mocks.js`__ — This file contains an implementation of mocks that makes
testing angular apps even easier. Your unit/integration test harness should load this file after
`angular-<version>.js` is loaded.
* __`angular-scenario-<version>.js`__ — This file is a very nifty JavaScript file that allows you
* __`angular-scenario.js`__ — This file is a very nifty JavaScript file that allows you
to write and execute end-to-end tests for angular applications.
* __`docs-<version>`__ — this directory contains all the files that compose the
* __`angular-loader.min.js`__ — Module loader for Angular modules. If you are loading multiple script files containing
Angular modules, you can load them asynchronosuly and in any order as long as you load this file first. Often the
contents of this file are copy&pasted into the `index.html` to avoid even the inial request to `angular-loader.min.js`.
See [angular-seed](https://github.com/angular/angular-seed/blob/master/app/index-async.html) for an example of usage.
* __`angular-resource.js`__, __`angular-cookies.js`__, etc - extra Angular modules with additional functionality.
* __`docs`__ — this directory contains all the files that compose the
<http://docs.angularjs.org/> documentation app. These files are handy to see the older version of
our docs, or even more importantly, view the docs offline.
+181 -46
View File
@@ -4,78 +4,213 @@
#FAQ
### Why is this project called "angular"? Why is the namespace called "ng"?
## Questions
Because HTML has angular brackets and "ng" sounds like "angular".
### Why is this project called "AngularJS"? Why is the namespace called "ng"?
### Is <angular/> an HTML5 tag?
Because HTML has Angular brackets and "ng" sounds like "Angular".
No, <angular/> is not an HTML5 tag. angular is an orthogonal project to HTML5; you can use the two
together.
### Is angular a {library, framework, DOM manipulation library, widget library, native plugin}?
### Is AngularJS a library, framework, plugin or a browser extension?
No, angular is none of these. You don't call its functions, it does not call your functions,
it does not provide a way to manipulate DOM, but does provide primitives to create UI projections
of your data. There are lots of existing widget libraries which you can integrate with angular.
It is 100% JavaScript, 100% client side and compatible with both desktop and mobile browsers.
AngularJS fits the definition of a framework the best, even though it's much more lightweight than
a typical framework and that's why many confuse it with a library.
### Do I need to worry about security holes in angular?
AngularJS is 100% JavaScript, 100% client side and compatible with both desktop and mobile browsers.
So it's definitely not a plugin or some other native browser extension.
Like with any technology, angular is not impervious to attack. angular does, however, provide
built-in protection from basic security holes including cross-site scripting and HTML injection
attacks. angular does round-trip escaping on all strings for you.
### Can I download the source, build, and host the angular environment locally?
### Is AngularJS a templating system?
Yes. See instructions in {@link downloading}.
### Is angular a templating system?
At the highest level, angular does look like a just another templating system. But there is one
important reason why angular templating system is different and makes it very good fit for
application development: bidirectional data binding. The template is compiled on the browser and
the compilation step produces a live view. This means you, the developer, don't need to write
At the highest level, Angular does look like a just another templating system. But there is one
important reason why the Angular templating system is different, that makes it very good fit for
application development: bidirectional data binding. The template is compiled in the browser and
the compilation step produces a live view. This means you, the developers, don't need to write
code to constantly sync the view with the model and the model with the view as in other
templating systems.
### What browsers does angular work with?
Webkit-based browsers (Safari, Chrome, iPhone, Android, WebOS, BlackBerry 6), Firefox, IE6 and
above. Note that CSS only works on IE7 and above.
### Do I need to worry about security holes in AngularJS?
### What's angular's performance like?
Like any other technology, AngularJS is not impervious to attack. Angular does, however, provide
built-in protection from basic security holes including cross-site scripting and HTML injection
attacks. AngularJS does round-trip escaping on all strings for you and even offers XSRF protection
for server-side communication.
angular takes ~300ms to load, render, and compile. In Chrome it uses about 2-5MB of memory. Your
app's performance will vary depending on how many bindings you use.
AngularJS was designed to be compatible with other security measures like Content Security Policy
(CSP), HTTPS (SSL/TLS) and server-side authentication and authorization that greatly reduce the
possible attack vectors and we highly recommended their use.
### How big is the angular bootstrap JS file that I need to include?
The size of the library itself is < 50KB compressed and obfuscated.
### Can I download the source, build, and host the AngularJS environment locally?
### Can I use the open-source Closure Library with angular?
Yes. See instructions in {@link downloading}.
### What browsers does Angular work with?
We run our extensive test suite against the following browsers: Safari, Chrome, Firefox, Opera,
IE8, IE9 and mobile browsers (Android, Chrome Mobile, iOS Safari). See {@link guide/ie Internet
Explorer Compatibility} for more details in supporting legacy IE browsers.
### What's Angular's performance like?
The startup time heavily depends on your network connection, state of the cache, browser used and
available hardware, but typically we measure bootstrap time in tens or hundreds of milliseconds.
The runtime performance will vary depending on the number and complexity of bindings on the page
as well as the speed of your backend (for apps that fetch data from the backend). Just for an
illustration we typically build snappy apps with hundreds or thousands of active bindings.
### How big is the angular.js file that I need to include?
The size of the file is < 29KB compressed and minified.
### Can I use the open-source Closure Library with Angular?
Yes, you can use widgets from the {@link http://code.google.com/closure/library Closure Library}
in angular.
in Angular.
### Does angular use the jQuery library?
### Does Angular use the jQuery library?
Yes, angular uses {@link http://jquery.com/ jQuery}, the open source DOM manipulation library.
If jQuery is not present in your script path, angular falls back on its own implementation of
{@link api/angular.element jQuery lite}. If jQuery is present in the path, angular uses it to
manipulate the DOM.
Yes, Angular can use {@link http://jquery.com/ jQuery} if it's present in your app when the
application is being bootstrapped. If jQuery is not present in your script path, Angular falls back
to its own implementation of the subset of jQuery that we call {@link api/angular.element jQLite}.
### What is testability like in angular?
Very testable. It has an integrated dependency injection framework. See
{@link api/angular.module.ng service} for details.
### What is testability like in Angular?
### How can I learn more about angular?
Very testable and designed this way from ground up. It has an integrated dependency injection
framework, provides mocks for many heavy dependencies (server-side communication). See
{@link api/ng service} for details.
Watch the July 28, 2010 talk
"{@link http://www.youtube.com/watch?v=elvcgVSynRg| Angular: A Radically Different Way of Building
AJAX Apps}".
### How is angular licensed?
### How can I learn more about Angular?
Watch the July 17, 2012 talk
"{@link http://www.youtube.com/watch?v=1CpiB3Wk25U AngularJS Intro + Dependency Injection}".
### How is Angular licensed?
The MIT License.
### Can I download and use the Angular logo artwork?
Yes! You can find design files in our github repository, under "{@link https://github.com/angular/angular.js/tree/master/images/logo
angular.js/images/logo}"
The logo design is licensed under a "{@link http://creativecommons.org/licenses/by-sa/3.0/
Creative Commons Attribution-ShareAlike 3.0 Unported License}". If you have some other use in mind, contact us.
### How can I get some AngularJS schwag?
We often bring a few t-shirts and stickers to events where we're presenting. If you want to order your own, the folks who
make our schwag will be happy to do a custom run for you, based on our existing template. By using the design they have on file,
they'll waive the setup costs, and you can order any quantity you need.
**Stickers**
Contact Tom Witting (or anyone in sales) via email at tom@stickergiant.com, and tell him you want to order some AngularJS
stickers just like the ones in job #42711. You'll have to give them your own info for billing and shipping.
As long as the design stays exactly the same, {@link http://www.stickergiant.com StickerGiant} will give you a reorder discount.
## Common Pitfalls
The Angular support channel (#angularjs on Freenode) sees a number of recurring pitfalls that new users of Angular fall into.
This document aims to point them out before you discover them the hard way.
### DOM Manipulation
Stop trying to use jQuery to modify the DOM in controllers. Really.
That includes adding elements, removing elements, retrieving their contents, showing and hiding them.
Use built-in directives, or write your own where necessary, to do your DOM manipulation.
See below about duplicating functionality.
If you're struggling to break the habit, consider removing jQuery from your app.
Really. Angular has the $http service and powerful directives that make it almost always unnecessary.
Angular's bundled jQLite has a handful of the features most commonly used in writing Angular directives, especially binding to events.
### Trying to duplicate functionality that already exists
There's a good chance that your app isn't the first to require certain functionality.
There are a few pieces of Angular that are particularly likely to be reimplemented out of old habits.
**ng-repeat**
`ng-repeat` gets this a lot.
People try to use jQuery (see above) to add more elements to some container as they're fetched from the server.
No, bad dog.
This is what `ng-repeat` is for, and it does its job very well.
Store the data from the server in an array on your `$scope`, and bind it to the DOM with `ng-repeat`.
**ng-show**
`ng-show` gets this frequently too.
Conditionally showing and hiding things using jQuery is a common pattern in other apps, but Angular has a better way.
`ng-show` (and `ng-hide`) conditionally show and hide elements based on boolean expressions.
Describe the conditions for showing and hiding an element in terms of `$scope` variables:
<div ng-show="!loggedIn">Click <a href="#/login">here</a> to log in</div>
Note also the counterpart `ng-hide` and similar `ng-disabled`.
Note especially the powerful `ng-switch` that should be used instead of several mutually exclusive `ng-show`s.
**ng-class**
`ng-class` is the last of the big three.
Conditionally applying classes to elements is another thing commonly done manually using jQuery.
Angular, of course, has a better way.
You can give `ng-class` a whitespace-separated set of class names, and then it's identical to ordinary `class`.
That's not very exciting, so there's a second syntax:
<div ng-class="{ errorClass: isError, warningClass: isWarning, okClass: !isError && !isWarning }">...</div>
Where you give `ng-class` an object, whose keys are CSS class names and whose values are conditional expressions using `$scope` variables.
The element will then have all the classes whose conditions are truthy, and none of those whose conditions are falsy.
Note also the handy `ng-class-even` and `ng-class-odd`, and the related though somewhat different `ng-style`.
### `$watch` and `$apply`
Angular's two-way data binding is the root of all awesome in Angular.
However, it's not magic, and there are some situations where you need to give it a nudge in the right direction.
When you bind a value to an element in Angular using `ng-model`, `ng-repeat`, etc., Angular creates a `$watch` on that value.
Then whenever a value on a scope changes, all `$watch`es observing that element are executed, and everything updates.
Sometimes, usually when you're writing a custom directive, you will have to define your own `$watch` on a scope value to make the directive react to changes.
On the flip side, sometimes you change a scope value in some code but the app doesn't react to it.
Angular checks for scope variable changes after pieces of your code have finished running; for example, when `ng-click` calls a function on your scope, Angular will check for changes and react.
However, some code is outside of Angular and you'll have to call `scope.$apply()` yourself to trigger the update.
This is most commonly seen in event handlers in custom directives.
### Combining `ng-repeat` with other directives
`ng-repeat` is extremely useful, one of the most powerful directives in Angular.
However the transformation it applies to the DOM is substantial.
Therefore applying other directives (such as `ng-show`, `ng-controller` and others) to the same element as `ng-repeat` generally leads to problems.
If you want to apply a directive to the whole repeat, wrap the repeat in a parent element and put it there.
If you want to apply a directive to each inner piece of the repeat, put it on a child of the element with `ng-repeat`.
### `$rootScope` exists, but it can be used for evil
Scopes in Angular form a hierarchy, prototypically inheriting from a root scope at the top of the tree.
Usually this can be ignored, since most views have a controller, and therefore a scope, of their own.
Occasionally there are pieces of data that you want to make global to the whole app.
For these, you can inject `$rootScope` and set values on it like any other scope.
Since the scopes inherit from the root scope, these values will be available to the expressions attached to directives like `ng-show` just like values on your local `$scope`.
Of course, global state sucks and you should use `$rootScope` sparingly, like you would (hopefully) use with global variables in any language.
In particular, don't use it for code, only data.
If you're tempted to put a function on `$rootScope`, it's almost always better to put it in a service that can be injected where it's needed, and more easily tested.
Conversely, don't create a service whose only purpose in life is to store and return bits of data.
+24 -128
View File
@@ -2,142 +2,38 @@
@name Getting Started
@description
# Hello World!
We want you to have an easy time while starting to use Angular. We've put together the following steps on your path to
becoming an Angular expert.
A great way for you to get started with AngularJS is to create the tradtional
"Hello World!" app:
1. In your favorite text editor, create an HTML file
(for example, `helloworld.html`).
2. From the __Source__ box below, copy and paste the code into your HTML file.
(Double-click on the source to easily select all.)
3. Open the file in your web browser.
<doc:example>
<doc:source>
Hello {{'World'}}!
</doc:source>
</doc:example>
The resulting web page should look something like the following:
<img class="center" src="img/helloworld.png" border="1">
Now let's take a closer look at that code, and see what is going on behind
the scenes.
The `ng-app` tags tells angular to process the entire HTML page and bootstrap the app when the page
is loaded:
<pre>
<html ng-app>
</pre>
The next line downloads the angular script:
<pre>
<script src="http://code.angularjs.org/angular-?.?.?.min.js"></script>
</pre>
(For details on what happens when angular processes an HTML page,
see {@link guide/dev_guide.bootstrap Bootstrap}.)
Finally, this line in the `<body>` of the page is the template that describes
how to display our greeting in the UI:
<pre>
Hello {{'World'}}!
</pre>
Note the use of the double curly brace markup (`{{ }}`) to bind the expression to
the greeting text. Here the expression is the string literal 'World'.
Next let's look at a more interesting example, that uses AngularJS to
bind a dynamic expression to our greeting text.
# Hello AngularJS World!
This example demonstrates angular's two-way data binding:
1. Edit the HTML file you created in the "Hello World!" example above.
2. Replace the contents of `<body>` with the code from the __Source__ box below.
3. Refresh your browser window.
<doc:example>
<doc:source>
Your name: <input type="text" ng-model="yourname" value="World"/>
<hr/>
Hello {{yourname}}!
</doc:source>
</doc:example>
After the refresh, the page should look something like this:
<img class="left" src="img/helloworld_2way.png" border="1" />
These are some of the important points to note from this example:
* The text input {@link api/angular.module.ng.$compileProvider.directive directive}
is bound to a model variable called `yourname`.
* The double curly braces notation binds the `yourname` model to the greeting text.
* You did not need to explicitly register an event listener or define an event handler for events!
Now try typing your name into the input box, and notice the immediate change to
the displayed greeting. This demonstrates the concept of angular's
{@link guide/dev_guide.templates.databinding bi-directional data binding}. Any changes to the input
field are immediately
reflected in the model (one direction), and any changes to the model are
reflected in the greeting text (the other direction).
1. Read the {@link guide/concepts conceptual overview}.<br/>Understand Angular's vocabulary and how all the Angular
components work together.
1. Do the {@link tutorial/ AngularJS Tutorial}.<br/>Walk end-to-end through building and application complete with tests
on top of a node.js web server. Covers every major AngularJS feature and show you how to set up your development
environment.
1. Download or clone the {@link https://github.com/angular/angular-seed Seed App project template}.<br/>Gives you a
starter app with a directory layout, test harness, and scripts to begin building your application.
# Anatomy Of An Angular App
#Further Steps
This section describes the 3 parts of an angular app, and explains how they map to the
Model-View-Controller design pattern:
##Watch Videos
## Templates
If you havent had a chance to watch the videos from the homepage, please check out:
Templates, which you write in HTML and CSS, serve as the View. You add elements, attributes, and
markup to HTML, which serve as instructions to the angular compiler. The angular compiler is fully
extensible, meaning that with angular you can build your own declarative language on top of HTML!
* {@link http://www.youtube.com/watch?v=WuiHuZq_cg4&list=PL173F1A311439C05D&context=C48ac877ADvjVQa1PpcFONnl4Q5x8hqvT6tRBTE-m0-Ym47jO3PEE%3D Introduction to AngularJS}
* {@link http://www.youtube.com/watch?v=Yg-R1gchccg&list=PL173F1A311439C05D&context=C48ac877ADvjVQa1PpcFONnl4Q5x8hqvT6tRBTE-m0-Ym47jO3PEE%3D Creating Directives}
* {@link http://www.youtube.com/watch?v=IRelx4-ISbs&list=PL173F1A311439C05D&context=C48ac877ADvjVQa1PpcFONnl4Q5x8hqvT6tRBTE-m0-Ym47jO3PEE%3D Communicating with Servers}
And visit our {@link http://www.youtube.com/user/angularjs YouTube channel} for more AngularJS video presentations and
tutorials.
## Application Logic and Behavior
##Subscribe
Application Logic and Behavior, which you define in JavaScript, serve as the Controller. With
angular (unlike with standard AJAX applications) you don't need to write additional listeners or
DOM manipulators, because they are built-in. This feature makes your application logic very easy to
write, test, maintain, and understand.
* Subscribe to the {@link http://groups.google.com/forum/?fromgroups#!forum/angular mailing list}. Ask questions here!
* Follow us on {@link https://twitter.com/intent/follow?original_referer=http%3A%2F%2Fangularjs.org%2F&region=follow_link&screen_name=angularjs&source=followbutton&variant=2.0 Twitter}
* Add us to your circles on {@link https://plus.google.com/110323587230527980117/posts Google+}
##Read more
## Data
The Model is referenced from properties on {@link guide/dev_guide.scopes angular scope objects}.
The data in your model could be Javascript objects, arrays, or primitives, it doesn't matter. What
matters is that these are all referenced by the scope object.
Angular employs scopes to keep your data model and your UI in sync. Whenever something occurs to
change the state of the model, angular immediately reflects that change in the UI, and vice versa.
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" />
In addition, angular comes with a set of Services, which have the following properties:
* The services provided are very useful for building web applications.
* You can extend and add application-specific behavior to services.
* Services include Dependency-Injection, XHR, caching, URL routing, and browser abstraction.
# Where To Go Next
* If you like what you've learned so far, you should definitely check out our awesome {@link
tutorial/ Tutorial}, which walks you through the process of building real apps with AngularJS.
* For further explanations and examples of the AngularJS concepts presented on this page, see the
{@link guide/index Developer Guide}.
* For additional hands-on examples of using AngularJS, including more source code that you can
copy and paste into your own pages, take a look through the {@link cookbook/ Cookbook}.
The AngularJS documentation includes the {@link guide/index Developer Guide} covering concepts and the
{@link api/ API Reference} for syntax and usage.
+115
View File
@@ -0,0 +1,115 @@
@ngdoc overview
@name Tutorial: Index
@description
A great way to get introduced to AngularJS is to work through this tutorial, which walks you through
the construction of an AngularJS web app. The app you will build is a catalog that displays a list
of Android devices, lets you filter the list to see only devices that interest you, and then view
details for any device.
<img class="diagram" src="img/tutorial/catalog_screen.png" width="488" height="413">
Work through the tutorial to see how Angular makes browsers smarter — without the use of extensions
or plug-ins. As you work through the tutorial, you will:
* See examples of how to use client-side data binding and dependency injection to build dynamic
views of data that change immediately in response to user actions.
* See how Angular creates listeners on your data without the need for DOM manipulation.
* Learn a better, easier way to test your web apps.
* Learn how to use Angular services to make common web tasks, such as getting data into your app,
easier.
And all of this works in any browser without modification to the browser!
When you finish the tutorial you will be able to:
* Create a dynamic application that works in any browser.
* Define the differences between Angular and common JavaScript frameworks.
* Understand how data binding works in AngularJS.
* Use the angular-seed project to quickly boot-strap your own projects.
* Create and run tests.
* Identify resources for learning more about AngularJS.
The tutorial guides you through the entire process of building a simple application, including
writing and running unit and end-to-end tests. Experiments at the end of each step provide
suggestions for you to learn more about AngularJS and the application you are building.
You can go through the whole tutorial in a couple of hours or you may want to spend a pleasant day
really digging into it. If you're looking for a shorter introduction to AngularJS, check out the
{@link misc/started Getting Started} document.
# Working with the code
You can follow this tutorial and hack on the code in either the Mac/Linux or the Windows
environment. The tutorial relies on the use of Git versioning system for source code management.
You don't need to know anything about Git to follow the tutorial. Select one of the tabs below
and follow the instructions for setting up your computer.
<div class="tabbable" show="true">
<div class="tab-pane well" id="git-mac" title="Git on Mac/Linux">
<ol>
<li><p>You will need Node.js and Karma to run unit tests, so please verify that you have
<a href="http://nodejs.org/">Node.js</a> v0.8 or better installed
and that the <code>node</code> executable is on your <code>PATH</code> by running the following
command in a terminal window:</p>
<pre>node --version</pre>
<p>Additionally install <a href="http://karma-runner.github.io/">Karma</a> if you
don't have it already:</p>
<pre>npm install -g karma</pre>
<li><p>You'll also need Git, which you can get from
<a href="http://git-scm.com/download">the Git site</a>.</p></li>
<li><p>Clone the angular-phonecat repository located at
<a href="https://github.com/angular/angular-phonecat">Github</a> by running the following command:</p>
<pre>git clone git://github.com/angular/angular-phonecat.git</pre>
<p>This command creates the <code>angular-phonecat</code> directory in your current
directory.</p></li>
<li><p>Change your current directory to <code>angular-phonecat</code>:</p>
<pre>cd angular-phonecat</pre>
<p>The tutorial instructions assume you are running all commands from the <code>angular-phonecat</code>
directory.</p></li>
<li><p>You will need an http server running on your system. Mac and Linux machines typically
have Apache pre-installed, but If you don't already have one installed, you can use <code>node</code>
to run <code>scripts/web-server.js</code>, a simple bundled http server.</p></li>
</ol>
</div>
<div class="tab-pane well" id="git-win" title="Git on Windows">
<ol>
<li><p>You will need Node.js and Karma to run unit tests, so please verify that you have
<a href="http://nodejs.org/">Node.js</a> v0.8 or better installed
and that the <code>node</code> executable is on your <code>PATH</code> by running the following
command in a terminal window:</p>
<pre>node --version</pre>
<p>Additionally install <a href="http://karma-runner.github.io/">Karma</a> if you
don't have it already:</p>
<pre>npm install -g karma</pre>
</li>
<li><p>You'll also need Git, which you can get from
<a href="http://git-scm.com/download">the Git site</a>.</p></li>
<li><p>Clone the angular-phonecat repository located at <a
href="https://github.com/angular/angular-phonecat">Github</a> by running the following command:</p>
<pre>git clone git://github.com/angular/angular-phonecat.git</pre>
<p>This command creates the <code>angular-phonecat</code> directory in your current directory.</p></li>
<li><p>Change your current directory to <code>angular-phonecat</code>:</p>
<pre>cd angular-phonecat</pre>
<p>The tutorial instructions assume you are running all commands from the <code>angular-phonecat</code>
directory.</p>
<p>You should run all <code>git</code> commands from Git bash.</p>
<p>Other commands like <code>test.bat</code> or <code>e2e-test.bat</code> should be
executed from the Windows command line.</li>
<li><p>You need an http server running on your system, but if you don't already have one
already installed, you can use <code>node</code> to run <code>scripts\web-server.js</code>, a simple
bundled http server.</p></li>
</ol>
</div>
The last thing to do is to make sure your computer has a web browser and a good text editor
installed. Now, let's get some cool stuff done!
{@link step_00 <span class="btn btn-primary">Get Started!</span>}
+212
View File
@@ -0,0 +1,212 @@
@ngdoc overview
@name Tutorial: 0 - Bootstrapping
@description
<ul doc-tutorial-nav="0"></ul>
You are now ready to build the AngularJS phonecat app. In this step, you will become familiar
with the most important source code files, learn how to start the development servers bundled with
angular-seed, and run the application in the browser.
<div class="tabbable" show="true" ng-model="$cookies.platformPreference">
<div class="tab-pane well" id="git-mac" title="Git on Mac/Linux" value="gitUnix">
<ol>
<li><p>In <code>angular-phonecat</code> directory, run this command:</p>
<pre>git checkout -f step-0</pre>
<p>This resets your workspace to step 0 of the tutorial app.</p>
<p>You must repeat this for every future step in the tutorial and change the number to
the number of the step you are on. This will cause any changes you made within
your working directory to be lost.</p></li>
<li>To see the app running in a browser, do one of the following:
<ul>
<li><b>For node.js users:</b>
<ol>
<li>In a <i>separate</i> terminal tab or window, run
<code>node ./scripts/web-server.js</code> to start the web server.</li>
<li>Open a browser window for the app and navigate to <a
href="http://localhost:8000/app/index.html">http://localhost:8000/app/index.html</a></li>
</ol>
</li>
<li><b>For other http servers:</b>
<ol>
<li>Configure the server to serve the files in the <code>angular-phonecat</code>
directory.</li>
<li>Navigate in your browser to
<code>http://localhost:[port-number]/[context-path]/app/index.html</code>.</li>
</ol>
</li>
</ul>
</li>
</ol>
</div>
<div class="tab-pane well" id="git-win" title="Git on Windows" value="gitWin">
<ol>
<li><p>Open Git bash and run this command (in <code>angular-phonecat</code> directory):</p>
<pre>git checkout -f step-0</pre>
<p>This resets your workspace to step 0 of the tutorial app.</p>
<p>You must repeat this for every future step in the tutorial and change the number to
the number of the step you are on. This will cause any changes you made within
your working directory to be lost.</p></li>
<li>To see the app running in a browser, do one of the following:
<ul>
<li><b>For node.js users:</b>
<ol>
<li>In a <i>separate</i> terminal tab or window, run <code>node
scripts\web-server.js</code> to start the web server.</li>
<li>Open a browser window for the app and navigate to <a
href="http://localhost:8000/app/index.html">http://localhost:8000/app/index.html</a></li>
</ol>
</li>
<li><b>For other http servers:</b>
<ol>
<li>Configure the server to serve the files in the <code>angular-phonecat</code>
directory.</li>
<li>Navigate in your browser to
<code>http://localhost:[port-number]/[context-path]/app/index.html</code>.</li>
</ol>
</li>
</ul>
</li>
</ol>
</div>
</div>
You can now see the page in your browser. It's not very exciting, but that's OK.
The HTML page that displays "Nothing here yet!" was constructed with the HTML code shown below.
The code contains some key Angular elements that we will need going forward.
__`app/index.html`:__
<pre>
<!doctype html>
<html lang="en" ng-app>
<head>
<meta charset="utf-8">
<title>My HTML File</title>
<link rel="stylesheet" href="css/app.css">
<link rel="stylesheet" href="css/bootstrap.css">
<script src="lib/angular/angular.js"></script>
</head>
<body>
<p>Nothing here {{'yet' + '!'}}</p>
</body>
</html>
</pre>
## What is the code doing?
* `ng-app` directive:
<html ng-app>
The `ng-app` attribute represents an Angular directive (named `ngApp`; Angular uses
`name-with-dashes` for attribute names and `camelCase` for the corresponding directive name)
used to flag an element which Angular should consider to be the root element of our application.
This gives application developers the freedom to tell Angular if the entire html page or only a
portion of it should be treated as the Angular application.
* AngularJS script tag:
<script src="lib/angular/angular.js">
This code downloads the `angular.js` script and registers a callback that will be executed by the
browser when the containing HTML page is fully downloaded. When the callback is executed, Angular
looks for the {@link api/ng.directive:ngApp ngApp} directive. If
Angular finds the directive, it will bootstrap the application with the root of the application DOM
being the element on which the `ngApp` directive was defined.
* Double-curly binding with an expression:
Nothing here {{'yet' + '!'}}
This line demonstrates the core feature of Angular's templating capabilities a binding, denoted
by double-curlies `{{ }}` as well as a simple expression `'yet' + '!'` used in this binding.
The binding tells Angular that it should evaluate an expression and insert the result into the
DOM in place of the binding. Rather than a one-time insert, as we'll see in the next steps, a
binding will result in efficient continuous updates whenever the result of the expression
evaluation changes.
{@link guide/expression Angular expression} is a JavaScript-like code snippet that is
evaluated by Angular in the context of the current model scope, rather than within the scope of
the global context (`window`).
As expected, once this template is processed by Angular, the html page contains the text:
"Nothing here yet!".
## Bootstrapping AngularJS apps
Bootstrapping AngularJS apps automatically using the `ngApp` directive is very easy and suitable
for most cases. In advanced cases, such as when using script loaders, you can use
{@link guide/bootstrap imperative / manual way} to bootstrap the app.
There are 3 important things that happen during the app bootstrap:
1. The {@link api/AUTO.$injector injector} that will be used for dependency injection
when this app is created.
2. The injector will then create the {@link api/ng.$rootScope root scope} that will
become the context for the model of our application.
3. Angular will then "compile" the DOM starting at the `ngApp` root element, processing any
directives and bindings found along the way.
Once an application is bootstrapped, it will then wait for incoming browser events (such as mouse
click, key press or incoming HTTP response) that might change the model. Once such an event occurs,
Angular detects if it caused any model changes and if changes are found, Angular will reflect them
in the view by updating all of the affected bindings.
The structure of our application is currently very simple. The template contains just one directive
and one static binding, and our model is empty. That will soon change!
<img class="diagram" src="img/tutorial/tutorial_00.png">
## What are all these files in my working directory?
Most of the files in your working directory come from the {@link
https://github.com/angular/angular-seed angular-seed project} which is typically used to bootstrap
new Angular projects. The seed project includes the latest Angular libraries, test libraries,
scripts and a simple example app, all pre-configured for developing a typical web app.
For the purposes of this tutorial, we modified the angular-seed with the following changes:
* Removed the example app
* Added phone images to `app/img/phones/`
* Added phone data files (JSON) to `app/phones/`
* Added [Bootstrap](http://twitter.github.com/bootstrap/) files to `app/css/` and `app/img/`
# Experiments
* Try adding a new expression to the `index.html` that will do some math:
<p>1 + 2 = {{ 1 + 2 }}</p>
# Summary
Now let's go to {@link step_01 step 1} and add some content to the web app.
<ul doc-tutorial-nav="0"></ul>
<div style="display: none">
Note: During the bootstrap the injector and the root scope will then be associated with the
element on which the `ngApp` directive was declared, so when debugging the app you can retrieve
them from browser console via `angular.element(rootElement).scope()` and
`angular.element(rootElement).injector()`.
</div>
+55
View File
@@ -0,0 +1,55 @@
@ngdoc overview
@name Tutorial: 1 - Static Template
@description
<ul doc-tutorial-nav="1"></ul>
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
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.
<div doc-tutorial-reset="1"></div>
The page now contains a list with information about two phones.
The most important changes are listed below. You can see the full diff on {@link
https://github.com/angular/angular-phonecat/compare/step-0...step-1 GitHub}:
__`app/index.html`:__
<pre>
<ul>
<li>
<span>Nexus S</span>
<p>
Fast just got faster with Nexus S.
</p>
</li>
<li>
<span>Motorola XOOM™ with Wi-Fi</span>
<p>
The Next, Next Generation tablet.
</p>
</li>
</ul>
</pre>
# Experiments
* Try adding more static HTML to `index.html`. For example:
<p>Total number of phones: 2</p>
# Summary
This addition to your app uses static HTML to display the list. Now, let's go to {@link step_02
step 2} to learn how to use AngularJS to dynamically generate the same list.
<ul doc-tutorial-nav="1"></ul>
+206
View File
@@ -0,0 +1,206 @@
@ngdoc overview
@name Tutorial: 2 - Angular Templates
@description
<ul doc-tutorial-nav="2"></ul>
Now it's time to make the web page dynamic — with AngularJS. We'll also add a test that verifies the
code for the controller we are going to add.
There are many ways to structure the code for an application. For Angular apps, we encourage the
use of {@link http://en.wikipedia.org/wiki/ModelViewController the Model-View-Controller (MVC)
design pattern} to decouple the code and to separate concerns. With that in mind, let's use a
little Angular and JavaScript to add model, view, and controller components to our app.
<div doc-tutorial-reset="2"></div>
The app now contains a list with three phones.
The most important changes are listed below. You can see the full diff on {@link
https://github.com/angular/angular-phonecat/compare/step-1...step-2 GitHub}:
## View and Template
In Angular, the __view__ is a projection of the model through the HTML __template__. This means that
whenever the model changes, Angular refreshes the appropriate binding points, which updates the
view.
The view component is constructed by Angular from this template:
__`app/index.html`:__
<pre>
<html ng-app>
<head>
...
<script src="lib/angular/angular.js"></script>
<script src="js/controllers.js"></script>
</head>
<body ng-controller="PhoneListCtrl">
<ul>
<li ng-repeat="phone in phones">
{{phone.name}}
<p>{{phone.snippet}}</p>
</li>
</ul>
</body>
</html>
</pre>
We replaced the hard-coded phone list with the
{@link api/ng.directive:ngRepeat ngRepeat directive} and two
{@link guide/expression Angular expressions} enclosed in curly braces:
`{{phone.name}}` and `{{phone.snippet}}`:
* The `ng-repeat="phone in phones"` statement in the `<li>` tag is an Angular repeater. The
repeater tells Angular to create a `<li>` element for each phone in the list using the first `<li>`
tag as the template.
* As we've learned in step 0, the curly braces around `phone.name` and `phone.snippet` denote
bindings. As opposed to evaluating constants, these expressions are referring to our application
model, which was set up in our `PhoneListCtrl` controller.
<img class="diagram" src="img/tutorial/tutorial_02.png">
## Model and Controller
The data __model__ (a simple array of phones in object literal notation) is instantiated within
the `PhoneListCtrl` __controller__:
__`app/js/controllers.js`:__
<pre>
function PhoneListCtrl($scope) {
$scope.phones = [
{"name": "Nexus S",
"snippet": "Fast just got faster with Nexus S."},
{"name": "Motorola XOOM™ with Wi-Fi",
"snippet": "The Next, Next Generation tablet."},
{"name": "MOTOROLA XOOM™",
"snippet": "The Next, Next Generation tablet."}
];
}
</pre>
Although the controller is not yet doing very much controlling, it is playing a crucial role. By
providing context for our data model, the controller allows us to establish data-binding between
the model and the view. We connected the dots between the presentation, data, and logic components
as follows:
* `PhoneListCtrl` — the name of our controller function (located in the JavaScript file
`controllers.js`), matches the value of the
{@link api/ng.directive:ngController ngController} directive located
on the `<body>` tag.
* The phone data is then attached to the *scope* (`$scope`) that was injected into our controller
function. The controller scope is a prototypical descendant of the root scope that was created
when the application bootstrapped. This controller scope is available to all bindings located within
the `<body ng-controller="PhoneListCtrl">` tag.
The concept of a scope in Angular is crucial; a scope can be seen as the glue which allows the
template, model and controller to work together. Angular uses scopes, along with the information
contained in the template, data model, and controller, to keep models and views separate, but in
sync. Any changes made to the model are reflected in the view; any changes that occur in the view
are reflected in the model.
To learn more about Angular scopes, see the {@link api/ng.$rootScope.Scope angular scope documentation}.
## Tests
The "Angular way" makes it easy to test code as it is being developed. Take a look at the following
unit test for your newly created controller:
__`test/unit/controllersSpec.js`:__
<pre>
describe('PhoneCat controllers', function() {
describe('PhoneListCtrl', function(){
it('should create "phones" model with 3 phones', function() {
var scope = {},
ctrl = new PhoneListCtrl(scope);
expect(scope.phones.length).toBe(3);
});
});
});
</pre>
The test instantiates our PhoneListCtrl and verifies that its phones array property contains three
records. This example demonstrates how easy it is to create a unit test for code in Angular. Since
testing is such a critical part of software development, we make it easy to create tests in Angular
so that developers are encouraged to write them.
Angular developers prefer the syntax of Jasmine's Behavior-driven Development (BDD) framework when
writing tests. Although Angular does not require you to use Jasmine, we wrote all of the tests in
this tutorial in Jasmine. You can learn about Jasmine on the {@link
http://pivotal.github.com/jasmine/ Jasmine home page} and on the {@link
https://github.com/pivotal/jasmine/wiki Jasmine wiki}.
The angular-seed project is pre-configured to run all unit tests using {@link
http://karma-runner.github.io/ Karma}. To run the test, do the following:
1. In a _separate_ terminal window or tab, go to the `angular-phonecat` directory and run
`./scripts/test.sh` to start the Karma server (the config file necessary to start the server
is located at `./config/karma.conf.js`).
2. Karma will start a new instance of Chrome browser automatically. Just ignore it and let it run in
the background. Karma will use this browser for test execution.
3. You should see the following or similar output in the terminal:
info: Karma server started at http://localhost:9876/
info (launcher): Starting browser "Chrome"
info (Chrome 22.0): Connected on socket id tPUm9DXcLHtZTKbAEO-n
Chrome 22.0: Executed 1 of 1 SUCCESS (0.093 secs / 0.004 secs)
Yay! The test passed! Or not...
4. To rerun the tests, just change any of the source or test files. Karma will notice the change
and will rerun the tests for you. Now isn't that sweet?
# Experiments
* Add another binding to `index.html`. For example:
<p>Total number of phones: {{phones.length}}</p>
* Create a new model property in the controller and bind to it from the template. For example:
$scope.hello = "Hello, World!"
Refresh your browser to make sure it says, "Hello, World!"
* Create a repeater that constructs a simple table:
<table>
<tr><th>row number</th></tr>
<tr ng-repeat="i in [0, 1, 2, 3, 4, 5, 6, 7]"><td>{{i}}</td></tr>
</table>
Now, make the list 1-based by incrementing `i` by one in the binding:
<table>
<tr><th>row number</th></tr>
<tr ng-repeat="i in [0, 1, 2, 3, 4, 5, 6, 7]"><td>{{i+1}}</td></tr>
</table>
* Make the unit test fail by changing the `toBe(3)` statement to `toBe(4)`.
# Summary
You now have a dynamic app that features separate model, view, and controller components, and you
are testing as you go. Now, let's go to {@link step_03 step 3} to learn how to add full text search
to the app.
<ul doc-tutorial-nav="2"></ul>
+204
View File
@@ -0,0 +1,204 @@
@ngdoc overview
@name Tutorial: 3 - Filtering Repeaters
@description
<ul doc-tutorial-nav="3"></ul>
We did a lot of work in laying a foundation for the app in the last step, so now we'll do something
simple; we will add full text search (yes, it will be simple!). We will also write an end-to-end
test, because a good end-to-end test is a good friend. It stays with your app, keeps an eye on it,
and quickly detects regressions.
<div doc-tutorial-reset="3"></div>
The app now has a search box. Notice that the phone list on the page changes depending on what a
user types into the search box.
The most important differences between Steps 2 and 3 are listed below. You can see the full diff on
{@link https://github.com/angular/angular-phonecat/compare/step-2...step-3
GitHub}:
## Controller
We made no changes to the controller.
## Template
__`app/index.html`:__
<pre>
<div class="container-fluid">
<div class="row-fluid">
<div class="span2">
<!--Sidebar content-->
Search: <input ng-model="query">
</div>
<div class="span10">
<!--Body content-->
<ul class="phones">
<li ng-repeat="phone in phones | filter:query">
{{phone.name}}
<p>{{phone.snippet}}</p>
</li>
</ul>
</div>
</div>
</div>
</pre>
We added a standard HTML `<input>` tag and used Angular's
{@link api/ng.filter:filter $filter} function to process the input for the
{@link api/ng.directive:ngRepeat ngRepeat} directive.
This lets a user enter search criteria and immediately see the effects of their search on the phone
list. This new code demonstrates the following:
* Data-binding: This is one of the core features in Angular. When the page loads, Angular binds the
name of the input box to a variable of the same name in the data model and keeps the two in sync.
In this code, the data that a user types into the input box (named __`query`__) is immediately
available as a filter input in the list repeater (`phone in phones | filter:`__`query`__). When
changes to the data model cause the repeater's input to change, the repeater efficiently updates
the DOM to reflect the current state of the model.
<img class="diagram" src="img/tutorial/tutorial_03.png">
* Use of the `filter` filter: The {@link api/ng.filter:filter filter} function uses the
`query` value to create a new array that contains only those records that match the `query`.
`ngRepeat` automatically updates the view in response to the changing number of phones returned
by the `filter` filter. The process is completely transparent to the developer.
## Test
In Step 2, we learned how to write and run unit tests. Unit tests are perfect for testing
controllers and other components of our application written in JavaScript, but they can't easily
test DOM manipulation or the wiring of our application. For these, an end-to-end test is a much
better choice.
The search feature was fully implemented via templates and data-binding, so we'll write our first
end-to-end test, to verify that the feature works.
__`test/e2e/scenarios.js`:__
<pre>
describe('PhoneCat App', function() {
describe('Phone list view', function() {
beforeEach(function() {
browser().navigateTo('../../app/index.html');
});
it('should filter the phone list as user types into the search box', function() {
expect(repeater('.phones li').count()).toBe(3);
input('query').enter('nexus');
expect(repeater('.phones li').count()).toBe(1);
input('query').enter('motorola');
expect(repeater('.phones li').count()).toBe(2);
});
});
});
</pre>
Even though the syntax of this test looks very much like our controller unit test written with
Jasmine, the end-to-end test uses APIs of {@link guide/dev_guide.e2e-testing Angular's end-to-end
test runner}.
To run the end-to-end test, open one of the following in a new browser tab:
* node.js users: {@link http://localhost:8000/test/e2e/runner.html}
* users with other http servers:
`http://localhost:[port-number]/[context-path]/test/e2e/runner.html`
* casual reader: {@link http://angular.github.com/angular-phonecat/step-3/test/e2e/runner.html}
Previously we've seen how Karma can be used to execute unit tests. Well, it can also run the
end-to-end tests! Use `./scripts/e2e-test.sh` script for that. End-to-end tests are slow, so unlike
with unit tests, Karma will exit after the test run and will not automatically rerun the test
suite on every file change. To rerun the test suite, execute the `e2e-test.sh` script again.
Note: You must ensure you've installed karma-ng-scenario prior to running the `e2e-test.sh` script.
You can do this by issuing `npm install karma-ng-scenario` into your terminal.
This test verifies that the search box and the repeater are correctly wired together. Notice how
easy it is to write end-to-end tests in Angular. Although this example is for a simple test, it
really is that easy to set up any functional, readable, end-to-end test.
# Experiments
* Display the current value of the `query` model by adding a `{{query}}` binding into the
`index.html` template, and see how it changes when you type in the input box.
* Let's see how we can get the current value of the `query` model to appear in the HTML page title.
You might think you could just add the `{{query}}` to the title tag element as follows:
<title>Google Phone Gallery: {{query}}</title>
However, when you reload the page, you won't see the expected result. This is because the "query"
model lives in the scope, defined by the `ng-controller="PhoneListCtrl"` directive, on the body element:
<body ng-controller="PhoneListCtrl">
If you want to bind to the query model from the `<title>` element, you must __move__ the
`ngController` declaration to the HTML element because it is the common parent of both the body
and title elements:
<html ng-app ng-controller="PhoneListCtrl">
Be sure to __remove__ the `ng-controller` declaration from the body element.
While using double curlies works fine within the title element, you might have noticed that
for a split second they are actually displayed to the user while the page is loading. A better
solution would be to use the {@link api/ng.directive:ngBind
ngBind} or {@link api/ng.directive:ngBindTemplate
ngBindTemplate} directives, which are invisible to the user while the page is loading:
<title ng-bind-template="Google Phone Gallery: {{query}}">Google Phone Gallery</title>
* Add the following end-to-end test into the `describe` block within `test/e2e/scenarios.js`:
<pre>
it('should display the current filter value within an element with id "status"',
function() {
expect(element('#status').text()).toMatch(/Current filter: \s*$/);
input('query').enter('nexus');
expect(element('#status').text()).toMatch(/Current filter: nexus\s*$/);
//alternative version of the last assertion that tests just the value of the binding
using('#status').expect(binding('query')).toBe('nexus');
});
</pre>
Refresh the browser tab with the end-to-end test runner to see the test fail. To make the test
pass, edit the `index.html` template to add a `div` or `p` element with `id` `"status"` and content
with the `query` binding, prefixed by "Current filter:". For instance:
<div id="status">Current filter: {{query}}</div>
* Add a `pause()` statement inside of an end-to-end test and rerun it. You'll see the runner pause;
this gives you the opportunity to explore the state of your application while it is displayed in
the browser. The app is live! You can change the search query to prove it. Notice how useful this
is for troubleshooting end-to-end tests.
# Summary
We have now added full text search and included a test to verify that search works! Now let's go on
to {@link step_04 step 4} to learn how to add sorting capability to the phone app.
<ul doc-tutorial-nav="3"></ul>
+189
View File
@@ -0,0 +1,189 @@
@ngdoc overview
@name Tutorial: 4 - Two-way Data Binding
@description
<ul doc-tutorial-nav="4"></ul>
In this step, you will add a feature to let your users control the order of the items in the phone
list. The dynamic ordering is implemented by creating a new model property, wiring it together with
the repeater, and letting the data binding magic do the rest of the work.
<div doc-tutorial-reset="4"></div>
You should see that in addition to the search box, the app displays a drop down menu that allows
users to control the order in which the phones are listed.
The most important differences between Steps 3 and 4 are listed below. You can see the full diff on
{@link https://github.com/angular/angular-phonecat/compare/step-3...step-4 GitHub}:
## Template
__`app/index.html`:__
<pre>
Search: <input ng-model="query">
Sort by:
<select ng-model="orderProp">
<option value="name">Alphabetical</option>
<option value="age">Newest</option>
</select>
<ul class="phones">
<li ng-repeat="phone in phones | filter:query | orderBy:orderProp">
{{phone.name}}
<p>{{phone.snippet}}</p>
</li>
</ul>
</pre>
We made the following changes to the `index.html` template:
* First, we added a `<select>` html element named `orderProp`, so that our users can pick from the
two provided sorting options.
<img class="diagram" src="img/tutorial/tutorial_04.png">
* We then chained the `filter` filter with {@link api/ng.filter:orderBy `orderBy`}
filter to further process the input into the repeater. `orderBy` is a filter that takes an input
array, copies it and reorders the copy which is then returned.
Angular creates a two way data-binding between the select element and the `orderProp` model.
`orderProp` is then used as the input for the `orderBy` filter.
As we discussed in the section about data-binding and the repeater in step 3, whenever the model
changes (for example because a user changes the order with the select drop down menu), Angular's
data-binding will cause the view to automatically update. No bloated DOM manipulation code is
necessary!
## Controller
__`app/js/controllers.js`:__
<pre>
function PhoneListCtrl($scope) {
$scope.phones = [
{"name": "Nexus S",
"snippet": "Fast just got faster with Nexus S.",
"age": 0},
{"name": "Motorola XOOM™ with Wi-Fi",
"snippet": "The Next, Next Generation tablet.",
"age": 1},
{"name": "MOTOROLA XOOM™",
"snippet": "The Next, Next Generation tablet.",
"age": 2}
];
$scope.orderProp = 'age';
}
</pre>
* We modified the `phones` model - the array of phones - and added an `age` property to each phone
record. This property is used to order phones by age.
* We added a line to the controller that sets the default value of `orderProp` to `age`. If we had
not set the default value here, the model would stay uninitialized until our user would pick an
option from the drop down menu.
This is a good time to talk about two-way data-binding. Notice that when the app is loaded in the
browser, "Newest" is selected in the drop down menu. This is because we set `orderProp` to `'age'`
in the controller. So the binding works in the direction from our model to the UI. Now if you
select "Alphabetically" in the drop down menu, the model will be updated as well and the phones
will be reordered. That is the data-binding doing its job in the opposite direction — from the UI
to the model.
## Test
The changes we made should be verified with both a unit test and an end-to-end test. Let's look at
the unit test first.
__`test/unit/controllersSpec.js`:__
<pre>
describe('PhoneCat controllers', function() {
describe('PhoneListCtrl', function(){
var scope, ctrl;
beforeEach(function() {
scope = {},
ctrl = new PhoneListCtrl(scope);
});
it('should create "phones" model with 3 phones', function() {
expect(scope.phones.length).toBe(3);
});
it('should set the default value of orderProp model', function() {
expect(scope.orderProp).toBe('age');
});
});
});
</pre>
The unit test now verifies that the default ordering property is set.
We used Jasmine's API to extract the controller construction into a `beforeEach` block, which is
shared by all tests in the parent `describe` block.
You should now see the following output in the Karma tab:
Chrome 22.0: Executed 2 of 2 SUCCESS (0.021 secs / 0.001 secs)
Let's turn our attention to the end-to-end test.
__`test/e2e/scenarios.js`:__
<pre>
...
it('should be possible to control phone order via the drop down select box',
function() {
//let's narrow the dataset to make the test assertions shorter
input('query').enter('tablet');
expect(repeater('.phones li', 'Phone List').column('phone.name')).
toEqual(["Motorola XOOM\u2122 with Wi-Fi",
"MOTOROLA XOOM\u2122"]);
select('orderProp').option('Alphabetical');
expect(repeater('.phones li', 'Phone List').column('phone.name')).
toEqual(["MOTOROLA XOOM\u2122",
"Motorola XOOM\u2122 with Wi-Fi"]);
});
...
</pre>
The end-to-end test verifies that the ordering mechanism of the select box is working correctly.
You can now rerun `./scripts/e2e-test.sh` or refresh the browser tab with the end-to-end test
`runner.html` to see the tests run, or you can see them running on {@link
http://angular.github.com/angular-phonecat/step-4/test/e2e/runner.html
Angular's server}.
# Experiments
* In the `PhoneListCtrl` controller, remove the statement that sets the `orderProp` value and
you'll see that Angular will temporarily add a new "unknown" option to the drop-down list and the
ordering will default to unordered/natural order.
* Add an `{{orderProp}}` binding into the `index.html` template to display its current value as
text.
* Reverse the sort order by adding a `-` symbol before the sorting value: `<option value="-age">Oldest</option>`
# Summary
Now that you have added list sorting and tested the app, go to {@link step_05 step 5} to learn
about Angular services and how Angular uses dependency injection.
<ul doc-tutorial-nav="4"></ul>
+236
View File
@@ -0,0 +1,236 @@
@ngdoc overview
@name Tutorial: 5 - XHRs & Dependency Injection
@description
<ul doc-tutorial-nav="5"></ul>
Enough of building an app with three phones in a hard-coded dataset! Let's fetch a larger dataset
from our server using one of angular's built-in {@link api/ng services} called {@link
api/ng.$http $http}. We will use angular's {@link guide/di dependency
injection (DI)} to provide the service to the `PhoneListCtrl` controller.
<div doc-tutorial-reset="5"></div>
You should now see a list of 20 phones.
The most important changes are listed below. You can see the full diff on {@link
https://github.com/angular/angular-phonecat/compare/step-4...step-5
GitHub}:
## Data
The `app/phones/phones.json` file in your project is a dataset that contains a larger list of phones
stored in the JSON format.
Following is a sample of the file:
<pre>
[
{
"age": 13,
"id": "motorola-defy-with-motoblur",
"name": "Motorola DEFY\u2122 with MOTOBLUR\u2122",
"snippet": "Are you ready for everything life throws your way?"
...
},
...
]
</pre>
## Controller
We'll use angular's {@link api/ng.$http $http} service in our controller to make an HTTP
request to your web server to fetch the data in the `app/phones/phones.json` file. `$http` is just
one of several built-in {@link guide/dev_guide.services angular services} that handle common operations
in web apps. Angular injects these services for you where you need them.
Services are managed by angular's {@link guide/di DI subsystem}. Dependency injection
helps to make your web apps both well-structured (e.g., separate components for presentation, data,
and control) and loosely coupled (dependencies between components are not resolved by the
components themselves, but by the DI subsystem).
__`app/js/controllers.js:`__
<pre>
function PhoneListCtrl($scope, $http) {
$http.get('phones/phones.json').success(function(data) {
$scope.phones = data;
});
$scope.orderProp = 'age';
}
//PhoneListCtrl.$inject = ['$scope', '$http'];
</pre>
`$http` makes an HTTP GET request to our web server, asking for `phone/phones.json` (the url is
relative to our `index.html` file). The server responds by providing the data in the json file.
(The response might just as well have been dynamically generated by a backend server. To the
browser and our app they both look the same. For the sake of simplicity we used a json file in this
tutorial.)
The `$http` service returns a {@link api/ng.$q promise object} with a `success`
method. We call this method to handle the asynchronous response and assign the phone data to the
scope controlled by this controller, as a model called `phones`. Notice that angular detected the
json response and parsed it for us!
To use a service in angular, you simply declare the names of the dependencies you need as arguments
to the controller's constructor function, as follows:
function PhoneListCtrl($scope, $http) {...}
Angular's dependency injector provides services to your controller when the controller is being
constructed. The dependency injector also takes care of creating any transitive dependencies the
service may have (services often depend upon other services).
Note that the names of arguments are significant, because the injector uses these to look up the
dependencies.
<img class="diagram" src="img/tutorial/xhr_service_final.png">
### '$' Prefix Naming Convention
You can create your own services, and in fact we will do exactly that in step 11. As a naming
convention, angular's built-in services, Scope methods and a few other angular APIs have a '$'
prefix in front of the name. Don't use a '$' prefix when naming your services and models, in order
to avoid any possible naming collisions.
### A Note on Minification
Since angular infers the controller's dependencies from the names of arguments to the controller's
constructor function, if you were to {@link http://en.wikipedia.org/wiki/Minification_(programming)
minify} the JavaScript code for `PhoneListCtrl` controller, all of its function arguments would be
minified as well, and the dependency injector would not be able to identify services correctly.
To overcome issues caused by minification, just assign an array with service identifier strings
into the `$inject` property of the controller function, just like the last line in the snippet
(commented out) suggests:
PhoneListCtrl.$inject = ['$scope', '$http'];
There is also one more way to specify this dependency list and avoid minification issues — using the
bracket notation which wraps the function to be injected into an array of strings (representing the
dependency names) followed by the function to be injected:
var PhoneListCtrl = ['$scope', '$http', function($scope, $http) { /* constructor body */ }];
Both of these methods work with any function that can be injected by Angular, so it's up to your
project's style guide to decide which one you use.
## Test
__`test/unit/controllersSpec.js`:__
Because we started using dependency injection and our controller has dependencies, constructing the
controller in our tests is a bit more complicated. We could use the `new` operator and provide the
constructor with some kind of fake `$http` implementation. However, the recommended (and easier) way
is to create a controller in the test environment in the same way that angular does it in the
production code behind the scenes, as follows:
<pre>
describe('PhoneCat controllers', function() {
describe('PhoneListCtrl', function(){
var scope, ctrl, $httpBackend;
// The injector ignores leading and trailing underscores here (i.e. _$httpBackend_).
// This allows us to inject a service but then attach it to a variable
// with the same name as the service.
beforeEach(inject(function(_$httpBackend_, $rootScope, $controller) {
$httpBackend = _$httpBackend_;
$httpBackend.expectGET('phones/phones.json').
respond([{name: 'Nexus S'}, {name: 'Motorola DROID'}]);
scope = $rootScope.$new();
ctrl = $controller(PhoneListCtrl, {$scope: scope});
}));
</pre>
Note: Because we loaded Jasmine and `angular-mocks.js` in our test environment, we got two helper
methods {@link api/angular.mock.module module} and {@link api/angular.mock.inject inject} that we'll
use to access and configure the injector.
We created the controller in the test environment, as follows:
* We used the `inject` helper method to inject instances of
{@link api/ng.$rootScope $rootScope},
{@link api/ng.$controller $controller} and
{@link api/ng.$httpBackend $httpBackend} services into the Jasmine's `beforeEach`
function. These instances come from an injector which is recreated from scratch for every single
test. This guarantees that each test starts from a well known starting point and each test is
isolated from the work done in other tests.
* We created a new scope for our controller by calling `$rootScope.$new()`
* We called the injected `$controller` function passing the `PhoneListCtrl` function and the created
scope as parameters.
Because our code now uses the `$http` service to fetch the phone list data in our controller, before
we create the `PhoneListCtrl` child scope, we need to tell the testing harness to expect an
incoming request from the controller. To do this we:
* Request `$httpBackend` service to be injected into our `beforeEach` function. This is a mock
version of the service that in a production environment facilitates all XHR and JSONP requests.
The mock version of this service allows you to write tests without having to deal with
native APIs and the global state associated with them — both of which make testing a nightmare.
* Use the `$httpBackend.expectGET` method to train the `$httpBackend` service to expect an incoming
HTTP request and tell it what to respond with. Note that the responses are not returned until we call
the `$httpBackend.flush` method.
Now, we will make assertions to verify that the `phones` model doesn't exist on `scope` before
the response is received:
<pre>
it('should create "phones" model with 2 phones fetched from xhr', function() {
expect(scope.phones).toBeUndefined();
$httpBackend.flush();
expect(scope.phones).toEqual([{name: 'Nexus S'},
{name: 'Motorola DROID'}]);
});
</pre>
* We flush the request queue in the browser by calling `$httpBackend.flush()`. This causes the
promise returned by the `$http` service to be resolved with the trained response.
* We make the assertions, verifying that the phone model now exists on the scope.
Finally, we verify that the default value of `orderProp` is set correctly:
<pre>
it('should set the default value of orderProp model', function() {
expect(scope.orderProp).toBe('age');
});
</pre>
You should now see the following output in the Karma tab:
Chrome 22.0: Executed 2 of 2 SUCCESS (0.028 secs / 0.007 secs)
# Experiments
* At the bottom of `index.html`, add a `{{phones | json}}` binding to see the list of phones
displayed in json format.
* In the `PhoneListCtrl` controller, pre-process the http response by limiting the number of phones
to the first 5 in the list. Use the following code in the $http callback:
$scope.phones = data.splice(0, 5);
# Summary
Now that you have learned how easy it is to use angular services (thanks to Angular's dependency
injection), go to {@link step_06 step 6}, where you will add some
thumbnail images of phones and some links.
<ul doc-tutorial-nav="5"></ul>
+111
View File
@@ -0,0 +1,111 @@
@ngdoc overview
@name Tutorial: 6 - Templating Links & Images
@description
<ul doc-tutorial-nav="6"></ul>
In this step, you will add thumbnail images for the phones in the phone list, and links that, for
now, will go nowhere. In subsequent steps you will use the links to display additional information
about the phones in the catalog.
<div doc-tutorial-reset="6"></div>
You should now see links and images of the phones in the list.
The most important changes are listed below. You can see the full diff on {@link
https://github.com/angular/angular-phonecat/compare/step-5...step-6
GitHub}:
## Data
Note that the `phones.json` file contains unique ids and image urls for each of the phones. The
urls point to the `app/img/phones/` directory.
__`app/phones/phones.json`__ (sample snippet):
<pre>
[
{
...
"id": "motorola-defy-with-motoblur",
"imageUrl": "img/phones/motorola-defy-with-motoblur.0.jpg",
"name": "Motorola DEFY\u2122 with MOTOBLUR\u2122",
...
},
...
]
</pre>
## Template
__`app/index.html`:__
<pre>
...
<ul class="phones">
<li ng-repeat="phone in phones | filter:query | orderBy:orderProp" class="thumbnail">
<a href="#/phones/{{phone.id}}" class="thumb"><img ng-src="{{phone.imageUrl}}"></a>
<a href="#/phones/{{phone.id}}">{{phone.name}}</a>
<p>{{phone.snippet}}</p>
</li>
</ul>
...
</pre>
To dynamically generate links that will in the future lead to phone detail pages, we used the
now-familiar double-curly brace binding in the `href` attribute values. In step 2, we added the
`{{phone.name}}` binding as the element content. In this step the `{{phone.id}}` binding is used in
the element attribute.
We also added phone images next to each record using an image tag with the {@link
api/ng.directive:ngSrc ngSrc} directive. That directive prevents the
browser from treating the angular `{{ expression }}` markup literally, and initiating a request to
invalid url `http://localhost:8000/app/{{phone.imageUrl}}`, which it would have done if we had only
specified an attribute binding in a regular `src` attribute (`<img class="diagram" src="{{phone.imageUrl}}">`).
Using the `ngSrc` directive prevents the browser from making an http request to an invalid location.
## Test
__`test/e2e/scenarios.js`__:
<pre>
...
it('should render phone specific links', function() {
input('query').enter('nexus');
element('.phones li a').click();
expect(browser().location().url()).toBe('/phones/nexus-s');
});
...
</pre>
We added a new end-to-end test to verify that the app is generating correct links to the phone
views that we will implement in the upcoming steps.
You can now rerun `./scripts/e2e-test.sh` or refresh the browser tab with the end-to-end test
runner to see the tests run, or you can see them running on {@link
http://angular.github.com/angular-phonecat/step-6/test/e2e/runner.html
Angular's server}.
# Experiments
* Replace the `ng-src` directive with a plain old `src` attribute. Using tools such as Firebug,
or Chrome's Web Inspector, or inspecting the webserver access logs, confirm that the app is indeed
making an extraneous request to `/app/%7B%7Bphone.imageUrl%7D%7D` (or
`/app/{{phone.imageUrl}}`).
The issue here is that the browser will fire a request for that invalid image address as soon as
it hits the `img` tag, which is before Angular has a chance to evaluate the expression and inject
the valid address.
# Summary
Now that you have added phone images and links, go to {@link step_07 step 7} to learn about Angular
layout templates and how Angular makes it easy to create applications that have multiple views.
<ul doc-tutorial-nav="6"></ul>
+262
View File
@@ -0,0 +1,262 @@
@ngdoc overview
@name Tutorial: 7 - Routing & Multiple Views
@description
<ul doc-tutorial-nav="7"></ul>
In this step, you will learn how to create a layout template and how to build an app that has
multiple views by adding routing.
<div doc-tutorial-reset="7"></div>
Note that when you now navigate to `app/index.html`, you are redirected to `app/index.html#/phones`
and the same phone list appears in the browser. When you click on a phone link the stub of a phone
detail page is displayed.
The most important changes are listed below. You can see the full diff on {@link
https://github.com/angular/angular-phonecat/compare/step-6...step-7
GitHub}.
## Multiple Views, Routing and Layout Template
Our app is slowly growing and becoming more complex. Before step 7, the app provided our users with
a single view (the list of all phones), and all of the template code was located in the
`index.html` file. The next step in building the app is to add a view that will show detailed
information about each of the devices in our list.
To add the detailed view, we could expand the `index.html` file to contain template code for both
views, but that would get messy very quickly. Instead, we are going to turn the `index.html`
template into what we call a "layout template". This is a template that is common for all views in
our application. Other "partial templates" are then included into this layout template depending on
the current "route" — the view that is currently displayed to the user.
Application routes in Angular are declared via the
{@link api/ng.$routeProvider $routeProvider}, which is the provider of the
{@link api/ng.$route $route service}. This service makes it easy to wire together
controllers, view templates, and the current
URL location in the browser. Using this feature we can implement {@link
http://en.wikipedia.org/wiki/Deep_linking deep linking}, which lets us utilize the browser's
history (back and forward navigation) and bookmarks.
### A Note About DI, Injector and Providers
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.
When the application bootstraps, Angular creates an injector that will be used for all DI stuff in
this app. The injector itself doesn't know anything about what `$http` or `$route` services do, in
fact it doesn't even know about the existence of these services unless it is configured with proper
module definitions. The sole responsibilities of the injector are to load specified module
definition(s), register all service providers defined in these modules, and when asked, inject
a specified function with dependencies (services) that it lazily instantiates via their providers.
Providers are objects that provide (create) instances of services and expose configuration APIs
that can be used to control the creation and runtime behavior of a service. In case of the `$route`
service, the `$routeProvider` exposes APIs that allow you to define routes for your application.
Angular modules solve the problem of removing global state from the application and provide a way
of configuring the injector. As opposed to AMD or require.js modules, Angular modules don't try to
solve the problem of script load ordering or lazy script fetching. These goals are orthogonal and
both module systems can live side by side and fulfil their goals.
## The App Module
__`app/js/app.js`:__
<pre>
angular.module('phonecat', []).
config(['$routeProvider', function($routeProvider) {
$routeProvider.
when('/phones', {templateUrl: 'partials/phone-list.html', controller: PhoneListCtrl}).
when('/phones/:phoneId', {templateUrl: 'partials/phone-detail.html', controller: PhoneDetailCtrl}).
otherwise({redirectTo: '/phones'});
}]);
</pre>
In order to configure our application with routes, we need to create a module for our application.
We call this module `phonecat` and using the `config` API we request the `$routeProvider` to be
injected into our config function and use `$routeProvider.when` API to define our routes.
Note that during the injector configuration phase, the providers can be injected as well, but they
will not be available for injection once the injector is created and starts creating service
instances.
Our application routes were defined as follows:
* The phone list view will be shown when the URL hash fragment is `/phones`. To construct this
view, Angular will use the `phone-list.html` template and the `PhoneListCtrl` controller.
* The phone details view will be shown when the URL hash fragment matches '/phone/:phoneId', where
`:phoneId` is a variable part of the URL. To construct the phone details view, angular will use the
`phone-detail.html` template and the `PhoneDetailCtrl` controller.
We reused the `PhoneListCtrl` controller that we constructed in previous steps and we added a new,
empty `PhoneDetailCtrl` controller to the `app/js/controllers.js` file for the phone details view.
The statement `$route.otherwise({redirectTo: '/phones'})` triggers a redirection to `/phones` when
the browser address doesn't match either of our routes.
Note the use of the `:phoneId` parameter in the second route declaration. The `$route` service uses
the route declaration — `'/phones/:phoneId'` — as a template that is matched against the current
URL. All variables defined with the `:` notation are extracted into the
{@link api/ng.$routeParams $routeParams} object.
In order for our application to bootstrap with our newly created module we'll also need to specify
the module name as the value of the {@link api/ng.directive:ngApp ngApp}
directive:
__`app/index.html`:__
<pre>
<!doctype html>
<html lang="en" ng-app="phonecat">
...
</pre>
## Controllers
__`app/js/controllers.js`:__
<pre>
...
function PhoneDetailCtrl($scope, $routeParams) {
$scope.phoneId = $routeParams.phoneId;
}
//PhoneDetailCtrl.$inject = ['$scope', '$routeParams'];
</pre>
## Template
The `$route` service is usually used in conjunction with the {@link api/ng.directive:ngView
ngView} directive. The role of the `ngView` directive is to include the view template for the current
route into the layout template, which makes it a perfect fit for our `index.html` template.
__`app/index.html`:__
<pre>
<html lang="en" ng-app="phonecat">
<head>
...
<script src="lib/angular/angular.js"></script>
<script src="js/app.js"></script>
<script src="js/controllers.js"></script>
</head>
<body>
<div ng-view></div>
</body>
</html>
</pre>
Note that we removed most of the code in the `index.html` template and replaced it with a single
line containing a div with the `ng-view` attribute. The code that we removed was placed into the
`phone-list.html` template:
__`app/partials/phone-list.html`:__
<pre>
<div class="container-fluid">
<div class="row-fluid">
<div class="span2">
<!--Sidebar content-->
Search: <input ng-model="query">
Sort by:
<select ng-model="orderProp">
<option value="name">Alphabetical</option>
<option value="age">Newest</option>
</select>
</div>
<div class="span10">
<!--Body content-->
<ul class="phones">
<li ng-repeat="phone in phones | filter:query | orderBy:orderProp" class="thumbnail">
<a href="#/phones/{{phone.id}}" class="thumb"><img ng-src="{{phone.imageUrl}}"></a>
<a href="#/phones/{{phone.id}}">{{phone.name}}</a>
<p>{{phone.snippet}}</p>
</li>
</ul>
</div>
</div>
</div>
</pre>
<div style="display:none">
TODO!
<img class="diagram" src="img/tutorial/tutorial_07_final.png">
</div>
We also added a placeholder template for the phone details view:
__`app/partials/phone-detail.html`:__
<pre>
TBD: detail view for {{phoneId}}
</pre>
Note how we are using `phoneId` model defined in the `PhoneDetailCtrl` controller.
## Test
To automatically verify that everything is wired properly, we wrote end-to-end tests that navigate
to various URLs and verify that the correct view was rendered.
<pre>
...
it('should redirect index.html to index.html#/phones', function() {
browser().navigateTo('../../app/index.html');
expect(browser().location().url()).toBe('/phones');
});
...
describe('Phone detail view', function() {
beforeEach(function() {
browser().navigateTo('../../app/index.html#/phones/nexus-s');
});
it('should display placeholder page with phoneId', function() {
expect(binding('phoneId')).toBe('nexus-s');
});
});
</pre>
You can now rerun `./scripts/e2e-test.sh` or refresh the browser tab with the end-to-end test
runner to see the tests run, or you can see them running on {@link
http://angular.github.com/angular-phonecat/step-7/test/e2e/runner.html
Angular's server}.
# Experiments
* Try to add an `{{orderProp}}` binding to `index.html`, and you'll see that nothing happens even
when you are in the phone list view. This is because the `orderProp` model is visible only in the
scope managed by `PhoneListCtrl`, which is associated with the `<div ng-view>` element. If you add
the same binding into the `phone-list.html` template, the binding will work as expected.
<div style="display: none">
* In `PhoneCatCtrl`, create a new model called "`hero`" with `this.hero = 'Zoro'`. In
`PhoneListCtrl` let's shadow it with `this.hero = 'Batman'`, and in `PhoneDetailCtrl` we'll use
`this.hero = "Captain Proton"`. Then add the `<p>hero = {{hero}}</p>` to all three of our templates
(`index.html`, `phone-list.html`, and `phone-detail.html`). Open the app and you'll see scope
inheritance and model property shadowing do some wonders.
</div>
# Summary
With the routing set up and the phone list view implemented, we're ready to go to {@link step_08
step 8} to implement the phone details view.
<ul doc-tutorial-nav="7"></ul>
+194
View File
@@ -0,0 +1,194 @@
@ngdoc overview
@name Tutorial: 8 - More Templating
@description
<ul doc-tutorial-nav="8"></ul>
In this step, you will implement the phone details view, which is displayed when a user clicks on a
phone in the phone list.
<div doc-tutorial-reset="8"></div>
Now when you click on a phone on the list, the phone details page with phone-specific information
is displayed.
To implement the phone details view we will use {@link api/ng.$http $http} to fetch
our data, and we'll flesh out the `phone-detail.html` view template.
The most important changes are listed below. You can see the full diff on {@link
https://github.com/angular/angular-phonecat/compare/step-7...step-8
GitHub}:
## Data
In addition to `phones.json`, the `app/phones/` directory also contains one json file for each
phone:
__`app/phones/nexus-s.json`:__ (sample snippet)
<pre>
{
"additionalFeatures": "Contour Display, Near Field Communications (NFC),...",
"android": {
"os": "Android 2.3",
"ui": "Android"
},
...
"images": [
"img/phones/nexus-s.0.jpg",
"img/phones/nexus-s.1.jpg",
"img/phones/nexus-s.2.jpg",
"img/phones/nexus-s.3.jpg"
],
"storage": {
"flash": "16384MB",
"ram": "512MB"
}
}
</pre>
Each of these files describes various properties of the phone using the same data structure. We'll
show this data in the phone detail view.
## Controller
We'll expand the `PhoneDetailCtrl` by using the `$http` service to fetch the json files. This works
the same way as the phone list controller.
__`app/js/controllers.js`:__
<pre>
function PhoneDetailCtrl($scope, $routeParams, $http) {
$http.get('phones/' + $routeParams.phoneId + '.json').success(function(data) {
$scope.phone = data;
});
}
//PhoneDetailCtrl.$inject = ['$scope', '$routeParams', '$http'];
</pre>
To construct the URL for the HTTP request, we use `$routeParams.phoneId` extracted from the current
route by the `$route` service.
## Template
The TBD placeholder line has been replaced with lists and bindings that comprise the phone details.
Note where we use the angular `{{expression}}` markup and `ngRepeat` to project phone data from
our model into the view.
__`app/partials/phone-detail.html`:__
<pre>
<img ng-src="{{phone.images[0]}}" class="phone">
<h1>{{phone.name}}</h1>
<p>{{phone.description}}</p>
<ul class="phone-thumbs">
<li ng-repeat="img in phone.images">
<img ng-src="{{img}}">
</li>
</ul>
<ul class="specs">
<li>
<span>Availability and Networks</span>
<dl>
<dt>Availability</dt>
<dd ng-repeat="availability in phone.availability">{{availability}}</dd>
</dl>
</li>
...
</li>
<span>Additional Features</span>
<dd>{{phone.additionalFeatures}}</dd>
</li>
</ul>
</pre>
<div style="display: none">
TODO!
<img class="diagram" src="img/tutorial/tutorial_08-09_final.png">
</div>
## Test
We wrote a new unit test that is similar to the one we wrote for the `PhoneListCtrl` controller in
step 5.
__`test/unit/controllersSpec.js`:__
<pre>
...
describe('PhoneDetailCtrl', function(){
var scope, $httpBackend, ctrl;
beforeEach(inject(function(_$httpBackend_, $rootScope, $routeParams, $controller) {
$httpBackend = _$httpBackend_;
$httpBackend.expectGET('phones/xyz.json').respond({name:'phone xyz'});
$routeParams.phoneId = 'xyz';
scope = $rootScope.$new();
ctrl = $controller(PhoneDetailCtrl, {$scope: scope});
}));
it('should fetch phone detail', function() {
expect(scope.phone).toBeUndefined();
$httpBackend.flush();
expect(scope.phone).toEqual({name:'phone xyz'});
});
});
...
</pre>
You should now see the following output in the Karma tab:
Chrome 22.0: Executed 3 of 3 SUCCESS (0.039 secs / 0.012 secs)
We also added a new end-to-end test that navigates to the Nexus S detail page and verifies that the
heading on the page is "Nexus S".
__`test/e2e/scenarios.js`:__
<pre>
...
describe('Phone detail view', function() {
beforeEach(function() {
browser().navigateTo('../../app/index.html#/phones/nexus-s');
});
it('should display nexus-s page', function() {
expect(binding('phone.name')).toBe('Nexus S');
});
});
...
</pre>
You can now rerun `./scripts/e2e-test.sh` or refresh the browser tab with the end-to-end test
runner to see the tests run, or you can see them running on {@link
http://angular.github.com/angular-phonecat/step-8/test/e2e/runner.html
Angular's server}.
# Experiments
* Using the {@link guide/dev_guide.e2e-testing Angular's end-to-end test runner API}, write a test
that verifies that we display 4 thumbnail images on the Nexus S details page.
# Summary
Now that the phone details view is in place, proceed to {@link step_09 step 9} to learn how to
write your own custom display filter.
<ul doc-tutorial-nav="8"></ul>
+141
View File
@@ -0,0 +1,141 @@
@ngdoc overview
@name Tutorial: 9 - Filters
@description
<ul doc-tutorial-nav="9"></ul>
In this step you will learn how to create your own custom display filter.
<div doc-tutorial-reset="9"></div>
Navigate to one of the detail pages.
In the previous step, the details page displayed either "true" or "false" to indicate whether
certain phone features were present or not. We have used a custom filter to convert those text
strings into glyphs: ✓ for "true", and ✘ for "false". Let's see what the filter code looks like.
The most important changes are listed below. You can see the full diff on {@link
https://github.com/angular/angular-phonecat/compare/step-8...step-9
GitHub}:
## Custom Filter
In order to create a new filter, you are going to create a `phonecatFilters` module and register
your custom filter with this module:
__`app/js/filters.js`:__
<pre>
angular.module('phonecatFilters', []).filter('checkmark', function() {
return function(input) {
return input ? '\u2713' : '\u2718';
};
});
</pre>
The name of our filter is "checkmark". The `input` evaluates to either `true` or `false`, and we
return one of the two unicode characters we have chosen to represent true (`\u2713` -> ✓) or false (`\u2718` -> ✘).
Now that our filter is ready, we need to register the `phonecatFilters` module as a dependency for
our main `phonecat` module.
__`app/js/app.js`:__
<pre>
...
angular.module('phonecat', ['phonecatFilters']).
...
</pre>
## Template
Since the filter code lives in the `app/js/filters.js` file, we need to include this file in our
layout template.
__`app/index.html`:__
<pre>
...
<script src="js/controllers.js"></script>
<script src="js/filters.js"></script>
...
</pre>
The syntax for using filters in Angular templates is as follows:
{{ expression | filter }}
Let's employ the filter in the phone details template:
__`app/partials/phone-detail.html`:__
<pre>
...
<dl>
<dt>Infrared</dt>
<dd>{{phone.connectivity.infrared | checkmark}}</dd>
<dt>GPS</dt>
<dd>{{phone.connectivity.gps | checkmark}}</dd>
</dl>
...
</pre>
## Test
Filters, like any other component, should be tested and these tests are very easy to write.
__`test/unit/filtersSpec.js`:__
<pre>
describe('filter', function() {
beforeEach(module('phonecatFilters'));
describe('checkmark', function() {
it('should convert boolean values to unicode checkmark or cross',
inject(function(checkmarkFilter) {
expect(checkmarkFilter(true)).toBe('\u2713');
expect(checkmarkFilter(false)).toBe('\u2718');
}));
});
});
</pre>
We must call `beforeEach(module('phonecatFilters'))` before any of
our filter tests execute. This call loads our `phonecatFilters` module into the injector
for this test run.
Note that we call the helper function, `inject(function(checkmarkFilter) { ... })`, to get
access to the filter that we want to test. See {@link api/angular.mock.inject angular.mock.inject()}.
You should now see the following output in the Karma tab:
Chrome 22.0: Executed 4 of 4 SUCCESS (0.034 secs / 0.012 secs)
# Experiments
* Let's experiment with some of the {@link api/ng.$filter built-in Angular filters} and add the
following bindings to `index.html`:
* `{{ "lower cap string" | uppercase }}`
* `{{ {foo: "bar", baz: 23} | json }}`
* `{{ 1304375948024 | date }}`
* `{{ 1304375948024 | date:"MM/dd/yyyy @ h:mma" }}`
* We can also create a model with an input element, and combine it with a filtered binding. Add
the following to index.html:
<input ng-model="userInput"> Uppercased: {{ userInput | uppercase }}
# Summary
Now that you have learned how to write and test a custom filter, go to {@link step_10 step 10} to
learn how we can use Angular to enhance the phone details page further.
<ul doc-tutorial-nav="9"></ul>
+141
View File
@@ -0,0 +1,141 @@
@ngdoc overview
@name Tutorial: 10 - Event Handlers
@description
<ul doc-tutorial-nav="10"></ul>
In this step, you will add a clickable phone image swapper to the phone details page.
<div doc-tutorial-reset="10"></div>
The phone details view displays one large image of the current phone and several smaller thumbnail
images. It would be great if we could replace the large image with any of the thumbnails just by
clicking on the desired thumbnail image. Let's have a look at how we can do this with Angular.
The most important changes are listed below. You can see the full diff on {@link
https://github.com/angular/angular-phonecat/compare/step-9...step-10
GitHub}:
## Controller
__`app/js/controllers.js`:__
<pre>
...
function PhoneDetailCtrl($scope, $routeParams, $http) {
$http.get('phones/' + $routeParams.phoneId + '.json').success(function(data) {
$scope.phone = data;
$scope.mainImageUrl = data.images[0];
});
$scope.setImage = function(imageUrl) {
$scope.mainImageUrl = imageUrl;
}
}
//PhoneDetailCtrl.$inject = ['$scope', '$routeParams', '$http'];
</pre>
In the `PhoneDetailCtrl` controller, we created the `mainImageUrl` model property and set its
default value to the first phone image URL.
We also created a `setImage` event handler function that will change the value of `mainImageUrl`.
## Template
__`app/partials/phone-detail.html`:__
<pre>
<img ng-src="{{mainImageUrl}}" class="phone">
...
<ul class="phone-thumbs">
<li ng-repeat="img in phone.images">
<img ng-src="{{img}}" ng-click="setImage(img)">
</li>
</ul>
...
</pre>
We bound the `ngSrc` directive of the large image to the `mainImageUrl` property.
We also registered an {@link api/ng.directive:ngClick `ngClick`}
handler with thumbnail images. When a user clicks on one of the thumbnail images, the handler will
use the `setImage` event handler function to change the value of the `mainImageUrl` property to the
URL of the thumbnail image.
<div style="display: none">
TODO!
<img class="diagram" src="img/tutorial/tutorial_10-11_final.png">
</div>
## Test
To verify this new feature, we added two end-to-end tests. One verifies that the main image is set
to the first phone image by default. The second test clicks on several thumbnail images and
verifies that the main image changed appropriately.
__`test/e2e/scenarios.js`:__
<pre>
...
describe('Phone detail view', function() {
...
it('should display the first phone image as the main phone image', function() {
expect(element('img.phone').attr('src')).toBe('img/phones/nexus-s.0.jpg');
});
it('should swap main image if a thumbnail image is clicked on', function() {
element('.phone-thumbs li:nth-child(3) img').click();
expect(element('img.phone').attr('src')).toBe('img/phones/nexus-s.2.jpg');
element('.phone-thumbs li:nth-child(1) img').click();
expect(element('img.phone').attr('src')).toBe('img/phones/nexus-s.0.jpg');
});
});
});
</pre>
You can now rerun `./scripts/e2e-test.sh` or refresh the browser tab with the end-to-end test
runner to see the tests run, or you can see them running on {@link
http://angular.github.com/angular-phonecat/step-10/test/e2e/runner.html
Angular's server}.
# Experiments
* Let's add a new controller method to `PhoneDetailCtrl`:
$scope.hello = function(name) {
alert('Hello ' + (name || 'world') + '!');
}
and add:
<button ng-click="hello('Elmo')">Hello</button>
to the `phone-details.html` template.
<div style="display: none">
TODO!
The controller methods are inherited between controllers/scopes, so you can use the same snippet
in the `phone-list.html` template as well.
* Move the `hello` method from `PhoneCatCtrl` to `PhoneListCtrl` and you'll see that the button
declared in `index.html` will stop working, while the one declared in the `phone-list.html`
template remains operational.
</div>
# Summary
With the phone image swapper in place, we're ready for {@link step_11 step 11} (the last step!) to
learn an even better way to fetch data.
<ul doc-tutorial-nav="10"></ul>

Some files were not shown because too many files have changed in this diff Show More