\n \nThis dashboard is to show information that helps discern the state of supporting databases primarily MySQL or Postgres. This may additionally include information on Redis, Cassandra, Mongo and/or ElasticSearch.",
+ "content": "
Cluster Databases
This dashboard is to show information that helps discern the state of supporting databases primarily MySQL or Postgres. This may additionally include information on Redis, Cassandra, Mongo and/or ElasticSearch.
\n \nThis dashboard presents information to help assess the authentication system in OpenStack. It will be enhanced to include other security metrics as they are collected.",
+ "content": "
Security
This dashboard presents information to help assess the authentication system in OpenStack. It will be enhanced to include other security metrics as they are collected.
\n \nThis dashboard provides information on the storage nodes and their OpenStack related processes.",
+ "content": "
OpenStack Block Store
This dashboard provides information on the Cinder storage nodes and their OpenStack related processes.
",
"style": {},
"title": "Store"
},
diff --git a/v2/dash/app/dashboards/default.json b/v2/dash/app/dashboards/default.json
index af1e8e1..63dbcef 100644
--- a/v2/dash/app/dashboards/default.json
+++ b/v2/dash/app/dashboards/default.json
@@ -4,7 +4,7 @@
"filter": {
"list": [],
"time": {
- "from": "now-6h",
+ "from": "now-1h",
"to": "now"
}
}
diff --git a/v2/dash/app/dashboards/empty.json b/v2/dash/app/dashboards/empty.json
index 168fb64..0a2150c 100644
--- a/v2/dash/app/dashboards/empty.json
+++ b/v2/dash/app/dashboards/empty.json
@@ -4,7 +4,7 @@
"filter": {
"list": [],
"time": {
- "from": "now-6h",
+ "from": "now-1h",
"to": "now"
}
}
diff --git a/v2/dboards/.gitignore b/v2/dboards/.gitignore
new file mode 100644
index 0000000..6e77adf
--- /dev/null
+++ b/v2/dboards/.gitignore
@@ -0,0 +1,12 @@
+node_modules
+.aws-config.json
+dist
+
+# locally required config files
+web.config
+config.js
+
+# Editor junk
+*.sublime-workspace
+*.swp
+.idea
diff --git a/v2/dboards/.jscs.json b/v2/dboards/.jscs.json
new file mode 100644
index 0000000..dcf694d
--- /dev/null
+++ b/v2/dboards/.jscs.json
@@ -0,0 +1,13 @@
+{
+ "disallowImplicitTypeConversion": ["string"],
+ "disallowKeywords": ["with"],
+ "disallowMultipleLineBreaks": true,
+ "disallowMixedSpacesAndTabs": true,
+ "disallowTrailingWhitespace": true,
+ "requireSpacesInFunctionExpression": {
+ "beforeOpeningCurlyBrace": true
+ },
+ "disallowSpacesInsideArrayBrackets": true,
+ "disallowSpacesInsideParentheses": true,
+ "validateIndentation": 2
+}
\ No newline at end of file
diff --git a/v2/dboards/.jshintrc b/v2/dboards/.jshintrc
new file mode 100644
index 0000000..e8f044e
--- /dev/null
+++ b/v2/dboards/.jshintrc
@@ -0,0 +1,35 @@
+{
+ "browser": true,
+
+ "bitwise":false,
+ "curly": true,
+ "eqnull": true,
+ "globalstrict": true,
+ "devel": true,
+ "eqeqeq": true,
+ "forin": false,
+ "immed": true,
+ "supernew": true,
+ "expr": true,
+ "indent": 2,
+ "latedef": true,
+ "newcap": true,
+ "noarg": true,
+ "noempty": true,
+ "undef": true,
+ "boss": true,
+ "trailing": true,
+ "laxbreak": true,
+ "laxcomma": true,
+ "sub": true,
+ "unused": true,
+ "maxdepth": 5,
+ "maxlen": 140,
+
+ "globals": {
+ "define": true,
+ "require": true,
+ "Chromath": false,
+ "setImmediate": true
+ }
+}
\ No newline at end of file
diff --git a/v2/dboards/.travis.yml b/v2/dboards/.travis.yml
new file mode 100644
index 0000000..0ce3be2
--- /dev/null
+++ b/v2/dboards/.travis.yml
@@ -0,0 +1,5 @@
+language: node_js
+node_js:
+ - "0.10"
+before_script:
+ - npm install -g grunt-cli
\ No newline at end of file
diff --git a/v2/dboards/CHANGELOG.md b/v2/dboards/CHANGELOG.md
new file mode 100644
index 0000000..567c447
--- /dev/null
+++ b/v2/dboards/CHANGELOG.md
@@ -0,0 +1,217 @@
+vNext
+
+**Changes**
+- Use unix epoch for Graphite from/to for absolute time ranges (Closes #536)
+
+# 1.6.1 (2014-06-24)
+
+**New features or improvements**
+- Ability to set y min/max for right y-axis (RR #519, Closes #360) - thx @acedrew
+
+**Fixes**
+
+- Fixes regex InfluxDB queries intoduced in 1.6.0 (PR #500)
+- Bug in when using % sign in legends (aliases), fixed by removing url decoding of metric names (Fixes #506)
+- Series names and column name typeahead cache fix (Fixes #522)
+- Fixed influxdb issue with raw query that caused wrong value column detection (Fixes #504)
+- Default property that marks which datasource is default in config.js is now optional (Fixes #526)
+- Auto-refresh caused 2 refreshes (and hence mulitple queries) each time (at least in firefox) (Fixes #342)
+
+# 1.6.0 (2014-06-16)
+
+#### New features or improvements
+- New Y-axis formater for metric values that represent seconds (Issue #427) - thx @jippi
+- Allow special characters in serie names (influxdb datasource), PR #390 - thx @majst01
+- Refactoring of filterSrv (Issue #428), thx @Tetha
+- New config for playlist feature. Set playlist_timespan to set default playlist interval (Issue #445) - thx @rmca
+- New graphite function definition added isNonNull (PR #461), - thx @tmonk42
+- New InfluxDB function difference add to function dropdown (PR #455)
+- Added parameter to keepLastValue graphite function definition (default 100), Closes #459
+- improved asset (css/js) build pipeline, added revision to css and js. Will remove issues related
+ to the browser cache when upgrading grafana and improve load performance (Fixes #418)
+- Partial support for url encoded metrics when using Graphite datasource (PR #327) - thx @axe-felix
+- Improvement to InfluxDB query editor and function/value column selection (Issue #473)
+- Initial support for filtering (templated queries) for InfluxDB (PR #375) - thx @mavimo
+- Row editing and adding new panel is now a lot quicker and easier with the new row menu (Issue #475)
+- New datasource! Initial support for OpenTSDB (PR #211) - thx @mpage
+- Improvement and polish to the OpenTSDB query editor (Issue #492)
+- Influxdb group by support (Issue #441) thx @piis3
+
+
+#### Changes
+- Graphite panel is now renamed graph (Existing dashboards will still work)
+- Add panel icon and Row edit button is replaced by the Row edit menu (Issue #475)
+- New graphs now have a default empty query
+- Add Row button now creates a row with default height of 250px (no longer opens dashboard settings modal)
+- Clean up of config.sample.js, graphiteUrl removed (still works, but depricated, removed in future)
+ Use datasources config instead. panel_names removed from config.js. Use plugins.panels to add custom panels
+
+#### Fixes
+- Graphite query lexer change, can now handle regex parameters for aliasSub function (Fixes #126)
+- Filter option loading when having muliple nested filters now works better.
+ Options are now reloaded correctly and there are no multiple renders/refresh inbetween (#447),
+ After an option is changed and a nested template param is also reloaded, if the current value
+ exists after the options are reloaded the current selected value is kept (Closes #447, Closes #412)
+- Legend Current value did not display when value was zero, Fixes #460
+- Fix to series toggling bug that caused annotations to be hidden when toggling (hiding) series. Fixes #328
+- Fix for graphite function selection menu that some times draws outside screen. It now displays upward (Fixes #293)
+- Fix for exclusive series toggling (hold down CTRL, SHIFT or META key) and left click a series for exclusive toggling
+ CTRL does not work on MAC OSX but SHIFT or META should (depending on browser) (Closes #350, Fixes #472)
+
+# 1.5.4 (2014-05-13)
+### New features and improvements
+- InfluxDB enhancement: support for multiple hosts (with retries) and raw queries (Issue #318, thx @toddboom)
+- Added rounding for graphites from and to time range filters
+ for very short absolute ranges (Issue #320)
+- Increased resolution for graphite datapoints (maxDataPoints), now equal to panel pixel width. (Closes #5)
+- Improvement to influxdb query editor, can now add where clause and alias (Issue #331, thanks @mavimo)
+- New config setting for graphite datasource to control if json render request is POST or GET (Issue #345)
+- Unsaved changes warning feature (Issue #324)
+- Improvement to series toggling, CTRL+MouseClick on series name will now hide all others (Issue #350)
+
+### Changes
+- Graph default setting for Y-Min changed from zero to auto scalling (will not effect existing dashboards). (Issue #386) - thx @kamaradclimber
+
+### Fixes
+- Fixes to filters and "All" option. It now never uses "*" as value, but all options in a {node1, node2, node3} expression (Issue #228, #359)
+- Fix for InfluxDB query generation with columns containing dots or dashes (Issue #369, #348) - Thanks to @jbripley
+
+
+# 1.5.3 (2014-04-17)
+- Add support for async scripted dashboards (Issue #274)
+- Text panel now accepts html (for links to other dashboards, etc) (Issue #236)
+- Fix for Text panel, now changes take effect directly (Issue #251)
+- Fix when adding functions without params that did not cause graph to update (Issue #267)
+- Graphite errors are now much easier to see and troubleshoot with the new inspector (Issue #265)
+- Use influxdb aliases to distinguish between multiple columns (Issue #283)
+- Correction to ms axis formater, now formats days correctly. (Issue #189)
+- Css fix for Firefox and using top menu dropdowns in panel fullscren / edit mode (Issue #106)
+- Browser page title is now Grafana - {{dashboard title}} (Issue #294)
+- Disable auto refresh zooming in (every time you change to an absolute time range), refresh will be restored when you change time range back to relative (Issue #282)
+- More graphite functions
+
+# 1.5.2 (2014-03-24)
+### New Features and improvements
+- Support for second optional params for functions like aliasByNode (Issue #167). Read the wiki on the [Function Editor](https://github.com/torkelo/grafana/wiki/Graphite-Function-Editor) for more info.
+- More functions added to InfluxDB query editor (Issue #218)
+- Filters can now be used inside other filters (templated segments) (Issue #128)
+- More graphite functions added
+
+### Fixes
+- Float arguments now work for functions like scale (Issue #223)
+- Fix for graphite function editor, the graph & target was not updated after adding a function and leaving default params as is #191
+
+The zip files now contains a sub folder with project name and version prefix. (Issue #209)
+
+# 1.5.1 (2014-03-10)
+### Fixes
+- maxDataPoints must be an integer #184 (thanks @frejsoya for fixing this)
+
+For people who are find Grafana slow for large time spans or high resolution metrics. This is most likely due to graphite returning a large number of datapoints. The maxDataPoints parameter solves this issue. For maxDataPoints to work you need to run the latest graphite-web (some builds of 0.9.12 does not include this feature).
+
+Read this for more info:
+[Performance for large time spans](https://github.com/torkelo/grafana/wiki/Performance-for-large-time-spans)
+
+# 1.5.0 (2014-03-09)
+### New Features and improvements
+- New function editor [video demo](http://youtu.be/I90WHRwE1ZM) (Issue #178)
+- Links to function documentation from function editor (Issue #3)
+- Reorder functions (Issue #130)
+- [Initial support for InfluxDB](https://github.com/torkelo/grafana/wiki/InfluxDB) as metric datasource (#103), need feedback!
+- [Dashboard playlist](https://github.com/torkelo/grafana/wiki/Dashboard-playlist) (Issue #36)
+- When adding aliasByNode smartly set node number (Issue #175)
+- Support graphite identifiers with embedded colons (Issue #173)
+- Typeahead & autocomplete when adding new function (Issue #164)
+- More graphite function definitions
+- Make "ms" axis format include hour, day, weeks, month and year (Issue #149)
+- Microsecond axis format (Issue #146)
+- Specify template paramaters in URL (Issue #123)
+
+### Fixes
+- Basic Auth fix (Issue #152)
+- Fix to annotations with graphite source & null values (Issue #138)
+
+# 1.4.0 (2014-02-21)
+### New Features
+- #44 Annotations! Required a lot of work to get right. Read wiki article for more info. Supported annotations data sources are graphite metrics and graphite events. Support for more will be added in the future!
+- #35 Support for multiple graphite servers! (Read wiki article for more)
+- #116 Back to dashboard link in top menu to easily exist full screen / edit mode.
+- #114, #97 Legend values now use the same y axes formatter
+- #77 Improvements and polish to the light theme
+
+### Changes
+- #98 Stack is no longer by default turned on in graph display settings.
+- Hide controls (Ctrl+h) now hides the sub menu row (where filtering, and annotations are). So if you had filtering enabled and hide controls enabled you will not see the filtering sub menu.
+
+### Fixes:
+- #94 Fix for bug that caused dashboard settings to sometimes not contain timepicker tab.
+- #110 Graph with many many metrics caused legend to push down graph editor below screen. You can now scroll in edit mode & full screen mode for graphs with lots of series & legends.
+- #104 Improvement to graphite target editor, select wildcard now gives you a "select metric" link for the next node.
+- #105 Added zero as a possible node value in groupByAlias function
+
+# 1.3.0 (2014-02-13)
+### New features or improvements
+- #86 Dashboard tags and search (see wiki article for details)
+- #54 Enhancement to filter / template. "Include All" improvement
+- #82 Dashboard search result sorted in alphabetical order
+
+### Fixes
+- #91 Custom date selector is one day behind
+- #89 Filter / template does not work after switching dashboard
+- #88 Closed / Minimized row css bug
+- #85 Added all parameters to summarize function
+- #83 Stack as percent should now work a lot better!
+
+# 1.2.0 (2014-02-10)
+### New features
+- #70 Grid Thresholds (warning and error regions or lines in graph)
+- #72 Added an example of a scripted dashboard and a short wiki article documenting scripted dashboards.
+
+### Fixes
+- #81 Grid min/max values are ignored bug
+- #80 "stacked as percent" graphs should always use "max" value of 100 bug
+- #73 Left Y format change did not work
+- #42 Fixes to grid min/max auto scaling
+- #69 Fixes to lexer/parser for metrics segments like "10-20".
+- #67 Allow decimal input for scale function
+- #68 Bug when trying to open dashboard while in edit mode
+
+# 1.1.0 (2014-02-06)
+### New features:
+
+- #22 Support for native graphite png renderer, does not support click and select zoom yet
+- #60 Support for legend values (cactiStyle, min, max, current, total, avg). The options for these are found in the new "Axes & Grid" tab for now.
+- #62 There is now a "New" button in the search/open dashboard view to quickly open a clean empty dashboard.
+- #55 Basic auth is now supported for elastic search as well
+- some new function definitions added (will focus more on this for next release).
+
+### Fixes
+- #45 zero values from graphite was handled as null.
+- #63 Kibana / Grafana on same host would use same localStorage keys, now fixed
+- #46 Impossible to edit graph without a name fixed.
+- #24 fix for dashboard search when elastic search is configured to disable _all field.
+- #38 Improvement to lexer / parser to support pure numeric literals in metric segments
+
+Thanks to everyone who contributed fixes and provided feedback :+1:
+
+# 1.0.4 (2014-01-24)
+- Fixes #28 - Relative time range caused 500 graphite error in some cases (thx rsommer for the fix)
+
+# 1.0.3 (2014-01-23)
+- #9 Add Y-axis format for milliseconds
+- #16 Add support for Basic Auth (use http://username:password@yourgraphitedomain.com)
+- #13 Relative time ranges now uses relative time ranges when issuing graphite query
+
+# 1.0.2 (2014-01-21)
+- Fixes #12, should now work ok without ElasticSearch
+
+# 1.0.1 (2014-01-21)
+- Resize fix
+- Improvements to drag & drop
+- Added a few graphite function definitions
+- Fixed duplicate panel bug
+- Updated default dashboard with welcome message and randomWalk graph
+
+# 1.0.0 (2014-01-19)
+
+First public release
diff --git a/v2/dboards/CONTRIBUTING.md b/v2/dboards/CONTRIBUTING.md
new file mode 100644
index 0000000..405be40
--- /dev/null
+++ b/v2/dboards/CONTRIBUTING.md
@@ -0,0 +1,14 @@
+If you have any idea for an improvement or found a bug do not hesitate to open an issue.
+And if you have time clone this repo and submit a pull request and help me make Grafana the
+kickass metrics & devops dashboard we all dream about!
+
+Prerequisites:
+ - Nodejs (for jshint & grunt & development server)
+
+Clone repository:
+
+ npm install
+ grunt server (starts development web server in src folder)
+ grunt (runs jshint and less -> css compilation)
+
+Please remember to run grunt before doing pull request to verify that your code passes all the jshint validations.
diff --git a/v2/dboards/Gruntfile.js b/v2/dboards/Gruntfile.js
new file mode 100644
index 0000000..bcc542e
--- /dev/null
+++ b/v2/dboards/Gruntfile.js
@@ -0,0 +1,38 @@
+/* jshint node:true */
+'use strict';
+module.exports = function (grunt) {
+
+ var config = {
+ pkg: grunt.file.readJSON('package.json'),
+ baseDir: '.',
+ srcDir: 'src',
+ destDir: 'dist',
+ tempDir: 'tmp',
+ docsDir: 'docs/'
+ };
+
+ // load plugins
+ require('load-grunt-tasks')(grunt);
+
+ // load task definitions
+ grunt.loadTasks('tasks');
+
+ // Utility function to load plugin settings into config
+ function loadConfig(config,path) {
+ require('glob').sync('*', {cwd: path}).forEach(function(option) {
+ var key = option.replace(/\.js$/,'');
+ // If key already exists, extend it. It is your responsibility to avoid naming collisions
+ config[key] = config[key] || {};
+ grunt.util._.extend(config[key], require(path + option)(config,grunt));
+ });
+ // technically not required
+ return config;
+ }
+
+ // Merge that object with what with whatever we have here
+ loadConfig(config,'./tasks/options/');
+
+ // pass the config to grunt
+ grunt.initConfig(config);
+
+};
\ No newline at end of file
diff --git a/v2/dboards/LICENSE.md b/v2/dboards/LICENSE.md
new file mode 100644
index 0000000..1d66924
--- /dev/null
+++ b/v2/dboards/LICENSE.md
@@ -0,0 +1,14 @@
+Copyright 2012-2013 Elasticsearch BV, Torkel Ödegaard
+
+Licensed under the Apache License, Version 2.0 (the "License"); you
+may not use this file except in compliance with the License. You may
+obtain a copy of the License at
+
+ http://www.apache.org/licenses/LICENSE-2.0
+
+Unless required by applicable law or agreed to in writing, software
+distributed under the License is distributed on an "AS IS" BASIS,
+WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
+implied. See the License for the specific language governing
+permissions and limitations under the License.
+
diff --git a/v2/dboards/NOTICE.md b/v2/dboards/NOTICE.md
new file mode 100644
index 0000000..171332f
--- /dev/null
+++ b/v2/dboards/NOTICE.md
@@ -0,0 +1,16 @@
+
+This software is based on Kibana:
+========================================
+Copyright 2012-2013 Elasticsearch BV
+
+Licensed under the Apache License, Version 2.0 (the "License"); you
+may not use this file except in compliance with the License. You may
+obtain a copy of the License at
+
+ http://www.apache.org/licenses/LICENSE-2.0
+
+Unless required by applicable law or agreed to in writing, software
+distributed under the License is distributed on an "AS IS" BASIS,
+WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
+implied. See the License for the specific language governing
+permissions and limitations under the License.
diff --git a/v2/dboards/README.md b/v2/dboards/README.md
new file mode 100644
index 0000000..72062b0
--- /dev/null
+++ b/v2/dboards/README.md
@@ -0,0 +1,131 @@
+[Grafana](http://grafana.org) [![Build Status](https://api.travis-ci.org/grafana/grafana.png)](https://travis-ci.org/grafana/grafana)
+=================
+A beautiful, easy to use and feature rich Graphite dashboard replacement and graph editor. Visit [grafana.org](http://grafana.org) for screenshots, videos and feature descriptions.
+
+![](http://grafana.org/assets/img/edit_dashboards.png)
+
+## Features
+### Graphite Target Editor
+- Graphite target expression parser
+- Quickly add / edit / remove function ([video demo](http://youtu.be/I90WHRwE1ZM))
+- Function parameters can be easily changed
+- Quickly navigate graphite metric structure
+- Templating
+- Integrated links to function documentation
+- Rearrange function order
+- Native Graphite PNG render support
+
+### Graphing
+- Fast rendering, even over large timespans.
+- Click and drag to zoom.
+- Multiple Y-axis.
+- Bars, Lines, Points.
+- Smart Y-axis formating
+- Series toggles & color selector
+- Axis labels
+- Grid thresholds, axis labels
+- [Annotations] (https://github.com/grafana/grafana/wiki/Annotations)
+
+### Dashboards
+- Create and edit dashboards
+- Drag and drop graphs to rearrange
+- Set column spans and row heights
+- Save & [search dashboards](https://github.com/grafana/grafana/wiki/Search-features)
+- Import & export dashboard (json file)
+- Import dashboard from Graphite
+- Templating
+- [Scripted dashboards](https://github.com/grafana/grafana/wiki/Scripted-dashboards) (generate from js script and url parameters)
+- Flexible [time range controls](https://github.com/grafana/grafana/wiki/Time-range-controls)
+- [Dashboard playlists](https://github.com/grafana/grafana/wiki/Dashboard-playlist)
+
+### InfluxDB
+- [Use InfluxDB](https://github.com/grafana/grafana/wiki/InfluxDB) as metric datasource
+
+# Requirements
+Grafana is very easy to install. It is a client side web app with no backend. Any webserver will do. Optionally you will need ElasticSearch if you want to be able to save and load dashboards quickly instead of json files or local storage.
+
+# Installation
+- Download and extract the [latest release](https://github.com/grafana/grafana/releases).
+- Rename `config.sample.js` to `config.js`, then change `graphiteUrl` and `elasticsearch` to point to the correct urls. The urls entered here must be reachable by your browser.
+- Point your browser to the installation.
+
+To run from master:
+- Clone this repository
+- Start a web server in src folder
+- Or create a optimized & minified build:
+ - npm install (requires nodejs)
+ - grunt build (requires grunt-cli)
+
+If you use ansible for provisioning and deployment [ansible-grafana](https://github.com/bobrik/ansible-grafana) should get you started.
+
+When you have Grafana up an running, read the [Getting started](https://github.com/grafana/grafana/wiki/Getting-started) guide for
+an introduction on how to use Grafana and/or watch [this video](https://www.youtube.com/watch?v=OUvJamHeMpw) for a guide in creating a new dashboard and for creating
+templated dashboards.
+
+# Graphite server config
+If you haven't used an alternative dashboard for graphite before you need to enable cross-domain origin request. For Apache 2.x:
+```
+Header set Access-Control-Allow-Origin "*"
+Header set Access-Control-Allow-Methods "GET, OPTIONS"
+Header set Access-Control-Allow-Headers "origin, authorization, accept"
+```
+Note that using "\*" leaves your graphite instance quite open so you might want to consider using "http://my.graphite-dom.ain" in place of "\*"
+
+Here is the same thing, in nginx format:
+```
+add_header "Access-Control-Allow-Origin" "*";
+add_header "Access-Control-Allow-Credentials" "true";
+add_header "Access-Control-Allow-Methods" "GET, OPTIONS";
+add_header "Access-Control-Allow-Headers" "Authorization, origin, accept";
+```
+If your Graphite web is protected by basic authentication, you have to enable the HTTP verb OPTIONS, origin
+(no wildcards are allowed in this case) and add Access-Control-Allow-Credentials. This looks like the following for Apache:
+```
+Header set Access-Control-Allow-Origin "http://mygrafana.com:5656"
+Header set Access-Control-Allow-Credentials true
+
+
+ AuthName "graphs restricted"
+ AuthType Basic
+ AuthUserFile /etc/apache2/htpasswd
+
+ require valid-user
+
+
+```
+And in nginx:
+```
+auth_basic "Restricted";
+auth_basic_user_file /path/to/my/htpasswd/file;
+if ($http_origin ~* (https?://[^/]*\.somedomain\.com(:[0-9]+)?)) { #Test if request is from allowed domain, you can use multiple if
+ set $cors "true"; #statements to allow multiple domains, simply setting $cors to true in each one.
+}
+if ($cors = 'true') {
+ add_header Access-Control-Allow-Origin $http_origin; #this mirrors back whatever domain the request came from as authorized, as
+ add_header "Access-Control-Allow-Credentials" "true"; #as long as it matches one of your if statements
+ add_header "Access-Control-Allow-Methods" "GET, OPTIONS";
+ add_header "Access-Control-Allow-Headers" "Authorization, origin, accept";
+}
+```
+# Roadmap
+- Improve and refine the target parser and editing
+- Improve graphite import feature
+- Refine and simplify common tasks
+- More panel types (not just graphs)
+- Use elasticsearch to search for metrics
+- Improve template support
+- Annotate graph by querying ElasticSearch for events (or other event sources)
+
+# Contribute
+If you have any idea for an improvement or found a bug do not hesitate to open an issue. And if you have time clone this repo and submit a pull request and help me make Grafana the kickass metrics & devops dashboard we all dream about!
+
+Clone repository:
+- npm install
+- grunt server (starts development web server in src folder)
+- grunt (runs jshint and less -> css compilation)
+
+# Notice
+This software is based on the great log dashboard [kibana](https://github.com/elasticsearch/kibana).
+
+# License
+Grafana is distributed under Apache 2.0 License.
diff --git a/v2/dboards/grafana.sublime-project b/v2/dboards/grafana.sublime-project
new file mode 100644
index 0000000..127807d
--- /dev/null
+++ b/v2/dboards/grafana.sublime-project
@@ -0,0 +1,18 @@
+{
+ "folders":
+ [
+ {
+ "follow_symlinks": true,
+ "path": ".",
+ "folder_exclude_patterns": [
+ "node_modules"
+ ]
+ }
+ ],
+ "settings":
+ {
+ "tab_size": 2,
+ "translate_tabs_to_spaces": true,
+ "trim_trailing_white_space_on_save": true
+ }
+}
diff --git a/v2/dboards/latest.json b/v2/dboards/latest.json
new file mode 100644
index 0000000..458f3ba
--- /dev/null
+++ b/v2/dboards/latest.json
@@ -0,0 +1,4 @@
+{
+ "version": "1.6.0",
+ "url": "http://grafanarel.s3.amazonaws.com/grafana-1.6.0.tar.gz"
+}
\ No newline at end of file
diff --git a/v2/dboards/package.json b/v2/dboards/package.json
new file mode 100644
index 0000000..cb46712
--- /dev/null
+++ b/v2/dboards/package.json
@@ -0,0 +1,63 @@
+{
+ "author": {
+ "name": "Torkel Ödegaard",
+ "company": "Coding Instinct AB"
+ },
+ "name": "grafana",
+ "version": "1.6.1",
+ "repository": {
+ "type": "git",
+ "url": "http://github.com/torkelo/grafana.git"
+ },
+ "devDependencies": {
+ "rjs-build-analysis": "0.0.3",
+ "grunt": "~0.4.0",
+ "grunt-ngmin": "0.0.3",
+ "grunt-contrib-less": "~0.7.0",
+ "grunt-contrib-copy": "~0.4.1",
+ "grunt-git-describe": "~2.3.2",
+ "grunt-contrib-clean": "~0.5.0",
+ "grunt-contrib-cssmin": "~0.6.1",
+ "grunt-contrib-jshint": "~0.10.0",
+ "grunt-string-replace": "~0.2.4",
+ "grunt-contrib-htmlmin": "~0.1.3",
+ "grunt-contrib-requirejs": "~0.4.1",
+ "grunt-angular-templates": "^0.5.5",
+ "grunt-contrib-compress": "~0.5.2",
+ "grunt-contrib-uglify": "~0.2.4",
+ "load-grunt-tasks": "~0.2.0",
+ "glob": "~3.2.7",
+ "grunt-contrib-connect": "~0.5.0",
+ "mocha": "~1.16.1",
+ "expect.js": "~0.2.0",
+ "karma-script-launcher": "~0.1.0",
+ "karma-firefox-launcher": "~0.1.3",
+ "karma-chrome-launcher": "~0.1.4",
+ "karma-html2js-preprocessor": "~0.1.0",
+ "karma-jasmine": "~0.2.2",
+ "requirejs": "~2.1.9",
+ "karma-requirejs": "~0.2.1",
+ "karma-coffee-preprocessor": "~0.1.2",
+ "karma-phantomjs-launcher": "~0.1.1",
+ "karma": "~0.12.16",
+ "grunt-karma": "~0.8.3",
+ "karma-mocha": "~0.1.4",
+ "karma-expect": "~1.1.0",
+ "grunt-cli": "~0.1.13",
+ "jshint-stylish": "~0.1.5",
+ "grunt-contrib-concat": "^0.4.0",
+ "grunt-usemin": "^2.1.1",
+ "grunt-filerev": "^0.2.1"
+ },
+ "engines": {
+ "node": "0.10.x",
+ "npm": "1.2.x"
+ },
+ "scripts": {
+ "test": "grunt test"
+ },
+ "license": "Apache License",
+ "dependencies": {
+ "grunt-jscs-checker": "^0.4.4"
+ }
+}
diff --git a/v2/dboards/sample/apache_ldap.conf b/v2/dboards/sample/apache_ldap.conf
new file mode 100644
index 0000000..f7df159
--- /dev/null
+++ b/v2/dboards/sample/apache_ldap.conf
@@ -0,0 +1,61 @@
+# Courtesy of https://github.com/sgzijl
+# config.js includes elasticsearch: "https://"+window.location.hostname+":443",
+
+
+ ServerName your.domain.tld
+ RewriteEngine On
+ RewriteCond %{HTTPS} off
+ RewriteRule (.*) https://%{HTTP_HOST}%{REQUEST_URI}
+
+
+
+ ServerName your.domain.tld
+
+ SSLEngine on
+ SSLCertificateFile /path/to/public.crt
+ SSLCertificateKeyFile /path/to/private.key
+
+ DocumentRoot /path/to/kibana3
+
+ Allow from all
+ Options -Multiviews
+
+
+ LogLevel debug
+ ErrorLog /path/to/logs/error_log
+ CustomLog /path/to/logs/access_log combined
+
+ # Set global proxy timeouts
+
+ ProxySet connectiontimeout=5 timeout=90
+
+
+ # Proxy for _aliases and .*/_search
+
+ ProxyPassMatch http://127.0.0.1:9200/$1
+ ProxyPassReverse http://127.0.0.1:9200/$1
+
+
+ # Proxy for kibana-int/{dashboard,temp} stuff (if you don't want auth on /, then you will want these to be protected)
+
+ ProxyPassMatch http://127.0.0.1:9200/$1$2
+ ProxyPassReverse http://127.0.0.1:9200/$1$2
+
+
+ # Optional disable auth for a src IP (eg: your monitoring host or subnet)
+
+ Allow from 5.6.7.8
+ Deny from all
+ Satisfy any
+
+ AuthLDAPBindDN "CN=_ldapbinduser,OU=Users,DC=example,DC=com"
+ AuthLDAPBindPassword "ldapbindpass"
+ AuthLDAPURL "ldaps://ldap01.example.com ldap02.example.com/OU=Users,DC=example,DC=com?sAMAccountName?sub?(objectClass=*)"
+ AuthType Basic
+ AuthBasicProvider ldap
+ AuthName "Please authenticate for Example dot com"
+ AuthLDAPGroupAttributeIsDN on
+ require valid-user
+
+
+
diff --git a/v2/dboards/sample/lighttpd_basic.conf b/v2/dboards/sample/lighttpd_basic.conf
new file mode 100644
index 0000000..667a6ab
--- /dev/null
+++ b/v2/dboards/sample/lighttpd_basic.conf
@@ -0,0 +1,24 @@
+$HTTP["host"] =~ "kibana" {
+
+ server.document-root = "/var/ww/kibana/src"
+ auth.backend = "plain"
+ auth.backend.plain.userfile = "/etc/lighttpd/kibanapassword"
+
+ index-file.names = ( "index.html", "index.htm" )
+
+ auth.require = ( "/" => (
+ "method" => "basic",
+ "realm" => "Password Protected",
+ "require" => "valid-user"
+ )
+ )
+
+ $HTTP["url"] =~ "^/kibana-int/(dashboard/|temp).*$" {
+ proxy.balance = "hash"
+ proxy.server = ( "" => ( ( "host" => "127.0.0.1", "port" => "9200" ) ) )
+ }
+ $HTTP["url"] =~ "^.*/_(mapping|search|nodes|aliases)$" {
+ proxy.balance = "hash"
+ proxy.server = ( "" => ( ( "host" => "127.0.0.1", "port" => "9200" ) ) )
+ }
+}
diff --git a/v2/dboards/sample/nginx.conf b/v2/dboards/sample/nginx.conf
new file mode 100644
index 0000000..b1e2f36
--- /dev/null
+++ b/v2/dboards/sample/nginx.conf
@@ -0,0 +1,60 @@
+#
+# Nginx proxy for Elasticsearch + Kibana
+#
+# In this setup, we are password protecting the saving of dashboards. You may
+# wish to extend the password protection to all paths.
+#
+# Even though these paths are being called as the result of an ajax request, the
+# browser will prompt for a username/password on the first request
+#
+# If you use this, you'll want to point config.js at http://FQDN:80/ instead of
+# http://FQDN:9200
+#
+server {
+ listen *:80 ;
+
+ server_name kibana.myhost.org;
+ access_log /var/log/nginx/kibana.myhost.org.access.log;
+
+ location / {
+ root /usr/share/kibana3;
+ index index.html index.htm;
+ }
+
+ location ~ ^/_aliases$ {
+ proxy_pass http://127.0.0.1:9200;
+ proxy_read_timeout 90;
+ }
+ location ~ ^/_nodes$ {
+ proxy_pass http://127.0.0.1:9200;
+ proxy_read_timeout 90;
+ }
+ location ~ ^/.*/_search$ {
+ proxy_pass http://127.0.0.1:9200;
+ proxy_read_timeout 90;
+ }
+ location ~ ^/.*/_mapping$ {
+ proxy_pass http://127.0.0.1:9200;
+ proxy_read_timeout 90;
+ }
+
+ # Password protected end points
+ location ~ ^/kibana-int/dashboard/.*$ {
+ proxy_pass http://127.0.0.1:9200;
+ proxy_read_timeout 90;
+ limit_except GET {
+ proxy_pass http://127.0.0.1:9200;
+ auth_basic "Restricted";
+ auth_basic_user_file /etc/nginx/conf.d/kibana.myhost.org.htpasswd;
+ }
+ }
+ location ~ ^/kibana-int/temp.*$ {
+ proxy_pass http://127.0.0.1:9200;
+ proxy_read_timeout 90;
+ limit_except GET {
+ proxy_pass http://127.0.0.1:9200;
+ auth_basic "Restricted";
+ auth_basic_user_file /etc/nginx/conf.d/kibana.myhost.org.htpasswd;
+ }
+ }
+}
diff --git a/v2/dboards/sample/server.js b/v2/dboards/sample/server.js
new file mode 100644
index 0000000..d976a48
--- /dev/null
+++ b/v2/dboards/sample/server.js
@@ -0,0 +1,244 @@
+#!/usr/bin/env node
+
+var util = require('util'),
+ http = require('http'),
+ fs = require('fs'),
+ url = require('url'),
+ events = require('events');
+
+var DEFAULT_PORT = 8000;
+
+function main(argv) {
+ new HttpServer({
+ 'GET': createServlet(StaticServlet),
+ 'HEAD': createServlet(StaticServlet)
+ }).start(Number(argv[2]) || DEFAULT_PORT);
+}
+
+function escapeHtml(value) {
+ return value.toString().
+ replace('<', '<').
+ replace('>', '>').
+ replace('"', '"');
+}
+
+function createServlet(Class) {
+ var servlet = new Class();
+ return servlet.handleRequest.bind(servlet);
+}
+
+/**
+ * An Http server implementation that uses a map of methods to decide
+ * action routing.
+ *
+ * @param {Object} Map of method => Handler function
+ */
+function HttpServer(handlers) {
+ this.handlers = handlers;
+ this.server = http.createServer(this.handleRequest_.bind(this));
+}
+
+HttpServer.prototype.start = function(port) {
+ this.port = port;
+ this.server.listen(port);
+ util.puts('Http Server running at http://localhost:' + port + '/');
+};
+
+HttpServer.prototype.parseUrl_ = function(urlString) {
+ var parsed = url.parse(urlString);
+ parsed.pathname = url.resolve('/', parsed.pathname);
+ return url.parse(url.format(parsed), true);
+};
+
+HttpServer.prototype.handleRequest_ = function(req, res) {
+ var logEntry = req.method + ' ' + req.url;
+ if (req.headers['user-agent']) {
+ logEntry += ' ' + req.headers['user-agent'];
+ }
+ util.puts(logEntry);
+ req.url = this.parseUrl_(req.url);
+ var handler = this.handlers[req.method];
+ if (!handler) {
+ res.writeHead(501);
+ res.end();
+ } else {
+ handler.call(this, req, res);
+ }
+};
+
+/**
+ * Handles static content.
+ */
+function StaticServlet() {}
+
+StaticServlet.MimeMap = {
+ 'txt': 'text/plain',
+ 'html': 'text/html',
+ 'css': 'text/css',
+ 'xml': 'application/xml',
+ 'json': 'application/json',
+ 'js': 'application/javascript',
+ 'jpg': 'image/jpeg',
+ 'jpeg': 'image/jpeg',
+ 'gif': 'image/gif',
+ 'png': 'image/png',
+ 'svg': 'image/svg+xml'
+};
+
+StaticServlet.prototype.handleRequest = function(req, res) {
+ var self = this;
+ var path = ('../src/' + req.url.pathname).replace('//','/').replace(/%(..)/g, function(match, hex){
+ return String.fromCharCode(parseInt(hex, 16));
+ });
+ var parts = path.split('/');
+ if (parts[parts.length-1].charAt(0) === '.')
+ return self.sendForbidden_(req, res, path);
+ fs.stat(path, function(err, stat) {
+ if (err)
+ return self.sendMissing_(req, res, path);
+ if (stat.isDirectory())
+ return self.sendDirectory_(req, res, path);
+ return self.sendFile_(req, res, path);
+ });
+}
+
+StaticServlet.prototype.sendError_ = function(req, res, error) {
+ res.writeHead(500, {
+ 'Content-Type': 'text/html'
+ });
+ res.write('\n');
+ res.write('Internal Server Error\n');
+ res.write('
+
+
\ No newline at end of file
diff --git a/v2/dboards/src/app/panels/annotations/module.html b/v2/dboards/src/app/panels/annotations/module.html
new file mode 100644
index 0000000..0441ed1
--- /dev/null
+++ b/v2/dboards/src/app/panels/annotations/module.html
@@ -0,0 +1,12 @@
+
+ No datapoints Can be caused by timezone mismatch between browser and graphite server
+ Datapoints outside time range Can be caused by timezone mismatch between browser and graphite server
+
");});
+
+ // atx-style headers:
+ // # Header 1
+ // ## Header 2
+ // ## Header 2 with closing hashes ##
+ // ...
+ // ###### Header 6
+ //
+
+ /*
+ text = text.replace(/
+ ^(\#{1,6}) // $1 = string of #'s
+ [ \t]*
+ (.+?) // $2 = Header text
+ [ \t]*
+ \#* // optional closing #'s (not counted)
+ \n+
+ /gm, function() {...});
+ */
+
+ text = text.replace(/^(\#{1,6})[ \t]*(.+?)[ \t]*\#*\n+/gm,
+ function(wholeMatch,m1,m2) {
+ var h_level = m1.length;
+ return hashBlock("' + _RunSpanGamut(m2) + "");
+ });
+
+ function headerId(m) {
+ return m.replace(/[^\w]/g, '').toLowerCase();
+ }
+ return text;
+}
+
+// This declaration keeps Dojo compressor from outputting garbage:
+var _ProcessListItems;
+
+var _DoLists = function(text) {
+//
+// Form HTML ordered (numbered) and unordered (bulleted) lists.
+//
+
+ // attacklab: add sentinel to hack around khtml/safari bug:
+ // http://bugs.webkit.org/show_bug.cgi?id=11231
+ text += "~0";
+
+ // Re-usable pattern to match any entirel ul or ol list:
+
+ /*
+ var whole_list = /
+ ( // $1 = whole list
+ ( // $2
+ [ ]{0,3} // attacklab: g_tab_width - 1
+ ([*+-]|\d+[.]) // $3 = first list item marker
+ [ \t]+
+ )
+ [^\r]+?
+ ( // $4
+ ~0 // sentinel for workaround; should be $
+ |
+ \n{2,}
+ (?=\S)
+ (?! // Negative lookahead for another list item marker
+ [ \t]*
+ (?:[*+-]|\d+[.])[ \t]+
+ )
+ )
+ )/g
+ */
+ var whole_list = /^(([ ]{0,3}([*+-]|\d+[.])[ \t]+)[^\r]+?(~0|\n{2,}(?=\S)(?![ \t]*(?:[*+-]|\d+[.])[ \t]+)))/gm;
+
+ if (g_list_level) {
+ text = text.replace(whole_list,function(wholeMatch,m1,m2) {
+ var list = m1;
+ var list_type = (m2.search(/[*+-]/g)>-1) ? "ul" : "ol";
+
+ // Turn double returns into triple returns, so that we can make a
+ // paragraph for the last item in a list, if necessary:
+ list = list.replace(/\n{2,}/g,"\n\n\n");;
+ var result = _ProcessListItems(list);
+
+ // Trim any trailing whitespace, to put the closing `$list_type>`
+ // up on the preceding line, to get it past the current stupid
+ // HTML block parser. This is a hack to work around the terrible
+ // hack that is the HTML block parser.
+ result = result.replace(/\s+$/,"");
+ result = "<"+list_type+">" + result + ""+list_type+">\n";
+ return result;
+ });
+ } else {
+ whole_list = /(\n\n|^\n?)(([ ]{0,3}([*+-]|\d+[.])[ \t]+)[^\r]+?(~0|\n{2,}(?=\S)(?![ \t]*(?:[*+-]|\d+[.])[ \t]+)))/g;
+ text = text.replace(whole_list,function(wholeMatch,m1,m2,m3) {
+ var runup = m1;
+ var list = m2;
+
+ var list_type = (m3.search(/[*+-]/g)>-1) ? "ul" : "ol";
+ // Turn double returns into triple returns, so that we can make a
+ // paragraph for the last item in a list, if necessary:
+ var list = list.replace(/\n{2,}/g,"\n\n\n");;
+ var result = _ProcessListItems(list);
+ result = runup + "<"+list_type+">\n" + result + ""+list_type+">\n";
+ return result;
+ });
+ }
+
+ // attacklab: strip sentinel
+ text = text.replace(/~0/,"");
+
+ return text;
+}
+
+_ProcessListItems = function(list_str) {
+//
+// Process the contents of a single ordered or unordered list, splitting it
+// into individual list items.
+//
+ // The $g_list_level global keeps track of when we're inside a list.
+ // Each time we enter a list, we increment it; when we leave a list,
+ // we decrement. If it's zero, we're not in a list anymore.
+ //
+ // We do this because when we're not inside a list, we want to treat
+ // something like this:
+ //
+ // I recommend upgrading to version
+ // 8. Oops, now this line is treated
+ // as a sub-list.
+ //
+ // As a single paragraph, despite the fact that the second line starts
+ // with a digit-period-space sequence.
+ //
+ // Whereas when we're inside a list (or sub-list), that line will be
+ // treated as the start of a sub-list. What a kludge, huh? This is
+ // an aspect of Markdown's syntax that's hard to parse perfectly
+ // without resorting to mind-reading. Perhaps the solution is to
+ // change the syntax rules such that sub-lists must start with a
+ // starting cardinal number; e.g. "1." or "a.".
+
+ g_list_level++;
+
+ // trim trailing blank lines:
+ list_str = list_str.replace(/\n{2,}$/,"\n");
+
+ // attacklab: add sentinel to emulate \z
+ list_str += "~0";
+
+ /*
+ list_str = list_str.replace(/
+ (\n)? // leading line = $1
+ (^[ \t]*) // leading whitespace = $2
+ ([*+-]|\d+[.]) [ \t]+ // list marker = $3
+ ([^\r]+? // list item text = $4
+ (\n{1,2}))
+ (?= \n* (~0 | \2 ([*+-]|\d+[.]) [ \t]+))
+ /gm, function(){...});
+ */
+ list_str = list_str.replace(/(\n)?(^[ \t]*)([*+-]|\d+[.])[ \t]+([^\r]+?(\n{1,2}))(?=\n*(~0|\2([*+-]|\d+[.])[ \t]+))/gm,
+ function(wholeMatch,m1,m2,m3,m4){
+ var item = m4;
+ var leading_line = m1;
+ var leading_space = m2;
+
+ if (leading_line || (item.search(/\n{2,}/)>-1)) {
+ item = _RunBlockGamut(_Outdent(item));
+ }
+ else {
+ // Recursion for sub-lists:
+ item = _DoLists(_Outdent(item));
+ item = item.replace(/\n$/,""); // chomp(item)
+ item = _RunSpanGamut(item);
+ }
+
+ return "
` blocks.
+//
+
+ /*
+ text = text.replace(text,
+ /(?:\n\n|^)
+ ( // $1 = the code block -- one or more lines, starting with a space/tab
+ (?:
+ (?:[ ]{4}|\t) // Lines must start with a tab or a tab-width of spaces - attacklab: g_tab_width
+ .*\n+
+ )+
+ )
+ (\n*[ ]{0,3}[^ \t\n]|(?=~0)) // attacklab: g_tab_width
+ /g,function(){...});
+ */
+
+ // attacklab: sentinel workarounds for lack of \A and \Z, safari\khtml bug
+ text += "~0";
+
+ text = text.replace(/(?:\n\n|^)((?:(?:[ ]{4}|\t).*\n+)+)(\n*[ ]{0,3}[^ \t\n]|(?=~0))/g,
+ function(wholeMatch,m1,m2) {
+ var codeblock = m1;
+ var nextChar = m2;
+
+ codeblock = _EncodeCode( _Outdent(codeblock));
+ codeblock = _Detab(codeblock);
+ codeblock = codeblock.replace(/^\n+/g,""); // trim leading newlines
+ codeblock = codeblock.replace(/\n+$/g,""); // trim trailing whitespace
+
+ codeblock = "
" + codeblock + "\n
";
+
+ return hashBlock(codeblock) + nextChar;
+ }
+ );
+
+ // attacklab: strip sentinel
+ text = text.replace(/~0/,"");
+
+ return text;
+};
+
+var _DoGithubCodeBlocks = function(text) {
+//
+// Process Github-style code blocks
+// Example:
+// ```ruby
+// def hello_world(x)
+// puts "Hello, #{x}"
+// end
+// ```
+//
+
+
+ // attacklab: sentinel workarounds for lack of \A and \Z, safari\khtml bug
+ text += "~0";
+
+ text = text.replace(/(?:^|\n)```(.*)\n([\s\S]*?)\n```/g,
+ function(wholeMatch,m1,m2) {
+ var language = m1;
+ var codeblock = m2;
+
+ codeblock = _EncodeCode(codeblock);
+ codeblock = _Detab(codeblock);
+ codeblock = codeblock.replace(/^\n+/g,""); // trim leading newlines
+ codeblock = codeblock.replace(/\n+$/g,""); // trim trailing whitespace
+
+ codeblock = "
" + codeblock + "\n
";
+
+ return hashBlock(codeblock);
+ }
+ );
+
+ // attacklab: strip sentinel
+ text = text.replace(/~0/,"");
+
+ return text;
+}
+
+var hashBlock = function(text) {
+ text = text.replace(/(^\n+|\n+$)/g,"");
+ return "\n\n~K" + (g_html_blocks.push(text)-1) + "K\n\n";
+}
+
+var _DoCodeSpans = function(text) {
+//
+// * Backtick quotes are used for spans.
+//
+// * You can use multiple backticks as the delimiters if you want to
+// include literal backticks in the code span. So, this input:
+//
+// Just type ``foo `bar` baz`` at the prompt.
+//
+// Will translate to:
+//
+//
Just type foo `bar` baz at the prompt.
+//
+// There's no arbitrary limit to the number of backticks you
+// can use as delimters. If you need three consecutive backticks
+// in your code, use four for delimiters, etc.
+//
+// * You can use spaces to get literal backticks at the edges:
+//
+// ... type `` `bar` `` ...
+//
+// Turns to:
+//
+// ... type `bar` ...
+//
+
+ /*
+ text = text.replace(/
+ (^|[^\\]) // Character before opening ` can't be a backslash
+ (`+) // $2 = Opening run of `
+ ( // $3 = The code block
+ [^\r]*?
+ [^`] // attacklab: work around lack of lookbehind
+ )
+ \2 // Matching closer
+ (?!`)
+ /gm, function(){...});
+ */
+
+ text = text.replace(/(^|[^\\])(`+)([^\r]*?[^`])\2(?!`)/gm,
+ function(wholeMatch,m1,m2,m3,m4) {
+ var c = m3;
+ c = c.replace(/^([ \t]*)/g,""); // leading whitespace
+ c = c.replace(/[ \t]*$/g,""); // trailing whitespace
+ c = _EncodeCode(c);
+ return m1+""+c+"";
+ });
+
+ return text;
+}
+
+var _EncodeCode = function(text) {
+//
+// Encode/escape certain characters inside Markdown code runs.
+// The point is that in code, these characters are literals,
+// and lose their special Markdown meanings.
+//
+ // Encode all ampersands; HTML entities are not
+ // entities within a Markdown code span.
+ text = text.replace(/&/g,"&");
+
+ // Do the angle bracket song and dance:
+ text = text.replace(//g,">");
+
+ // Now, escape characters that are magic in Markdown:
+ text = escapeCharacters(text,"\*_{}[]\\",false);
+
+// jj the line above breaks this:
+//---
+
+//* Item
+
+// 1. Subitem
+
+// special char: *
+//---
+
+ return text;
+}
+
+
+var _DoItalicsAndBold = function(text) {
+
+ // must go first:
+ text = text.replace(/(\*\*|__)(?=\S)([^\r]*?\S[*_]*)\1/g,
+ "$2");
+
+ text = text.replace(/(\*|_)(?=\S)([^\r]*?\S)\1/g,
+ "$2");
+
+ return text;
+}
+
+
+var _DoBlockQuotes = function(text) {
+
+ /*
+ text = text.replace(/
+ ( // Wrap whole match in $1
+ (
+ ^[ \t]*>[ \t]? // '>' at the start of a line
+ .+\n // rest of the first line
+ (.+\n)* // subsequent consecutive lines
+ \n* // blanks
+ )+
+ )
+ /gm, function(){...});
+ */
+
+ text = text.replace(/((^[ \t]*>[ \t]?.+\n(.+\n)*\n*)+)/gm,
+ function(wholeMatch,m1) {
+ var bq = m1;
+
+ // attacklab: hack around Konqueror 3.5.4 bug:
+ // "----------bug".replace(/^-/g,"") == "bug"
+
+ bq = bq.replace(/^[ \t]*>[ \t]?/gm,"~0"); // trim one level of quoting
+
+ // attacklab: clean up hack
+ bq = bq.replace(/~0/g,"");
+
+ bq = bq.replace(/^[ \t]+$/gm,""); // trim whitespace-only lines
+ bq = _RunBlockGamut(bq); // recurse
+
+ bq = bq.replace(/(^|\n)/g,"$1 ");
+ // These leading spaces screw with
content, so we need to fix that:
+ bq = bq.replace(
+ /(\s*
[^\r]+?<\/pre>)/gm,
+ function(wholeMatch,m1) {
+ var pre = m1;
+ // attacklab: hack around Konqueror 3.5.4 bug:
+ pre = pre.replace(/^ /mg,"~0");
+ pre = pre.replace(/~0/g,"");
+ return pre;
+ });
+
+ return hashBlock("
\n" + bq + "\n
");
+ });
+ return text;
+}
+
+
+var _FormParagraphs = function(text) {
+//
+// Params:
+// $text - string to process with html
tags
+//
+
+ // Strip leading and trailing lines:
+ text = text.replace(/^\n+/g,"");
+ text = text.replace(/\n+$/g,"");
+
+ var grafs = text.split(/\n{2,}/g);
+ var grafsOut = [];
+
+ //
+ // Wrap
tags.
+ //
+ var end = grafs.length;
+ for (var i=0; i= 0) {
+ grafsOut.push(str);
+ }
+ else if (str.search(/\S/) >= 0) {
+ str = _RunSpanGamut(str);
+ str = str.replace(/^([ \t]*)/g,"
");
+ str += "
"
+ grafsOut.push(str);
+ }
+
+ }
+
+ //
+ // Unhashify HTML blocks
+ //
+ end = grafsOut.length;
+ for (var i=0; i= 0) {
+ var blockText = g_html_blocks[RegExp.$1];
+ blockText = blockText.replace(/\$/g,"$$$$"); // Escape any dollar signs
+ grafsOut[i] = grafsOut[i].replace(/~K\d+K/,blockText);
+ }
+ }
+
+ return grafsOut.join("\n\n");
+}
+
+
+var _EncodeAmpsAndAngles = function(text) {
+// Smart processing for ampersands and angle brackets that need to be encoded.
+
+ // Ampersand-encoding based entirely on Nat Irons's Amputator MT plugin:
+ // http://bumppo.net/projects/amputator/
+ text = text.replace(/&(?!#?[xX]?(?:[0-9a-fA-F]+|\w+);)/g,"&");
+
+ // Encode naked <'s
+ text = text.replace(/<(?![a-z\/?\$!])/gi,"<");
+
+ return text;
+}
+
+
+var _EncodeBackslashEscapes = function(text) {
+//
+// Parameter: String.
+// Returns: The string, with after processing the following backslash
+// escape sequences.
+//
+
+ // attacklab: The polite way to do this is with the new
+ // escapeCharacters() function:
+ //
+ // text = escapeCharacters(text,"\\",true);
+ // text = escapeCharacters(text,"`*_{}[]()>#+-.!",true);
+ //
+ // ...but we're sidestepping its use of the (slow) RegExp constructor
+ // as an optimization for Firefox. This function gets called a LOT.
+
+ text = text.replace(/\\(\\)/g,escapeCharacters_callback);
+ text = text.replace(/\\([`*_{}\[\]()>#+-.!])/g,escapeCharacters_callback);
+ return text;
+}
+
+
+var _DoAutoLinks = function(text) {
+
+ text = text.replace(/<((https?|ftp|dict):[^'">\s]+)>/gi,"$1");
+
+ // Email addresses:
+
+ /*
+ text = text.replace(/
+ <
+ (?:mailto:)?
+ (
+ [-.\w]+
+ \@
+ [-a-z0-9]+(\.[-a-z0-9]+)*\.[a-z]+
+ )
+ >
+ /gi, _DoAutoLinks_callback());
+ */
+ text = text.replace(/<(?:mailto:)?([-.\w]+\@[-a-z0-9]+(\.[-a-z0-9]+)*\.[a-z]+)>/gi,
+ function(wholeMatch,m1) {
+ return _EncodeEmailAddress( _UnescapeSpecialChars(m1) );
+ }
+ );
+
+ return text;
+}
+
+
+var _EncodeEmailAddress = function(addr) {
+//
+// Input: an email address, e.g. "foo@example.com"
+//
+// Output: the email address as a mailto link, with each character
+// of the address encoded as either a decimal or hex entity, in
+// the hopes of foiling most address harvesting spam bots. E.g.:
+//
+// foo
+// @example.com
+//
+// Based on a filter by Matthew Wickline, posted to the BBEdit-Talk
+// mailing list:
+//
+
+ var encode = [
+ function(ch){return ""+ch.charCodeAt(0)+";";},
+ function(ch){return ""+ch.charCodeAt(0).toString(16)+";";},
+ function(ch){return ch;}
+ ];
+
+ addr = "mailto:" + addr;
+
+ addr = addr.replace(/./g, function(ch) {
+ if (ch == "@") {
+ // this *must* be encoded. I insist.
+ ch = encode[Math.floor(Math.random()*2)](ch);
+ } else if (ch !=":") {
+ // leave ':' alone (to spot mailto: later)
+ var r = Math.random();
+ // roughly 10% raw, 45% hex, 45% dec
+ ch = (
+ r > .9 ? encode[2](ch) :
+ r > .45 ? encode[1](ch) :
+ encode[0](ch)
+ );
+ }
+ return ch;
+ });
+
+ addr = "" + addr + "";
+ addr = addr.replace(/">.+:/g,"\">"); // strip the mailto: from the visible part
+
+ return addr;
+}
+
+
+var _UnescapeSpecialChars = function(text) {
+//
+// Swap back in all the special characters we've hidden.
+//
+ text = text.replace(/~E(\d+)E/g,
+ function(wholeMatch,m1) {
+ var charCodeToReplace = parseInt(m1);
+ return String.fromCharCode(charCodeToReplace);
+ }
+ );
+ return text;
+}
+
+
+var _Outdent = function(text) {
+//
+// Remove one level of line-leading tabs or spaces
+//
+
+ // attacklab: hack around Konqueror 3.5.4 bug:
+ // "----------bug".replace(/^-/g,"") == "bug"
+
+ text = text.replace(/^(\t|[ ]{1,4})/gm,"~0"); // attacklab: g_tab_width
+
+ // attacklab: clean up hack
+ text = text.replace(/~0/g,"")
+
+ return text;
+}
+
+var _Detab = function(text) {
+// attacklab: Detab's completely rewritten for speed.
+// In perl we could fix it by anchoring the regexp with \G.
+// In javascript we're less fortunate.
+
+ // expand first n-1 tabs
+ text = text.replace(/\t(?=\t)/g," "); // attacklab: g_tab_width
+
+ // replace the nth with two sentinels
+ text = text.replace(/\t/g,"~A~B");
+
+ // use the sentinel to anchor our regex so it doesn't explode
+ text = text.replace(/~B(.+?)~A/g,
+ function(wholeMatch,m1,m2) {
+ var leadingText = m1;
+ var numSpaces = 4 - leadingText.length % 4; // attacklab: g_tab_width
+
+ // there *must* be a better way to do this:
+ for (var i=0; i
+
+
+ {{panel.content}}
+
+
+
+
+
+
diff --git a/v2/dboards/src/app/panels/text/module.js b/v2/dboards/src/app/panels/text/module.js
new file mode 100644
index 0000000..37735d3
--- /dev/null
+++ b/v2/dboards/src/app/panels/text/module.js
@@ -0,0 +1,101 @@
+/** @scratch /panels/5
+ * include::panels/text.asciidoc[]
+ */
+
+/** @scratch /panels/text/0
+ * == text
+ * Status: *Stable*
+ *
+ * The text panel is used for displaying static text formated as markdown, sanitized html or as plain
+ * text.
+ *
+ */
+define([
+ 'angular',
+ 'app',
+ 'underscore',
+ 'require'
+],
+function (angular, app, _, require) {
+ 'use strict';
+
+ var module = angular.module('kibana.panels.text', []);
+ app.useModule(module);
+
+ module.controller('text', function($scope) {
+
+ $scope.panelMeta = {
+ description : "A static text panel that can use plain text, markdown, or (sanitized) HTML"
+ };
+
+ // Set and populate defaults
+ var _d = {
+ mode : "markdown", // 'html', 'markdown', 'text'
+ content : "",
+ style: {},
+ };
+
+ _.defaults($scope.panel,_d);
+
+ $scope.init = function() {
+ $scope.initBaseController(this, $scope);
+
+ $scope.ready = false;
+ };
+
+ $scope.render = function() {
+ $scope.$emit('render');
+ };
+
+ $scope.openEditor = function() {
+ //$scope.$emit('open-modal','paneleditor');
+ console.log('scope id', $scope.$id);
+ };
+
+ });
+
+ module.directive('markdown', function() {
+ return {
+ restrict: 'E',
+ link: function(scope, element) {
+ scope.$on('render', function() {
+ render_panel();
+ });
+
+ function render_panel() {
+ require(['./lib/showdown'], function (Showdown) {
+ scope.ready = true;
+ var converter = new Showdown.converter();
+ var text = scope.panel.content.replace(/&/g, '&')
+ .replace(/>/g, '>')
+ .replace(/');
+ };
+ });
+
+ module.filter('striphtml', function () {
+ return function(text) {
+ return text
+ .replace(/&/g, '&')
+ .replace(/>/g, '>')
+ .replace(/
+
+
+
\ No newline at end of file
diff --git a/v2/dboards/src/app/partials/dashLoaderShare.html b/v2/dboards/src/app/partials/dashLoaderShare.html
new file mode 100644
index 0000000..7769773
--- /dev/null
+++ b/v2/dboards/src/app/partials/dashLoaderShare.html
@@ -0,0 +1,11 @@
+
+
+
{{share.title}} shareable link
+
+
+
+
+
+
diff --git a/v2/dboards/src/app/partials/dashboard.html b/v2/dboards/src/app/partials/dashboard.html
new file mode 100644
index 0000000..0c49761
--- /dev/null
+++ b/v2/dboards/src/app/partials/dashboard.html
@@ -0,0 +1,110 @@
+
+
\ No newline at end of file
diff --git a/v2/dboards/src/app/partials/dasheditor.html b/v2/dboards/src/app/partials/dasheditor.html
new file mode 100644
index 0000000..4ad8078
--- /dev/null
+++ b/v2/dboards/src/app/partials/dasheditor.html
@@ -0,0 +1,161 @@
+
+
Dashboard settings
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+ Press enter to a add tag
+
+
+
+
+
+
+
+
+
Rows
+
+
+
+
+
+
Title
+
+
+
+
+
+
{{row.title}}
+
+
+
+
+
Add Row
+
+
+
+
+
+
+
+
+
+
+
+
Save to
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
Load from
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
Sharing
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
Feature toggles
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
\ No newline at end of file
diff --git a/v2/dboards/src/app/partials/graphite/editor.html b/v2/dboards/src/app/partials/graphite/editor.html
new file mode 100755
index 0000000..48179ec
--- /dev/null
+++ b/v2/dboards/src/app/partials/graphite/editor.html
@@ -0,0 +1,105 @@
+
+
+
diff --git a/v2/dboards/src/app/partials/inspector.html b/v2/dboards/src/app/partials/inspector.html
new file mode 100644
index 0000000..e89a575
--- /dev/null
+++ b/v2/dboards/src/app/partials/inspector.html
@@ -0,0 +1,68 @@
+
+
Inspector
+
+
+
+
+
+
+
+
Request details
+
+
+
Url
+
{{inspector.error.config.url}}
+
+
+
Method
+
{{inspector.error.config.method}}
+
+
+
+ {{key}}
+
+
+ {{value}}
+
+
+
+
+
Request parameters
+
+
+
+ {{param.key}}
+
+
+ {{param.value}}
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+ {{message}}
+
+
+
+
+ {{stack_trace}}
+
+
+
+
+
+
\ No newline at end of file
diff --git a/v2/dboards/src/app/partials/kairosdb/editor.html b/v2/dboards/src/app/partials/kairosdb/editor.html
new file mode 100644
index 0000000..fdaf391
--- /dev/null
+++ b/v2/dboards/src/app/partials/kairosdb/editor.html
@@ -0,0 +1,375 @@
+
diff --git a/v2/dboards/src/app/partials/load.html b/v2/dboards/src/app/partials/load.html
new file mode 100644
index 0000000..27d012b
--- /dev/null
+++ b/v2/dboards/src/app/partials/load.html
@@ -0,0 +1,4 @@
+
+ type: {{type}}
+ id: {{id}}
+
\ No newline at end of file
diff --git a/v2/dboards/src/app/partials/loadmetrics.html b/v2/dboards/src/app/partials/loadmetrics.html
new file mode 100644
index 0000000..2665386
--- /dev/null
+++ b/v2/dboards/src/app/partials/loadmetrics.html
@@ -0,0 +1,36 @@
+
diff --git a/v2/dboards/src/app/partials/modal.html b/v2/dboards/src/app/partials/modal.html
new file mode 100644
index 0000000..38d86cd
--- /dev/null
+++ b/v2/dboards/src/app/partials/modal.html
@@ -0,0 +1,12 @@
+
+
+
{{modal.title}}
+
+
+
+
+
+
+
\ No newline at end of file
diff --git a/v2/dboards/src/app/partials/opentsdb/editor.html b/v2/dboards/src/app/partials/opentsdb/editor.html
new file mode 100644
index 0000000..673c5a6
--- /dev/null
+++ b/v2/dboards/src/app/partials/opentsdb/editor.html
@@ -0,0 +1,176 @@
+
\ No newline at end of file
diff --git a/v2/dboards/src/app/partials/paneleditor.html b/v2/dboards/src/app/partials/paneleditor.html
new file mode 100644
index 0000000..62692c5
--- /dev/null
+++ b/v2/dboards/src/app/partials/paneleditor.html
@@ -0,0 +1,23 @@
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
\ No newline at end of file
diff --git a/v2/dboards/src/app/partials/panelgeneral.html b/v2/dboards/src/app/partials/panelgeneral.html
new file mode 100644
index 0000000..e239866
--- /dev/null
+++ b/v2/dboards/src/app/partials/panelgeneral.html
@@ -0,0 +1,11 @@
+
+
+
General options
+
+
+
+
+
+
+
+
\ No newline at end of file
diff --git a/v2/dboards/src/app/partials/playlist.html b/v2/dboards/src/app/partials/playlist.html
new file mode 100644
index 0000000..4861d0e
--- /dev/null
+++ b/v2/dboards/src/app/partials/playlist.html
@@ -0,0 +1,54 @@
+
+
+
Start dashboard playlist
+
+
+
+
+
+
+
+
Dashboard
+
Include
+
Remove as favorite
+
+
+
+ {{dashboard.title}}
+
+
+
+
+
+
+
+
+
+
+ No dashboards marked as favorites
+
+
+
+
+
+
+
+ Dashboards available in the playlist are only the once marked as favorites (stored in local browser storage).
+ To mark a dashboard as favorite, use save icon in the menu and in the dropdown select Mark as favorite
+
+
+
+
+
+
+
+
+
+
+
+
\ No newline at end of file
diff --git a/v2/dboards/src/app/partials/roweditor.html b/v2/dboards/src/app/partials/roweditor.html
new file mode 100644
index 0000000..8a0032a
--- /dev/null
+++ b/v2/dboards/src/app/partials/roweditor.html
@@ -0,0 +1,66 @@
+
+
Row settings
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
Panels
+
+
+
Title
+
Type
+
Span ({{rowSpan(row)}}/12)
+
Delete
+
Move
+
+
Hide
+
+
+
{{panel.title}}
+
{{panel.type}}
+
+
+
+
+
+
+
+
+
+
+
Select Panel Type
+
+
+
+
+
+
+
+
\ No newline at end of file
diff --git a/v2/dboards/src/app/partials/search.html b/v2/dboards/src/app/partials/search.html
new file mode 100644
index 0000000..0eb1d1d
--- /dev/null
+++ b/v2/dboards/src/app/partials/search.html
@@ -0,0 +1,122 @@
+
+
+
+
+
+
+
diff --git a/v2/dboards/src/app/partials/unsaved-changes.html b/v2/dboards/src/app/partials/unsaved-changes.html
new file mode 100644
index 0000000..87220e4
--- /dev/null
+++ b/v2/dboards/src/app/partials/unsaved-changes.html
@@ -0,0 +1,16 @@
+
+
+
+
+
Unsaved changes
+
+
+
+
+
+
+
+
+
+
\ No newline at end of file
diff --git a/v2/dboards/src/app/services/alertSrv.js b/v2/dboards/src/app/services/alertSrv.js
new file mode 100644
index 0000000..35395bb
--- /dev/null
+++ b/v2/dboards/src/app/services/alertSrv.js
@@ -0,0 +1,49 @@
+define([
+ 'angular',
+ 'underscore'
+],
+function (angular, _) {
+ 'use strict';
+
+ var module = angular.module('kibana.services');
+
+ module.service('alertSrv', function($timeout) {
+ var self = this;
+
+ // List of all alert objects
+ this.list = [];
+
+ this.set = function(title,text,severity,timeout) {
+ var
+ _a = {
+ title: title || '',
+ text: text || '',
+ severity: severity || 'info',
+ },
+ _ca = angular.toJson(_a),
+ _clist = _.map(self.list,function(alert) {return angular.toJson(alert);});
+
+ // If we already have this alert, remove it and add a new one
+ // Why do this instead of skipping the add because it resets the timer
+ if(_.contains(_clist,_ca)) {
+ _.remove(self.list,_.indexOf(_clist,_ca));
+ }
+
+ self.list.push(_a);
+ if (timeout > 0) {
+ $timeout(function() {
+ self.list = _.without(self.list,_a);
+ }, timeout);
+ }
+ return(_a);
+ };
+
+ this.clear = function(alert) {
+ self.list = _.without(self.list,alert);
+ };
+
+ this.clearAll = function() {
+ self.list = [];
+ };
+ });
+});
\ No newline at end of file
diff --git a/v2/dboards/src/app/services/all.js b/v2/dboards/src/app/services/all.js
new file mode 100644
index 0000000..53a4f52
--- /dev/null
+++ b/v2/dboards/src/app/services/all.js
@@ -0,0 +1,13 @@
+define([
+ './alertSrv',
+ './dashboard',
+ './datasourceSrv',
+ './filterSrv',
+ './timer',
+ './panelMove',
+ './keyboardManager',
+ './annotationsSrv',
+ './playlistSrv',
+ './unsavedChangesSrv',
+],
+function () {});
\ No newline at end of file
diff --git a/v2/dboards/src/app/services/annotationsSrv.js b/v2/dboards/src/app/services/annotationsSrv.js
new file mode 100644
index 0000000..459b5ff
--- /dev/null
+++ b/v2/dboards/src/app/services/annotationsSrv.js
@@ -0,0 +1,157 @@
+define([
+ 'angular',
+ 'underscore',
+ 'moment'
+], function (angular, _, moment) {
+ 'use strict';
+
+ var module = angular.module('kibana.services');
+
+ module.service('annotationsSrv', function(dashboard, datasourceSrv, $q, alertSrv, $rootScope) {
+ var promiseCached;
+ var annotationPanel;
+ var list = [];
+
+ this.init = function() {
+ $rootScope.$on('refresh', this.clearCache);
+ $rootScope.$on('dashboard-loaded', this.dashboardLoaded);
+
+ this.dashboardLoaded();
+ };
+
+ this.dashboardLoaded = function () {
+ annotationPanel = _.findWhere(dashboard.current.pulldowns, { type: 'annotations' });
+ };
+
+ this.clearCache = function() {
+ promiseCached = null;
+ list = [];
+ };
+
+ this.getAnnotations = function(filterSrv, rangeUnparsed) {
+ if (!annotationPanel.enable) {
+ return $q.when(null);
+ }
+
+ if (promiseCached) {
+ return promiseCached;
+ }
+
+ var graphiteMetrics = this.getGraphiteMetrics(filterSrv, rangeUnparsed);
+ var graphiteEvents = this.getGraphiteEvents(rangeUnparsed);
+
+ promiseCached = $q.all(graphiteMetrics.concat(graphiteEvents))
+ .then(function() {
+ return list;
+ });
+
+ return promiseCached;
+ };
+
+ this.getGraphiteEvents = function(rangeUnparsed) {
+ var annotations = this.getAnnotationsByType('graphite events');
+ if (annotations.length === 0) {
+ return [];
+ }
+
+ var promises = _.map(annotations, function(annotation) {
+
+ return datasourceSrv.default.events({ range: rangeUnparsed, tags: annotation.tags })
+ .then(function(results) {
+ _.each(results.data, function (event) {
+ addAnnotation({
+ annotation: annotation,
+ time: event.when * 1000,
+ description: event.what,
+ tags: event.tags,
+ data: event.data
+ });
+ });
+ })
+ .then(null, errorHandler);
+ });
+
+ return promises;
+ };
+
+ this.getAnnotationsByType = function(type) {
+ return _.where(annotationPanel.annotations, {
+ type: type,
+ enable: true
+ });
+ };
+
+ this.getGraphiteMetrics = function(filterSrv, rangeUnparsed) {
+ var annotations = this.getAnnotationsByType('graphite metric');
+ if (annotations.length === 0) {
+ return [];
+ }
+
+ var promises = _.map(annotations, function(annotation) {
+ var graphiteQuery = {
+ range: rangeUnparsed,
+ targets: [{ target: annotation.target }],
+ format: 'json',
+ maxDataPoints: 100
+ };
+
+ var receiveFunc = _.partial(receiveGraphiteMetrics, annotation);
+
+ return datasourceSrv.default.query(filterSrv, graphiteQuery)
+ .then(receiveFunc)
+ .then(null, errorHandler);
+ });
+
+ return promises;
+ };
+
+ function errorHandler(err) {
+ console.log('Annotation error: ', err);
+ alertSrv.set('Annotations','Could not fetch annotations','error');
+ }
+
+ function receiveGraphiteMetrics(annotation, results) {
+ for (var i = 0; i < results.data.length; i++) {
+ var target = results.data[i];
+
+ for (var y = 0; y < target.datapoints.length; y++) {
+ var datapoint = target.datapoints[y];
+
+ if (datapoint[0]) {
+ addAnnotation({
+ annotation: annotation,
+ time: datapoint[1] * 1000,
+ description: target.target
+ });
+ }
+ }
+ }
+ }
+
+ function addAnnotation(options) {
+ var tooltip = "" + options.description + " ";
+ if (options.tags) {
+ tooltip += (options.tags || '') + ' ';
+ }
+ tooltip += '' + moment(options.time).format('YYYY-MM-DD HH:mm:ss') + ' ';
+ if (options.data) {
+ tooltip += options.data.replace(/\n/g, ' ');
+ }
+ tooltip += "";
+
+ list.push({
+ annotation: options.annotation,
+ min: options.time,
+ max: options.time,
+ eventType: options.annotation.name,
+ title: null,
+ description: tooltip,
+ score: 1
+ });
+ }
+
+ // Now init
+ this.init();
+ });
+
+});
diff --git a/v2/dboards/src/app/services/dashboard.js b/v2/dboards/src/app/services/dashboard.js
new file mode 100644
index 0000000..a12a8ad
--- /dev/null
+++ b/v2/dboards/src/app/services/dashboard.js
@@ -0,0 +1,472 @@
+define([
+ 'angular',
+ 'jquery',
+ 'kbn',
+ 'underscore',
+ 'config',
+ 'moment',
+ 'modernizr',
+ 'filesaver'
+],
+function (angular, $, kbn, _, config, moment, Modernizr) {
+ 'use strict';
+
+ var module = angular.module('kibana.services');
+
+ module.service('dashboard', function(
+ $routeParams, $http, $rootScope, $injector, $location, $timeout,
+ ejsResource, timer, alertSrv, $q
+ ) {
+ // A hash of defaults to use when loading a dashboard
+
+ var _dash = {
+ title: "",
+ tags: [],
+ style: "dark",
+ timezone: 'browser',
+ editable: true,
+ failover: false,
+ panel_hints: true,
+ rows: [],
+ pulldowns: [{ type: 'templating' }, { type: 'annotations' }],
+ nav: [{ type: 'timepicker' }],
+ services: {},
+ loader: {
+ save_gist: false,
+ save_elasticsearch: true,
+ save_local: true,
+ save_default: true,
+ save_temp: true,
+ save_temp_ttl_enable: true,
+ save_temp_ttl: '30d',
+ load_gist: false,
+ load_elasticsearch: true,
+ load_elasticsearch_size: 20,
+ load_local: false,
+ hide: false
+ },
+ refresh: false
+ };
+
+ // An elasticJS client to use
+ var ejs = ejsResource(config.elasticsearch, config.elasticsearchBasicAuth);
+ var gist_pattern = /(^\d{5,}$)|(^[a-z0-9]{10,}$)|(gist.github.com(\/*.*)\/[a-z0-9]{5,}\/*$)/;
+
+ // Store a reference to this
+ var self = this;
+
+ this.current = _.clone(_dash);
+ this.last = {};
+ this.availablePanels = [];
+
+ $rootScope.$on('$routeChangeSuccess',function() {
+ // Clear the current dashboard to prevent reloading
+ self.current = {};
+ self.indices = [];
+ route();
+ });
+
+ var route = function() {
+ // Is there a dashboard type and id in the URL?
+ if(!(_.isUndefined($routeParams.kbnType)) && !(_.isUndefined($routeParams.kbnId))) {
+ var _type = $routeParams.kbnType;
+ var _id = $routeParams.kbnId;
+
+ switch(_type) {
+ case ('elasticsearch'):
+ self.elasticsearch_load('dashboard',_id);
+ break;
+ case ('temp'):
+ self.elasticsearch_load('temp',_id);
+ break;
+ case ('file'):
+ self.file_load(_id);
+ break;
+ case('script'):
+ self.script_load(_id);
+ break;
+ case('local'):
+ self.local_load();
+ break;
+ default:
+ $location.path(config.default_route);
+ }
+ // No dashboard in the URL
+ } else {
+ // Check if browser supports localstorage, and if there's an old dashboard. If there is,
+ // inform the user that they should save their dashboard to Elasticsearch and then set that
+ // as their default
+ if (Modernizr.localstorage) {
+ if(!(_.isUndefined(window.localStorage['dashboard'])) && window.localStorage['dashboard'] !== '') {
+ $location.path(config.default_route);
+ alertSrv.set('Saving to browser storage has been replaced',' with saving to Elasticsearch.'+
+ ' Click here to load your old dashboard anyway.');
+ } else if(!(_.isUndefined(window.localStorage.grafanaDashboardDefault))) {
+ $location.path(window.localStorage.grafanaDashboardDefault);
+ } else {
+ $location.path(config.default_route);
+ }
+ // No? Ok, grab the default route, its all we have now
+ } else {
+ $location.path(config.default_route);
+ }
+ }
+ };
+
+ this.refresh = function() {
+ $rootScope.$broadcast('refresh');
+ };
+
+ var dash_defaults = function(dashboard) {
+
+ _.defaults(dashboard, _dash);
+ _.defaults(dashboard.loader,_dash.loader);
+
+ var filtering = _.findWhere(dashboard.pulldowns, {type: 'filtering'});
+ if (!filtering) {
+ dashboard.pulldowns.push({
+ type: 'filtering',
+ enable: false
+ });
+ }
+
+ var annotations = _.findWhere(dashboard.pulldowns, {type: 'annotations'});
+ if (!annotations) {
+ dashboard.pulldowns.push({
+ type: 'annotations',
+ enable: false
+ });
+ }
+
+ _.each(dashboard.rows, function(row) {
+ _.each(row.panels, function(panel) {
+ if (panel.type === 'graphite') {
+ panel.type = 'graph';
+ }
+ });
+ });
+
+ return dashboard;
+ };
+
+ this.dash_load = function(dashboard) {
+ // Cancel all timers
+ timer.cancel_all();
+
+ // reset fullscreen flag
+ $rootScope.fullscreen = false;
+
+ // Make sure the dashboard being loaded has everything required
+ dashboard = dash_defaults(dashboard);
+
+ window.document.title = 'Grafana - ' + dashboard.title;
+
+ // Set the current dashboard
+ self.current = angular.copy(dashboard);
+ if(dashboard.refresh) {
+ self.set_interval(dashboard.refresh);
+ }
+
+ self.availablePanels = config.panels;
+
+ $rootScope.$emit('dashboard-loaded', self.current);
+
+ return true;
+ };
+
+ this.gist_id = function(string) {
+ if(self.is_gist(string)) {
+ return string.match(gist_pattern)[0].replace(/.*\//, '');
+ }
+ };
+
+ this.is_gist = function(string) {
+ if(!_.isUndefined(string) && string !== '' && !_.isNull(string.match(gist_pattern))) {
+ return string.match(gist_pattern).length > 0 ? true : false;
+ } else {
+ return false;
+ }
+ };
+
+ this.to_file = function() {
+ var blob = new Blob([angular.toJson(self.current,true)], {type: "application/json;charset=utf-8"});
+ // from filesaver.js
+ window.saveAs(blob, self.current.title+"-"+new Date().getTime());
+ return true;
+ };
+
+ this.set_default = function(route) {
+ if (Modernizr.localstorage) {
+ // Purge any old dashboards
+ if(!_.isUndefined(window.localStorage['dashboard'])) {
+ delete window.localStorage['dashboard'];
+ }
+ window.localStorage.grafanaDashboardDefault = route;
+ return true;
+ } else {
+ return false;
+ }
+ };
+
+ this.purge_default = function() {
+ if (Modernizr.localstorage) {
+ // Purge any old dashboards
+ if(!_.isUndefined(window.localStorage['dashboard'])) {
+
+ delete window.localStorage['dashboard'];
+ }
+ delete window.localStorage.grafanaDashboardDefault;
+ return true;
+ } else {
+ return false;
+ }
+ };
+
+ // TOFIX: Pretty sure this breaks when you're on a saved dashboard already
+ this.share_link = function(title,type,id) {
+ return {
+ location : window.location.href.replace(window.location.hash,""),
+ type : type,
+ id : id,
+ link : window.location.href.replace(window.location.hash,"")+"#dashboard/"+type+"/"+id,
+ title : title
+ };
+ };
+
+ var renderTemplate = function(json,params) {
+ var _r;
+ _.templateSettings = {interpolate : /\{\{(.+?)\}\}/g};
+ var template = _.template(json);
+ var rendered = template({ARGS:params});
+ try {
+ _r = angular.fromJson(rendered);
+ } catch(e) {
+ _r = false;
+ }
+ return _r;
+ };
+
+ this.local_load = function() {
+ var dashboard = JSON.parse(window.localStorage['dashboard']);
+ dashboard.rows.unshift({
+ height: "30",
+ title: "Deprecation Notice",
+ panels: [
+ {
+ title: 'WARNING: Legacy dashboard',
+ type: 'text',
+ span: 12,
+ mode: 'html',
+ content: 'This dashboard has been loaded from the browsers local cache. If you use '+
+ 'another brower or computer you will not be able to access it! '+
+ '\n\n
Good news!
Kibana'+
+ ' now stores saved dashboards in Elasticsearch. Click the '+
+ 'button in the top left to save this dashboard. Then select "Set as Home" from'+
+ ' the "advanced" sub menu to automatically use the stored dashboard as your Kibana '+
+ 'landing page afterwards'+
+ '
+ * $log.log('Some Error');
+ * var first = $log.error.logs.unshift();
+ *
+ */
+ $log.error.logs = [];
+ };
+
+ /**
+ * @ngdoc method
+ * @name ngMock.$log#assertEmpty
+ * @methodOf ngMock.$log
+ *
+ * @description
+ * Assert that the all of the logging methods have no logged messages. If messages present, an exception is thrown.
+ */
+ $log.assertEmpty = function() {
+ var errors = [];
+ angular.forEach(['error', 'warn', 'info', 'log'], function(logLevel) {
+ angular.forEach($log[logLevel].logs, function(log) {
+ angular.forEach(log, function (logItem) {
+ errors.push('MOCK $log (' + logLevel + '): ' + String(logItem) + '\n' + (logItem.stack || ''));
+ });
+ });
+ });
+ if (errors.length) {
+ errors.unshift("Expected $log to be empty! Either a message was logged unexpectedly, or an expected " +
+ "log message was not checked and removed:");
+ errors.push('');
+ throw new Error(errors.join('\n---------\n'));
+ }
+ };
+
+ $log.reset();
+ return $log;
+ };
+};
+
+
+(function() {
+ var R_ISO8061_STR = /^(\d{4})-?(\d\d)-?(\d\d)(?:T(\d\d)(?:\:?(\d\d)(?:\:?(\d\d)(?:\.(\d{3}))?)?)?(Z|([+-])(\d\d):?(\d\d)))?$/;
+
+ function jsonStringToDate(string){
+ var match;
+ if (match = string.match(R_ISO8061_STR)) {
+ var date = new Date(0),
+ tzHour = 0,
+ tzMin = 0;
+ if (match[9]) {
+ tzHour = int(match[9] + match[10]);
+ tzMin = int(match[9] + match[11]);
+ }
+ date.setUTCFullYear(int(match[1]), int(match[2]) - 1, int(match[3]));
+ date.setUTCHours(int(match[4]||0) - tzHour, int(match[5]||0) - tzMin, int(match[6]||0), int(match[7]||0));
+ return date;
+ }
+ return string;
+ }
+
+ function int(str) {
+ return parseInt(str, 10);
+ }
+
+ function padNumber(num, digits, trim) {
+ var neg = '';
+ if (num < 0) {
+ neg = '-';
+ num = -num;
+ }
+ num = '' + num;
+ while(num.length < digits) num = '0' + num;
+ if (trim)
+ num = num.substr(num.length - digits);
+ return neg + num;
+ }
+
+
+ /**
+ * @ngdoc object
+ * @name angular.mock.TzDate
+ * @description
+ *
+ * *NOTE*: this is not an injectable instance, just a globally available mock class of `Date`.
+ *
+ * Mock of the Date type which has its timezone specified via constructor arg.
+ *
+ * The main purpose is to create Date-like instances with timezone fixed to the specified timezone
+ * offset, so that we can test code that depends on local timezone settings without dependency on
+ * the time zone settings of the machine where the code is running.
+ *
+ * @param {number} offset Offset of the *desired* timezone in hours (fractions will be honored)
+ * @param {(number|string)} timestamp Timestamp representing the desired time in *UTC*
+ *
+ * @example
+ * !!!! WARNING !!!!!
+ * This is not a complete Date object so only methods that were implemented can be called safely.
+ * To make matters worse, TzDate instances inherit stuff from Date via a prototype.
+ *
+ * We do our best to intercept calls to "unimplemented" methods, but since the list of methods is
+ * incomplete we might be missing some non-standard methods. This can result in errors like:
+ * "Date.prototype.foo called on incompatible Object".
+ *
+ *
+ beforeEach(module(function($provide) {
+ $provide.value('$window', window = angular.mock.createMockWindow());
+ }));
+
+ it('should do something', inject(function($window) {
+ var val = null;
+ $window.setTimeout(function() { val = 123; }, 10);
+ expect(val).toEqual(null);
+ window.setTimeout.expect(10).process();
+ expect(val).toEqual(123);
+ });
+ *
+ *
+ */
+angular.mock.createMockWindow = function() {
+ var mockWindow = {};
+ var setTimeoutQueue = [];
+
+ mockWindow.document = window.document;
+ mockWindow.getComputedStyle = angular.bind(window, window.getComputedStyle);
+ mockWindow.scrollTo = angular.bind(window, window.scrollTo);
+ mockWindow.navigator = window.navigator;
+ mockWindow.setTimeout = function(fn, delay) {
+ setTimeoutQueue.push({fn: fn, delay: delay});
+ };
+ mockWindow.setTimeout.queue = setTimeoutQueue;
+ mockWindow.setTimeout.expect = function(delay) {
+ if (setTimeoutQueue.length > 0) {
+ return {
+ process: function() {
+ var tick = setTimeoutQueue.shift();
+ expect(tick.delay).toEqual(delay);
+ tick.fn();
+ }
+ };
+ } else {
+ expect('SetTimoutQueue empty. Expecting delay of ').toEqual(delay);
+ }
+ };
+
+ return mockWindow;
+};
+
+/**
+ * @ngdoc function
+ * @name angular.mock.dump
+ * @description
+ *
+ * *NOTE*: this is not an injectable instance, just a globally available function.
+ *
+ * Method for serializing common angular objects (scope, elements, etc..) into strings, useful for debugging.
+ *
+ * This method is also available on window, where it can be used to display objects on debug console.
+ *
+ * @param {*} object - any object to turn into string.
+ * @return {string} a serialized string of the argument
+ */
+angular.mock.dump = function(object) {
+ return serialize(object);
+
+ function serialize(object) {
+ var out;
+
+ if (angular.isElement(object)) {
+ object = angular.element(object);
+ out = angular.element('');
+ angular.forEach(object, function(element) {
+ out.append(angular.element(element).clone());
+ });
+ out = out.html();
+ } else if (angular.isArray(object)) {
+ out = [];
+ angular.forEach(object, function(o) {
+ out.push(serialize(o));
+ });
+ out = '[ ' + out.join(', ') + ' ]';
+ } else if (angular.isObject(object)) {
+ if (angular.isFunction(object.$eval) && angular.isFunction(object.$apply)) {
+ out = serializeScope(object);
+ } else if (object instanceof Error) {
+ out = object.stack || ('' + object.name + ': ' + object.message);
+ } else {
+ out = angular.toJson(object, true);
+ }
+ } else {
+ out = String(object);
+ }
+
+ return out;
+ }
+
+ function serializeScope(scope, offset) {
+ offset = offset || ' ';
+ var log = [offset + 'Scope(' + scope.$id + '): {'];
+ for ( var key in scope ) {
+ if (scope.hasOwnProperty(key) && !key.match(/^(\$|this)/)) {
+ log.push(' ' + key + ': ' + angular.toJson(scope[key]));
+ }
+ }
+ var child = scope.$$childHead;
+ while(child) {
+ log.push(serializeScope(child, offset + ' '));
+ child = child.$$nextSibling;
+ }
+ log.push('}');
+ return log.join('\n' + offset);
+ }
+};
+
+/**
+ * @ngdoc object
+ * @name ngMock.$httpBackend
+ * @description
+ * Fake HTTP backend implementation suitable for unit testing applications that use the
+ * {@link ng.$http $http service}.
+ *
+ * *Note*: For fake HTTP backend implementation suitable for end-to-end testing or backend-less
+ * development please see {@link ngMockE2E.$httpBackend e2e $httpBackend mock}.
+ *
+ * During unit testing, we want our unit tests to run quickly and have no external dependencies so
+ * we don’t want to send {@link https://developer.mozilla.org/en/xmlhttprequest XHR} or
+ * {@link http://en.wikipedia.org/wiki/JSONP JSONP} requests to a real server. All we really need is
+ * to verify whether a certain request has been sent or not, or alternatively just let the
+ * application make requests, respond with pre-trained responses and assert that the end result is
+ * what we expect it to be.
+ *
+ * This mock implementation can be used to respond with static or dynamic responses via the
+ * `expect` and `when` apis and their shortcuts (`expectGET`, `whenPOST`, etc).
+ *
+ * When an Angular application needs some data from a server, it calls the $http service, which
+ * sends the request to a real server using $httpBackend service. With dependency injection, it is
+ * easy to inject $httpBackend mock (which has the same API as $httpBackend) and use it to verify
+ * the requests and respond with some testing data without sending a request to real server.
+ *
+ * There are two ways to specify what test data should be returned as http responses by the mock
+ * backend when the code under test makes http requests:
+ *
+ * - `$httpBackend.expect` - specifies a request expectation
+ * - `$httpBackend.when` - specifies a backend definition
+ *
+ *
+ * # Request Expectations vs Backend Definitions
+ *
+ * Request expectations provide a way to make assertions about requests made by the application and
+ * to define responses for those requests. The test will fail if the expected requests are not made
+ * or they are made in the wrong order.
+ *
+ * Backend definitions allow you to define a fake backend for your application which doesn't assert
+ * if a particular request was made or not, it just returns a trained response if a request is made.
+ * The test will pass whether or not the request gets made during testing.
+ *
+ *
+ *
+ *
Request expectations
Backend definitions
+ *
+ *
Syntax
+ *
.expect(...).respond(...)
+ *
.when(...).respond(...)
+ *
+ *
+ *
Typical usage
+ *
strict unit tests
+ *
loose (black-box) unit testing
+ *
+ *
+ *
Fulfills multiple requests
+ *
NO
+ *
YES
+ *
+ *
+ *
Order of requests matters
+ *
YES
+ *
NO
+ *
+ *
+ *
Request required
+ *
YES
+ *
NO
+ *
+ *
+ *
Response required
+ *
optional (see below)
+ *
YES
+ *
+ *
+ *
+ * In cases where both backend definitions and request expectations are specified during unit
+ * testing, the request expectations are evaluated first.
+ *
+ * If a request expectation has no response specified, the algorithm will search your backend
+ * definitions for an appropriate response.
+ *
+ * If a request didn't match any expectation or if the expectation doesn't have the response
+ * defined, the backend definitions are evaluated in sequential order to see if any of them match
+ * the request. The response from the first matched definition is returned.
+ *
+ *
+ * # Flushing HTTP requests
+ *
+ * The $httpBackend used in production, always responds to requests with responses asynchronously.
+ * If we preserved this behavior in unit testing, we'd have to create async unit tests, which are
+ * hard to write, follow and maintain. At the same time the testing mock, can't respond
+ * synchronously because that would change the execution of the code under test. For this reason the
+ * mock $httpBackend has a `flush()` method, which allows the test to explicitly flush pending
+ * requests and thus preserving the async api of the backend, while allowing the test to execute
+ * synchronously.
+ *
+ *
+ * # Unit testing with mock $httpBackend
+ *
+ *
+ // controller
+ function MyController($scope, $http) {
+ $http.get('/auth.py').success(function(data) {
+ $scope.user = data;
+ });
+
+ this.saveMessage = function(message) {
+ $scope.status = 'Saving...';
+ $http.post('/add-msg.py', message).success(function(response) {
+ $scope.status = '';
+ }).error(function() {
+ $scope.status = 'ERROR!';
+ });
+ };
+ }
+
+ // testing controller
+ var $httpBackend;
+
+ beforeEach(inject(function($injector) {
+ $httpBackend = $injector.get('$httpBackend');
+
+ // backend definition common for all tests
+ $httpBackend.when('GET', '/auth.py').respond({userId: 'userX'}, {'A-Token': 'xxx'});
+ }));
+
+
+ afterEach(function() {
+ $httpBackend.verifyNoOutstandingExpectation();
+ $httpBackend.verifyNoOutstandingRequest();
+ });
+
+
+ it('should fetch authentication token', function() {
+ $httpBackend.expectGET('/auth.py');
+ var controller = scope.$new(MyController);
+ $httpBackend.flush();
+ });
+
+
+ it('should send msg to server', function() {
+ // now you don’t care about the authentication, but
+ // the controller will still send the request and
+ // $httpBackend will respond without you having to
+ // specify the expectation and response for this request
+ $httpBackend.expectPOST('/add-msg.py', 'message content').respond(201, '');
+
+ var controller = scope.$new(MyController);
+ $httpBackend.flush();
+ controller.saveMessage('message content');
+ expect(controller.status).toBe('Saving...');
+ $httpBackend.flush();
+ expect(controller.status).toBe('');
+ });
+
+
+ it('should send auth header', function() {
+ $httpBackend.expectPOST('/add-msg.py', undefined, function(headers) {
+ // check if the header was send, if it wasn't the expectation won't
+ // match the request and the test will fail
+ return headers['Authorization'] == 'xxx';
+ }).respond(201, '');
+
+ var controller = scope.$new(MyController);
+ controller.saveMessage('whatever');
+ $httpBackend.flush();
+ });
+
+ */
+angular.mock.$HttpBackendProvider = function() {
+ this.$get = ['$rootScope', createHttpBackendMock];
+};
+
+/**
+ * General factory function for $httpBackend mock.
+ * Returns instance for unit testing (when no arguments specified):
+ * - passing through is disabled
+ * - auto flushing is disabled
+ *
+ * Returns instance for e2e testing (when `$delegate` and `$browser` specified):
+ * - passing through (delegating request to real backend) is enabled
+ * - auto flushing is enabled
+ *
+ * @param {Object=} $delegate Real $httpBackend instance (allow passing through if specified)
+ * @param {Object=} $browser Auto-flushing enabled if specified
+ * @return {Object} Instance of $httpBackend mock
+ */
+function createHttpBackendMock($rootScope, $delegate, $browser) {
+ var definitions = [],
+ expectations = [],
+ responses = [],
+ responsesPush = angular.bind(responses, responses.push);
+
+ function createResponse(status, data, headers) {
+ if (angular.isFunction(status)) return status;
+
+ return function() {
+ return angular.isNumber(status)
+ ? [status, data, headers]
+ : [200, status, data];
+ };
+ }
+
+ // TODO(vojta): change params to: method, url, data, headers, callback
+ function $httpBackend(method, url, data, callback, headers, timeout) {
+ var xhr = new MockXhr(),
+ expectation = expectations[0],
+ wasExpected = false;
+
+ function prettyPrint(data) {
+ return (angular.isString(data) || angular.isFunction(data) || data instanceof RegExp)
+ ? data
+ : angular.toJson(data);
+ }
+
+ function wrapResponse(wrapped) {
+ if (!$browser && timeout && timeout.then) timeout.then(handleTimeout);
+
+ return handleResponse;
+
+ function handleResponse() {
+ var response = wrapped.response(method, url, data, headers);
+ xhr.$$respHeaders = response[2];
+ callback(response[0], response[1], xhr.getAllResponseHeaders());
+ }
+
+ function handleTimeout() {
+ for (var i = 0, ii = responses.length; i < ii; i++) {
+ if (responses[i] === handleResponse) {
+ responses.splice(i, 1);
+ callback(-1, undefined, '');
+ break;
+ }
+ }
+ }
+ }
+
+ if (expectation && expectation.match(method, url)) {
+ if (!expectation.matchData(data))
+ throw Error('Expected ' + expectation + ' with different data\n' +
+ 'EXPECTED: ' + prettyPrint(expectation.data) + '\nGOT: ' + data);
+
+ if (!expectation.matchHeaders(headers))
+ throw Error('Expected ' + expectation + ' with different headers\n' +
+ 'EXPECTED: ' + prettyPrint(expectation.headers) + '\nGOT: ' +
+ prettyPrint(headers));
+
+ expectations.shift();
+
+ if (expectation.response) {
+ responses.push(wrapResponse(expectation));
+ return;
+ }
+ wasExpected = true;
+ }
+
+ var i = -1, definition;
+ while ((definition = definitions[++i])) {
+ if (definition.match(method, url, data, headers || {})) {
+ if (definition.response) {
+ // if $browser specified, we do auto flush all requests
+ ($browser ? $browser.defer : responsesPush)(wrapResponse(definition));
+ } else if (definition.passThrough) {
+ $delegate(method, url, data, callback, headers, timeout);
+ } else throw Error('No response defined !');
+ return;
+ }
+ }
+ throw wasExpected ?
+ Error('No response defined !') :
+ Error('Unexpected request: ' + method + ' ' + url + '\n' +
+ (expectation ? 'Expected ' + expectation : 'No more request expected'));
+ }
+
+ /**
+ * @ngdoc method
+ * @name ngMock.$httpBackend#when
+ * @methodOf ngMock.$httpBackend
+ * @description
+ * Creates a new backend definition.
+ *
+ * @param {string} method HTTP method.
+ * @param {string|RegExp} url HTTP url.
+ * @param {(string|RegExp)=} data HTTP request body.
+ * @param {(Object|function(Object))=} headers HTTP headers or function that receives http header
+ * object and returns true if the headers match the current definition.
+ * @returns {requestHandler} Returns an object with `respond` method that control how a matched
+ * request is handled.
+ *
+ * - respond – `{function([status,] data[, headers])|function(function(method, url, data, headers)}`
+ * – The respond method takes a set of static data to be returned or a function that can return
+ * an array containing response status (number), response data (string) and response headers
+ * (Object).
+ */
+ $httpBackend.when = function(method, url, data, headers) {
+ var definition = new MockHttpExpectation(method, url, data, headers),
+ chain = {
+ respond: function(status, data, headers) {
+ definition.response = createResponse(status, data, headers);
+ }
+ };
+
+ if ($browser) {
+ chain.passThrough = function() {
+ definition.passThrough = true;
+ };
+ }
+
+ definitions.push(definition);
+ return chain;
+ };
+
+ /**
+ * @ngdoc method
+ * @name ngMock.$httpBackend#whenGET
+ * @methodOf ngMock.$httpBackend
+ * @description
+ * Creates a new backend definition for GET requests. For more info see `when()`.
+ *
+ * @param {string|RegExp} url HTTP url.
+ * @param {(Object|function(Object))=} headers HTTP headers.
+ * @returns {requestHandler} Returns an object with `respond` method that control how a matched
+ * request is handled.
+ */
+
+ /**
+ * @ngdoc method
+ * @name ngMock.$httpBackend#whenHEAD
+ * @methodOf ngMock.$httpBackend
+ * @description
+ * Creates a new backend definition for HEAD requests. For more info see `when()`.
+ *
+ * @param {string|RegExp} url HTTP url.
+ * @param {(Object|function(Object))=} headers HTTP headers.
+ * @returns {requestHandler} Returns an object with `respond` method that control how a matched
+ * request is handled.
+ */
+
+ /**
+ * @ngdoc method
+ * @name ngMock.$httpBackend#whenDELETE
+ * @methodOf ngMock.$httpBackend
+ * @description
+ * Creates a new backend definition for DELETE requests. For more info see `when()`.
+ *
+ * @param {string|RegExp} url HTTP url.
+ * @param {(Object|function(Object))=} headers HTTP headers.
+ * @returns {requestHandler} Returns an object with `respond` method that control how a matched
+ * request is handled.
+ */
+
+ /**
+ * @ngdoc method
+ * @name ngMock.$httpBackend#whenPOST
+ * @methodOf ngMock.$httpBackend
+ * @description
+ * Creates a new backend definition for POST requests. For more info see `when()`.
+ *
+ * @param {string|RegExp} url HTTP url.
+ * @param {(string|RegExp)=} data HTTP request body.
+ * @param {(Object|function(Object))=} headers HTTP headers.
+ * @returns {requestHandler} Returns an object with `respond` method that control how a matched
+ * request is handled.
+ */
+
+ /**
+ * @ngdoc method
+ * @name ngMock.$httpBackend#whenPUT
+ * @methodOf ngMock.$httpBackend
+ * @description
+ * Creates a new backend definition for PUT requests. For more info see `when()`.
+ *
+ * @param {string|RegExp} url HTTP url.
+ * @param {(string|RegExp)=} data HTTP request body.
+ * @param {(Object|function(Object))=} headers HTTP headers.
+ * @returns {requestHandler} Returns an object with `respond` method that control how a matched
+ * request is handled.
+ */
+
+ /**
+ * @ngdoc method
+ * @name ngMock.$httpBackend#whenJSONP
+ * @methodOf ngMock.$httpBackend
+ * @description
+ * Creates a new backend definition for JSONP requests. For more info see `when()`.
+ *
+ * @param {string|RegExp} url HTTP url.
+ * @returns {requestHandler} Returns an object with `respond` method that control how a matched
+ * request is handled.
+ */
+ createShortMethods('when');
+
+
+ /**
+ * @ngdoc method
+ * @name ngMock.$httpBackend#expect
+ * @methodOf ngMock.$httpBackend
+ * @description
+ * Creates a new request expectation.
+ *
+ * @param {string} method HTTP method.
+ * @param {string|RegExp} url HTTP url.
+ * @param {(string|RegExp)=} data HTTP request body.
+ * @param {(Object|function(Object))=} headers HTTP headers or function that receives http header
+ * object and returns true if the headers match the current expectation.
+ * @returns {requestHandler} Returns an object with `respond` method that control how a matched
+ * request is handled.
+ *
+ * - respond – `{function([status,] data[, headers])|function(function(method, url, data, headers)}`
+ * – The respond method takes a set of static data to be returned or a function that can return
+ * an array containing response status (number), response data (string) and response headers
+ * (Object).
+ */
+ $httpBackend.expect = function(method, url, data, headers) {
+ var expectation = new MockHttpExpectation(method, url, data, headers);
+ expectations.push(expectation);
+ return {
+ respond: function(status, data, headers) {
+ expectation.response = createResponse(status, data, headers);
+ }
+ };
+ };
+
+
+ /**
+ * @ngdoc method
+ * @name ngMock.$httpBackend#expectGET
+ * @methodOf ngMock.$httpBackend
+ * @description
+ * Creates a new request expectation for GET requests. For more info see `expect()`.
+ *
+ * @param {string|RegExp} url HTTP url.
+ * @param {Object=} headers HTTP headers.
+ * @returns {requestHandler} Returns an object with `respond` method that control how a matched
+ * request is handled. See #expect for more info.
+ */
+
+ /**
+ * @ngdoc method
+ * @name ngMock.$httpBackend#expectHEAD
+ * @methodOf ngMock.$httpBackend
+ * @description
+ * Creates a new request expectation for HEAD requests. For more info see `expect()`.
+ *
+ * @param {string|RegExp} url HTTP url.
+ * @param {Object=} headers HTTP headers.
+ * @returns {requestHandler} Returns an object with `respond` method that control how a matched
+ * request is handled.
+ */
+
+ /**
+ * @ngdoc method
+ * @name ngMock.$httpBackend#expectDELETE
+ * @methodOf ngMock.$httpBackend
+ * @description
+ * Creates a new request expectation for DELETE requests. For more info see `expect()`.
+ *
+ * @param {string|RegExp} url HTTP url.
+ * @param {Object=} headers HTTP headers.
+ * @returns {requestHandler} Returns an object with `respond` method that control how a matched
+ * request is handled.
+ */
+
+ /**
+ * @ngdoc method
+ * @name ngMock.$httpBackend#expectPOST
+ * @methodOf ngMock.$httpBackend
+ * @description
+ * Creates a new request expectation for POST requests. For more info see `expect()`.
+ *
+ * @param {string|RegExp} url HTTP url.
+ * @param {(string|RegExp)=} data HTTP request body.
+ * @param {Object=} headers HTTP headers.
+ * @returns {requestHandler} Returns an object with `respond` method that control how a matched
+ * request is handled.
+ */
+
+ /**
+ * @ngdoc method
+ * @name ngMock.$httpBackend#expectPUT
+ * @methodOf ngMock.$httpBackend
+ * @description
+ * Creates a new request expectation for PUT requests. For more info see `expect()`.
+ *
+ * @param {string|RegExp} url HTTP url.
+ * @param {(string|RegExp)=} data HTTP request body.
+ * @param {Object=} headers HTTP headers.
+ * @returns {requestHandler} Returns an object with `respond` method that control how a matched
+ * request is handled.
+ */
+
+ /**
+ * @ngdoc method
+ * @name ngMock.$httpBackend#expectPATCH
+ * @methodOf ngMock.$httpBackend
+ * @description
+ * Creates a new request expectation for PATCH requests. For more info see `expect()`.
+ *
+ * @param {string|RegExp} url HTTP url.
+ * @param {(string|RegExp)=} data HTTP request body.
+ * @param {Object=} headers HTTP headers.
+ * @returns {requestHandler} Returns an object with `respond` method that control how a matched
+ * request is handled.
+ */
+
+ /**
+ * @ngdoc method
+ * @name ngMock.$httpBackend#expectJSONP
+ * @methodOf ngMock.$httpBackend
+ * @description
+ * Creates a new request expectation for JSONP requests. For more info see `expect()`.
+ *
+ * @param {string|RegExp} url HTTP url.
+ * @returns {requestHandler} Returns an object with `respond` method that control how a matched
+ * request is handled.
+ */
+ createShortMethods('expect');
+
+
+ /**
+ * @ngdoc method
+ * @name ngMock.$httpBackend#flush
+ * @methodOf ngMock.$httpBackend
+ * @description
+ * Flushes all pending requests using the trained responses.
+ *
+ * @param {number=} count Number of responses to flush (in the order they arrived). If undefined,
+ * all pending requests will be flushed. If there are no pending requests when the flush method
+ * is called an exception is thrown (as this typically a sign of programming error).
+ */
+ $httpBackend.flush = function(count) {
+ $rootScope.$digest();
+ if (!responses.length) throw Error('No pending request to flush !');
+
+ if (angular.isDefined(count)) {
+ while (count--) {
+ if (!responses.length) throw Error('No more pending request to flush !');
+ responses.shift()();
+ }
+ } else {
+ while (responses.length) {
+ responses.shift()();
+ }
+ }
+ $httpBackend.verifyNoOutstandingExpectation();
+ };
+
+
+ /**
+ * @ngdoc method
+ * @name ngMock.$httpBackend#verifyNoOutstandingExpectation
+ * @methodOf ngMock.$httpBackend
+ * @description
+ * Verifies that all of the requests defined via the `expect` api were made. If any of the
+ * requests were not made, verifyNoOutstandingExpectation throws an exception.
+ *
+ * Typically, you would call this method following each test case that asserts requests using an
+ * "afterEach" clause.
+ *
+ *
+ */
+ $httpBackend.verifyNoOutstandingExpectation = function() {
+ $rootScope.$digest();
+ if (expectations.length) {
+ throw Error('Unsatisfied requests: ' + expectations.join(', '));
+ }
+ };
+
+
+ /**
+ * @ngdoc method
+ * @name ngMock.$httpBackend#verifyNoOutstandingRequest
+ * @methodOf ngMock.$httpBackend
+ * @description
+ * Verifies that there are no outstanding requests that need to be flushed.
+ *
+ * Typically, you would call this method following each test case that asserts requests using an
+ * "afterEach" clause.
+ *
+ *
+ */
+ $httpBackend.verifyNoOutstandingRequest = function() {
+ if (responses.length) {
+ throw Error('Unflushed requests: ' + responses.length);
+ }
+ };
+
+
+ /**
+ * @ngdoc method
+ * @name ngMock.$httpBackend#resetExpectations
+ * @methodOf ngMock.$httpBackend
+ * @description
+ * Resets all request expectations, but preserves all backend definitions. Typically, you would
+ * call resetExpectations during a multiple-phase test when you want to reuse the same instance of
+ * $httpBackend mock.
+ */
+ $httpBackend.resetExpectations = function() {
+ expectations.length = 0;
+ responses.length = 0;
+ };
+
+ return $httpBackend;
+
+
+ function createShortMethods(prefix) {
+ angular.forEach(['GET', 'DELETE', 'JSONP'], function(method) {
+ $httpBackend[prefix + method] = function(url, headers) {
+ return $httpBackend[prefix](method, url, undefined, headers)
+ }
+ });
+
+ angular.forEach(['PUT', 'POST', 'PATCH'], function(method) {
+ $httpBackend[prefix + method] = function(url, data, headers) {
+ return $httpBackend[prefix](method, url, data, headers)
+ }
+ });
+ }
+}
+
+function MockHttpExpectation(method, url, data, headers) {
+
+ this.data = data;
+ this.headers = headers;
+
+ this.match = function(m, u, d, h) {
+ if (method != m) return false;
+ if (!this.matchUrl(u)) return false;
+ if (angular.isDefined(d) && !this.matchData(d)) return false;
+ if (angular.isDefined(h) && !this.matchHeaders(h)) return false;
+ return true;
+ };
+
+ this.matchUrl = function(u) {
+ if (!url) return true;
+ if (angular.isFunction(url.test)) return url.test(u);
+ return url == u;
+ };
+
+ this.matchHeaders = function(h) {
+ if (angular.isUndefined(headers)) return true;
+ if (angular.isFunction(headers)) return headers(h);
+ return angular.equals(headers, h);
+ };
+
+ this.matchData = function(d) {
+ if (angular.isUndefined(data)) return true;
+ if (data && angular.isFunction(data.test)) return data.test(d);
+ if (data && !angular.isString(data)) return angular.toJson(data) == d;
+ return data == d;
+ };
+
+ this.toString = function() {
+ return method + ' ' + url;
+ };
+}
+
+function MockXhr() {
+
+ // hack for testing $http, $httpBackend
+ MockXhr.$$lastInstance = this;
+
+ this.open = function(method, url, async) {
+ this.$$method = method;
+ this.$$url = url;
+ this.$$async = async;
+ this.$$reqHeaders = {};
+ this.$$respHeaders = {};
+ };
+
+ this.send = function(data) {
+ this.$$data = data;
+ };
+
+ this.setRequestHeader = function(key, value) {
+ this.$$reqHeaders[key] = value;
+ };
+
+ this.getResponseHeader = function(name) {
+ // the lookup must be case insensitive, that's why we try two quick lookups and full scan at last
+ var header = this.$$respHeaders[name];
+ if (header) return header;
+
+ name = angular.lowercase(name);
+ header = this.$$respHeaders[name];
+ if (header) return header;
+
+ header = undefined;
+ angular.forEach(this.$$respHeaders, function(headerVal, headerName) {
+ if (!header && angular.lowercase(headerName) == name) header = headerVal;
+ });
+ return header;
+ };
+
+ this.getAllResponseHeaders = function() {
+ var lines = [];
+
+ angular.forEach(this.$$respHeaders, function(value, key) {
+ lines.push(key + ': ' + value);
+ });
+ return lines.join('\n');
+ };
+
+ this.abort = angular.noop;
+}
+
+
+/**
+ * @ngdoc function
+ * @name ngMock.$timeout
+ * @description
+ *
+ * This service is just a simple decorator for {@link ng.$timeout $timeout} service
+ * that adds a "flush" and "verifyNoPendingTasks" methods.
+ */
+
+angular.mock.$TimeoutDecorator = function($delegate, $browser) {
+
+ /**
+ * @ngdoc method
+ * @name ngMock.$timeout#flush
+ * @methodOf ngMock.$timeout
+ * @description
+ *
+ * Flushes the queue of pending tasks.
+ */
+ $delegate.flush = function() {
+ $browser.defer.flush();
+ };
+
+ /**
+ * @ngdoc method
+ * @name ngMock.$timeout#verifyNoPendingTasks
+ * @methodOf ngMock.$timeout
+ * @description
+ *
+ * Verifies that there are no pending tasks that need to be flushed.
+ */
+ $delegate.verifyNoPendingTasks = function() {
+ if ($browser.deferredFns.length) {
+ throw Error('Deferred tasks to flush (' + $browser.deferredFns.length + '): ' +
+ formatPendingTasksAsString($browser.deferredFns));
+ }
+ };
+
+ function formatPendingTasksAsString(tasks) {
+ var result = [];
+ angular.forEach(tasks, function(task) {
+ result.push('{id: ' + task.id + ', ' + 'time: ' + task.time + '}');
+ });
+
+ return result.join(', ');
+ }
+
+ return $delegate;
+};
+
+/**
+ *
+ */
+angular.mock.$RootElementProvider = function() {
+ this.$get = function() {
+ return angular.element('');
+ }
+};
+
+/**
+ * @ngdoc overview
+ * @name ngMock
+ * @description
+ *
+ * The `ngMock` is an angular module which is used with `ng` module and adds unit-test configuration as well as useful
+ * mocks to the {@link AUTO.$injector $injector}.
+ */
+angular.module('ngMock', ['ng']).provider({
+ $browser: angular.mock.$BrowserProvider,
+ $exceptionHandler: angular.mock.$ExceptionHandlerProvider,
+ $log: angular.mock.$LogProvider,
+ $httpBackend: angular.mock.$HttpBackendProvider,
+ $rootElement: angular.mock.$RootElementProvider
+}).config(function($provide) {
+ $provide.decorator('$timeout', angular.mock.$TimeoutDecorator);
+});
+
+/**
+ * @ngdoc overview
+ * @name ngMockE2E
+ * @description
+ *
+ * The `ngMockE2E` is an angular module which contains mocks suitable for end-to-end testing.
+ * Currently there is only one mock present in this module -
+ * the {@link ngMockE2E.$httpBackend e2e $httpBackend} mock.
+ */
+angular.module('ngMockE2E', ['ng']).config(function($provide) {
+ $provide.decorator('$httpBackend', angular.mock.e2e.$httpBackendDecorator);
+});
+
+/**
+ * @ngdoc object
+ * @name ngMockE2E.$httpBackend
+ * @description
+ * Fake HTTP backend implementation suitable for end-to-end testing or backend-less development of
+ * applications that use the {@link ng.$http $http service}.
+ *
+ * *Note*: For fake http backend implementation suitable for unit testing please see
+ * {@link ngMock.$httpBackend unit-testing $httpBackend mock}.
+ *
+ * This implementation can be used to respond with static or dynamic responses via the `when` api
+ * and its shortcuts (`whenGET`, `whenPOST`, etc) and optionally pass through requests to the
+ * real $httpBackend for specific requests (e.g. to interact with certain remote apis or to fetch
+ * templates from a webserver).
+ *
+ * As opposed to unit-testing, in an end-to-end testing scenario or in scenario when an application
+ * is being developed with the real backend api replaced with a mock, it is often desirable for
+ * certain category of requests to bypass the mock and issue a real http request (e.g. to fetch
+ * templates or static files from the webserver). To configure the backend with this behavior
+ * use the `passThrough` request handler of `when` instead of `respond`.
+ *
+ * Additionally, we don't want to manually have to flush mocked out requests like we do during unit
+ * testing. For this reason the e2e $httpBackend automatically flushes mocked out requests
+ * automatically, closely simulating the behavior of the XMLHttpRequest object.
+ *
+ * To setup the application to run with this http backend, you have to create a module that depends
+ * on the `ngMockE2E` and your application modules and defines the fake backend:
+ *
+ *
+ * myAppDev = angular.module('myAppDev', ['myApp', 'ngMockE2E']);
+ * myAppDev.run(function($httpBackend) {
+ * phones = [{name: 'phone1'}, {name: 'phone2'}];
+ *
+ * // returns the current list of phones
+ * $httpBackend.whenGET('/phones').respond(phones);
+ *
+ * // adds a new phone to the phones array
+ * $httpBackend.whenPOST('/phones').respond(function(method, url, data) {
+ * phones.push(angular.fromJSON(data));
+ * });
+ * $httpBackend.whenGET(/^\/templates\//).passThrough();
+ * //...
+ * });
+ *
+ *
+ * Afterwards, bootstrap your app with this new module.
+ */
+
+/**
+ * @ngdoc method
+ * @name ngMockE2E.$httpBackend#when
+ * @methodOf ngMockE2E.$httpBackend
+ * @description
+ * Creates a new backend definition.
+ *
+ * @param {string} method HTTP method.
+ * @param {string|RegExp} url HTTP url.
+ * @param {(string|RegExp)=} data HTTP request body.
+ * @param {(Object|function(Object))=} headers HTTP headers or function that receives http header
+ * object and returns true if the headers match the current definition.
+ * @returns {requestHandler} Returns an object with `respond` and `passThrough` methods that
+ * control how a matched request is handled.
+ *
+ * - respond – `{function([status,] data[, headers])|function(function(method, url, data, headers)}`
+ * – The respond method takes a set of static data to be returned or a function that can return
+ * an array containing response status (number), response data (string) and response headers
+ * (Object).
+ * - passThrough – `{function()}` – Any request matching a backend definition with `passThrough`
+ * handler, will be pass through to the real backend (an XHR request will be made to the
+ * server.
+ */
+
+/**
+ * @ngdoc method
+ * @name ngMockE2E.$httpBackend#whenGET
+ * @methodOf ngMockE2E.$httpBackend
+ * @description
+ * Creates a new backend definition for GET requests. For more info see `when()`.
+ *
+ * @param {string|RegExp} url HTTP url.
+ * @param {(Object|function(Object))=} headers HTTP headers.
+ * @returns {requestHandler} Returns an object with `respond` and `passThrough` methods that
+ * control how a matched request is handled.
+ */
+
+/**
+ * @ngdoc method
+ * @name ngMockE2E.$httpBackend#whenHEAD
+ * @methodOf ngMockE2E.$httpBackend
+ * @description
+ * Creates a new backend definition for HEAD requests. For more info see `when()`.
+ *
+ * @param {string|RegExp} url HTTP url.
+ * @param {(Object|function(Object))=} headers HTTP headers.
+ * @returns {requestHandler} Returns an object with `respond` and `passThrough` methods that
+ * control how a matched request is handled.
+ */
+
+/**
+ * @ngdoc method
+ * @name ngMockE2E.$httpBackend#whenDELETE
+ * @methodOf ngMockE2E.$httpBackend
+ * @description
+ * Creates a new backend definition for DELETE requests. For more info see `when()`.
+ *
+ * @param {string|RegExp} url HTTP url.
+ * @param {(Object|function(Object))=} headers HTTP headers.
+ * @returns {requestHandler} Returns an object with `respond` and `passThrough` methods that
+ * control how a matched request is handled.
+ */
+
+/**
+ * @ngdoc method
+ * @name ngMockE2E.$httpBackend#whenPOST
+ * @methodOf ngMockE2E.$httpBackend
+ * @description
+ * Creates a new backend definition for POST requests. For more info see `when()`.
+ *
+ * @param {string|RegExp} url HTTP url.
+ * @param {(string|RegExp)=} data HTTP request body.
+ * @param {(Object|function(Object))=} headers HTTP headers.
+ * @returns {requestHandler} Returns an object with `respond` and `passThrough` methods that
+ * control how a matched request is handled.
+ */
+
+/**
+ * @ngdoc method
+ * @name ngMockE2E.$httpBackend#whenPUT
+ * @methodOf ngMockE2E.$httpBackend
+ * @description
+ * Creates a new backend definition for PUT requests. For more info see `when()`.
+ *
+ * @param {string|RegExp} url HTTP url.
+ * @param {(string|RegExp)=} data HTTP request body.
+ * @param {(Object|function(Object))=} headers HTTP headers.
+ * @returns {requestHandler} Returns an object with `respond` and `passThrough` methods that
+ * control how a matched request is handled.
+ */
+
+/**
+ * @ngdoc method
+ * @name ngMockE2E.$httpBackend#whenPATCH
+ * @methodOf ngMockE2E.$httpBackend
+ * @description
+ * Creates a new backend definition for PATCH requests. For more info see `when()`.
+ *
+ * @param {string|RegExp} url HTTP url.
+ * @param {(string|RegExp)=} data HTTP request body.
+ * @param {(Object|function(Object))=} headers HTTP headers.
+ * @returns {requestHandler} Returns an object with `respond` and `passThrough` methods that
+ * control how a matched request is handled.
+ */
+
+/**
+ * @ngdoc method
+ * @name ngMockE2E.$httpBackend#whenJSONP
+ * @methodOf ngMockE2E.$httpBackend
+ * @description
+ * Creates a new backend definition for JSONP requests. For more info see `when()`.
+ *
+ * @param {string|RegExp} url HTTP url.
+ * @returns {requestHandler} Returns an object with `respond` and `passThrough` methods that
+ * control how a matched request is handled.
+ */
+angular.mock.e2e = {};
+angular.mock.e2e.$httpBackendDecorator = ['$rootScope', '$delegate', '$browser', createHttpBackendMock];
+
+
+angular.mock.clearDataCache = function() {
+ var key,
+ cache = angular.element.cache;
+
+ for(key in cache) {
+ if (cache.hasOwnProperty(key)) {
+ var handle = cache[key].handle;
+
+ handle && angular.element(handle.elem).unbind();
+ delete cache[key];
+ }
+ }
+};
+
+
+window.jstestdriver && (function(window) {
+ /**
+ * Global method to output any number of objects into JSTD console. Useful for debugging.
+ */
+ window.dump = function() {
+ var args = [];
+ angular.forEach(arguments, function(arg) {
+ args.push(angular.mock.dump(arg));
+ });
+ jstestdriver.console.log.apply(jstestdriver.console, args);
+ if (window.console) {
+ window.console.log.apply(window.console, args);
+ }
+ };
+})(window);
+
+
+(window.jasmine || window.mocha) && (function(window) {
+
+ var currentSpec = null;
+
+ beforeEach(function() {
+ currentSpec = this;
+ });
+
+ afterEach(function() {
+ var injector = currentSpec.$injector;
+
+ currentSpec.$injector = null;
+ currentSpec.$modules = null;
+ currentSpec = null;
+
+ if (injector) {
+ injector.get('$rootElement').unbind();
+ injector.get('$browser').pollFns.length = 0;
+ }
+
+ angular.mock.clearDataCache();
+
+ // clean up jquery's fragment cache
+ angular.forEach(angular.element.fragments, function(val, key) {
+ delete angular.element.fragments[key];
+ });
+
+ MockXhr.$$lastInstance = null;
+
+ angular.forEach(angular.callbacks, function(val, key) {
+ delete angular.callbacks[key];
+ });
+ angular.callbacks.counter = 0;
+ });
+
+ function isSpecRunning() {
+ return currentSpec && (window.mocha || currentSpec.queue.running);
+ }
+
+ /**
+ * @ngdoc function
+ * @name angular.mock.module
+ * @description
+ *
+ * *NOTE*: This function is also published on window for easy access.
+ *
+ * This function registers a module configuration code. It collects the configuration information
+ * which will be used when the injector is created by {@link angular.mock.inject inject}.
+ *
+ * See {@link angular.mock.inject inject} for usage example
+ *
+ * @param {...(string|Function)} fns any number of modules which are represented as string
+ * aliases or as anonymous module initialization functions. The modules are used to
+ * configure the injector. The 'ng' and 'ngMock' modules are automatically loaded.
+ */
+ window.module = angular.mock.module = function() {
+ var moduleFns = Array.prototype.slice.call(arguments, 0);
+ return isSpecRunning() ? workFn() : workFn;
+ /////////////////////
+ function workFn() {
+ if (currentSpec.$injector) {
+ throw Error('Injector already created, can not register a module!');
+ } else {
+ var modules = currentSpec.$modules || (currentSpec.$modules = []);
+ angular.forEach(moduleFns, function(module) {
+ modules.push(module);
+ });
+ }
+ }
+ };
+
+ /**
+ * @ngdoc function
+ * @name angular.mock.inject
+ * @description
+ *
+ * *NOTE*: This function is also published on window for easy access.
+ *
+ * The inject function wraps a function into an injectable function. The inject() creates new
+ * instance of {@link AUTO.$injector $injector} per test, which is then used for
+ * resolving references.
+ *
+ * See also {@link angular.mock.module module}
+ *
+ * Example of what a typical jasmine tests looks like with the inject method.
+ *
+ *
+ * angular.module('myApplicationModule', [])
+ * .value('mode', 'app')
+ * .value('version', 'v1.0.1');
+ *
+ *
+ * describe('MyApp', function() {
+ *
+ * // You need to load modules that you want to test,
+ * // it loads only the "ng" module by default.
+ * beforeEach(module('myApplicationModule'));
+ *
+ *
+ * // inject() is used to inject arguments of all given functions
+ * it('should provide a version', inject(function(mode, version) {
+ * expect(version).toEqual('v1.0.1');
+ * expect(mode).toEqual('app');
+ * }));
+ *
+ *
+ * // The inject and module method can also be used inside of the it or beforeEach
+ * it('should override a version and test the new version is injected', function() {
+ * // module() takes functions or strings (module aliases)
+ * module(function($provide) {
+ * $provide.value('version', 'overridden'); // override version here
+ * });
+ *
+ * inject(function(version) {
+ * expect(version).toEqual('overridden');
+ * });
+ * ));
+ * });
+ *
+ *
+ *
+ * @param {...Function} fns any number of functions which will be injected using the injector.
+ */
+ window.inject = angular.mock.inject = function() {
+ var blockFns = Array.prototype.slice.call(arguments, 0);
+ var errorForStack = new Error('Declaration Location');
+ return isSpecRunning() ? workFn() : workFn;
+ /////////////////////
+ function workFn() {
+ var modules = currentSpec.$modules || [];
+
+ modules.unshift('ngMock');
+ modules.unshift('ng');
+ var injector = currentSpec.$injector;
+ if (!injector) {
+ injector = currentSpec.$injector = angular.injector(modules);
+ }
+ for(var i = 0, ii = blockFns.length; i < ii; i++) {
+ try {
+ injector.invoke(blockFns[i] || angular.noop, this);
+ } catch (e) {
+ if(e.stack && errorForStack) e.stack += '\n' + errorForStack.stack;
+ throw e;
+ } finally {
+ errorForStack = null;
+ }
+ }
+ }
+ };
+})(window);
\ No newline at end of file
diff --git a/v2/dboards/src/vendor/angular/angular-sanitize.js b/v2/dboards/src/vendor/angular/angular-sanitize.js
new file mode 100644
index 0000000..a2d8d34
--- /dev/null
+++ b/v2/dboards/src/vendor/angular/angular-sanitize.js
@@ -0,0 +1,558 @@
+/**
+ * @license AngularJS v1.1.5
+ * (c) 2010-2012 Google, Inc. http://angularjs.org
+ * License: MIT
+ */
+(function(window, angular, undefined) {
+'use strict';
+
+/**
+ * @ngdoc overview
+ * @name ngSanitize
+ * @description
+ */
+
+/*
+ * HTML Parser By Misko Hevery (misko@hevery.com)
+ * based on: HTML Parser By John Resig (ejohn.org)
+ * Original code by Erik Arvidsson, Mozilla Public License
+ * http://erik.eae.net/simplehtmlparser/simplehtmlparser.js
+ *
+ * // Use like so:
+ * htmlParser(htmlString, {
+ * start: function(tag, attrs, unary) {},
+ * end: function(tag) {},
+ * chars: function(text) {},
+ * comment: function(text) {}
+ * });
+ *
+ */
+
+
+/**
+ * @ngdoc service
+ * @name ngSanitize.$sanitize
+ * @function
+ *
+ * @description
+ * The input is sanitized by parsing the html into tokens. All safe tokens (from a whitelist) are
+ * then serialized back to properly escaped html string. This means that no unsafe input can make
+ * it into the returned string, however, since our parser is more strict than a typical browser
+ * parser, it's possible that some obscure input, which would be recognized as valid HTML by a
+ * browser, won't make it through the sanitizer.
+ *
+ * @param {string} html Html input.
+ * @returns {string} Sanitized html.
+ *
+ * @example
+
+
+
+
+ Snippet:
+
+
+
Filter
+
Source
+
Rendered
+
+
+
html filter
+
+
<div ng-bind-html="snippet"> </div>
+
+
+
+
+
+
+
no filter
+
<div ng-bind="snippet"> </div>
+
+
+
+
unsafe html filter
+
<div ng-bind-html-unsafe="snippet"> </div>
+
+
+
+
+
+
+ it('should sanitize the html snippet ', function() {
+ expect(using('#html-filter').element('div').html()).
+ toBe('
an html\nclick here\nsnippet
');
+ });
+
+ it('should escape snippet without any filter', function() {
+ expect(using('#escaped-html').element('div').html()).
+ toBe("<p style=\"color:blue\">an html\n" +
+ "<em onmouseover=\"this.textContent='PWN3D!'\">click here</em>\n" +
+ "snippet</p>");
+ });
+
+ it('should inline raw snippet if filtered as unsafe', function() {
+ expect(using('#html-unsafe-filter').element("div").html()).
+ toBe("
an html\n" +
+ "click here\n" +
+ "snippet
");
+ });
+
+ it('should update', function() {
+ input('snippet').enter('new text');
+ expect(using('#html-filter').binding('snippet')).toBe('new text');
+ expect(using('#escaped-html').element('div').html()).toBe("new <b>text</b>");
+ expect(using('#html-unsafe-filter').binding("snippet")).toBe('new text');
+ });
+
+
+ */
+var $sanitize = function(html) {
+ var buf = [];
+ htmlParser(html, htmlSanitizeWriter(buf));
+ return buf.join('');
+};
+
+
+// Regular Expressions for parsing tags and attributes
+var START_TAG_REGEXP = /^<\s*([\w:-]+)((?:\s+[\w:-]+(?:\s*=\s*(?:(?:"[^"]*")|(?:'[^']*')|[^>\s]+))?)*)\s*(\/?)\s*>/,
+ END_TAG_REGEXP = /^<\s*\/\s*([\w:-]+)[^>]*>/,
+ ATTR_REGEXP = /([\w:-]+)(?:\s*=\s*(?:(?:"((?:[^"])*)")|(?:'((?:[^'])*)')|([^>\s]+)))?/g,
+ BEGIN_TAG_REGEXP = /^,
+ BEGING_END_TAGE_REGEXP = /^<\s*\//,
+ COMMENT_REGEXP = //g,
+ CDATA_REGEXP = //g,
+ URI_REGEXP = /^((ftp|https?):\/\/|mailto:|tel:|#)/,
+ NON_ALPHANUMERIC_REGEXP = /([^\#-~| |!])/g; // Match everything outside of normal chars and " (quote character)
+
+
+// Good source of info about elements and attributes
+// http://dev.w3.org/html5/spec/Overview.html#semantics
+// http://simon.html5.org/html-elements
+
+// Safe Void Elements - HTML5
+// http://dev.w3.org/html5/spec/Overview.html#void-elements
+var voidElements = makeMap("area,br,col,hr,img,wbr");
+
+// Elements that you can, intentionally, leave open (and which close themselves)
+// http://dev.w3.org/html5/spec/Overview.html#optional-tags
+var optionalEndTagBlockElements = makeMap("colgroup,dd,dt,li,p,tbody,td,tfoot,th,thead,tr"),
+ optionalEndTagInlineElements = makeMap("rp,rt"),
+ optionalEndTagElements = angular.extend({}, optionalEndTagInlineElements, optionalEndTagBlockElements);
+
+// Safe Block Elements - HTML5
+var blockElements = angular.extend({}, optionalEndTagBlockElements, makeMap("address,article,aside," +
+ "blockquote,caption,center,del,dir,div,dl,figure,figcaption,footer,h1,h2,h3,h4,h5,h6," +
+ "header,hgroup,hr,ins,map,menu,nav,ol,pre,script,section,table,ul"));
+
+// Inline Elements - HTML5
+var inlineElements = angular.extend({}, optionalEndTagInlineElements, makeMap("a,abbr,acronym,b,bdi,bdo," +
+ "big,br,cite,code,del,dfn,em,font,i,img,ins,kbd,label,map,mark,q,ruby,rp,rt,s,samp,small," +
+ "span,strike,strong,sub,sup,time,tt,u,var"));
+
+
+// Special Elements (can contain anything)
+var specialElements = makeMap("script,style");
+
+var validElements = angular.extend({}, voidElements, blockElements, inlineElements, optionalEndTagElements);
+
+//Attributes that have href and hence need to be sanitized
+var uriAttrs = makeMap("background,cite,href,longdesc,src,usemap");
+var validAttrs = angular.extend({}, uriAttrs, makeMap(
+ 'abbr,align,alt,axis,bgcolor,border,cellpadding,cellspacing,class,clear,'+
+ 'color,cols,colspan,compact,coords,dir,face,headers,height,hreflang,hspace,'+
+ 'ismap,lang,language,nohref,nowrap,rel,rev,rows,rowspan,rules,'+
+ 'scope,scrolling,shape,span,start,summary,target,title,type,'+
+ 'valign,value,vspace,width'));
+
+function makeMap(str) {
+ var obj = {}, items = str.split(','), i;
+ for (i = 0; i < items.length; i++) obj[items[i]] = true;
+ return obj;
+}
+
+
+/**
+ * @example
+ * htmlParser(htmlString, {
+ * start: function(tag, attrs, unary) {},
+ * end: function(tag) {},
+ * chars: function(text) {},
+ * comment: function(text) {}
+ * });
+ *
+ * @param {string} html string
+ * @param {object} handler
+ */
+function htmlParser( html, handler ) {
+ var index, chars, match, stack = [], last = html;
+ stack.last = function() { return stack[ stack.length - 1 ]; };
+
+ while ( html ) {
+ chars = true;
+
+ // Make sure we're not in a script or style element
+ if ( !stack.last() || !specialElements[ stack.last() ] ) {
+
+ // Comment
+ if ( html.indexOf("");
+
+ if ( index >= 0 ) {
+ if (handler.comment) handler.comment( html.substring( 4, index ) );
+ html = html.substring( index + 3 );
+ chars = false;
+ }
+
+ // end tag
+ } else if ( BEGING_END_TAGE_REGEXP.test(html) ) {
+ match = html.match( END_TAG_REGEXP );
+
+ if ( match ) {
+ html = html.substring( match[0].length );
+ match[0].replace( END_TAG_REGEXP, parseEndTag );
+ chars = false;
+ }
+
+ // start tag
+ } else if ( BEGIN_TAG_REGEXP.test(html) ) {
+ match = html.match( START_TAG_REGEXP );
+
+ if ( match ) {
+ html = html.substring( match[0].length );
+ match[0].replace( START_TAG_REGEXP, parseStartTag );
+ chars = false;
+ }
+ }
+
+ if ( chars ) {
+ index = html.indexOf("<");
+
+ var text = index < 0 ? html : html.substring( 0, index );
+ html = index < 0 ? "" : html.substring( index );
+
+ if (handler.chars) handler.chars( decodeEntities(text) );
+ }
+
+ } else {
+ html = html.replace(new RegExp("(.*)<\\s*\\/\\s*" + stack.last() + "[^>]*>", 'i'), function(all, text){
+ text = text.
+ replace(COMMENT_REGEXP, "$1").
+ replace(CDATA_REGEXP, "$1");
+
+ if (handler.chars) handler.chars( decodeEntities(text) );
+
+ return "";
+ });
+
+ parseEndTag( "", stack.last() );
+ }
+
+ if ( html == last ) {
+ throw "Parse Error: " + html;
+ }
+ last = html;
+ }
+
+ // Clean up any remaining tags
+ parseEndTag();
+
+ function parseStartTag( tag, tagName, rest, unary ) {
+ tagName = angular.lowercase(tagName);
+ if ( blockElements[ tagName ] ) {
+ while ( stack.last() && inlineElements[ stack.last() ] ) {
+ parseEndTag( "", stack.last() );
+ }
+ }
+
+ if ( optionalEndTagElements[ tagName ] && stack.last() == tagName ) {
+ parseEndTag( "", tagName );
+ }
+
+ unary = voidElements[ tagName ] || !!unary;
+
+ if ( !unary )
+ stack.push( tagName );
+
+ var attrs = {};
+
+ rest.replace(ATTR_REGEXP, function(match, name, doubleQuotedValue, singleQoutedValue, unqoutedValue) {
+ var value = doubleQuotedValue
+ || singleQoutedValue
+ || unqoutedValue
+ || '';
+
+ attrs[name] = decodeEntities(value);
+ });
+ if (handler.start) handler.start( tagName, attrs, unary );
+ }
+
+ function parseEndTag( tag, tagName ) {
+ var pos = 0, i;
+ tagName = angular.lowercase(tagName);
+ if ( tagName )
+ // Find the closest opened tag of the same type
+ for ( pos = stack.length - 1; pos >= 0; pos-- )
+ if ( stack[ pos ] == tagName )
+ break;
+
+ if ( pos >= 0 ) {
+ // Close all the open elements, up the stack
+ for ( i = stack.length - 1; i >= pos; i-- )
+ if (handler.end) handler.end( stack[ i ] );
+
+ // Remove the open elements from the stack
+ stack.length = pos;
+ }
+ }
+}
+
+/**
+ * decodes all entities into regular string
+ * @param value
+ * @returns {string} A string with decoded entities.
+ */
+var hiddenPre=document.createElement("pre");
+function decodeEntities(value) {
+ hiddenPre.innerHTML=value.replace(//g, '>');
+}
+
+/**
+ * create an HTML/XML writer which writes to buffer
+ * @param {Array} buf use buf.jain('') to get out sanitized html string
+ * @returns {object} in the form of {
+ * start: function(tag, attrs, unary) {},
+ * end: function(tag) {},
+ * chars: function(text) {},
+ * comment: function(text) {}
+ * }
+ */
+function htmlSanitizeWriter(buf){
+ var ignore = false;
+ var out = angular.bind(buf, buf.push);
+ return {
+ start: function(tag, attrs, unary){
+ tag = angular.lowercase(tag);
+ if (!ignore && specialElements[tag]) {
+ ignore = tag;
+ }
+ if (!ignore && validElements[tag] == true) {
+ out('<');
+ out(tag);
+ angular.forEach(attrs, function(value, key){
+ var lkey=angular.lowercase(key);
+ if (validAttrs[lkey]==true && (uriAttrs[lkey]!==true || value.match(URI_REGEXP))) {
+ out(' ');
+ out(key);
+ out('="');
+ out(encodeEntities(value));
+ out('"');
+ }
+ });
+ out(unary ? '/>' : '>');
+ }
+ },
+ end: function(tag){
+ tag = angular.lowercase(tag);
+ if (!ignore && validElements[tag] == true) {
+ out('');
+ out(tag);
+ out('>');
+ }
+ if (tag == ignore) {
+ ignore = false;
+ }
+ },
+ chars: function(chars){
+ if (!ignore) {
+ out(encodeEntities(chars));
+ }
+ }
+ };
+}
+
+
+// define ngSanitize module and register $sanitize service
+angular.module('ngSanitize', []).value('$sanitize', $sanitize);
+
+/**
+ * @ngdoc directive
+ * @name ngSanitize.directive:ngBindHtml
+ *
+ * @description
+ * Creates a binding that will sanitize the result of evaluating the `expression` with the
+ * {@link ngSanitize.$sanitize $sanitize} service and innerHTML the result into the current element.
+ *
+ * See {@link ngSanitize.$sanitize $sanitize} docs for examples.
+ *
+ * @element ANY
+ * @param {expression} ngBindHtml {@link guide/expression Expression} to evaluate.
+ */
+angular.module('ngSanitize').directive('ngBindHtml', ['$sanitize', function($sanitize) {
+ return function(scope, element, attr) {
+ element.addClass('ng-binding').data('$binding', attr.ngBindHtml);
+ scope.$watch(attr.ngBindHtml, function ngBindHtmlWatchAction(value) {
+ value = $sanitize(value);
+ element.html(value || '');
+ });
+ };
+}]);
+
+/**
+ * @ngdoc filter
+ * @name ngSanitize.filter:linky
+ * @function
+ *
+ * @description
+ * Finds links in text input and turns them into html links. Supports http/https/ftp/mailto and
+ * plain email address links.
+ *
+ * @param {string} text Input text.
+ * @param {string} target Window (_blank|_self|_parent|_top) or named frame to open links in.
+ * @returns {string} Html-linkified text.
+ *
+ * @usage
+
+ *
+ * @example
+
+
+
+
+ *
+ * @param {Object|Array} obj Object to iterate over.
+ * @param {Function} iterator Iterator function.
+ * @param {Object=} context Object to become context (`this`) for the iterator function.
+ * @returns {Object|Array} Reference to `obj`.
+ */
+function forEach(obj, iterator, context) {
+ var key;
+ if (obj) {
+ if (isFunction(obj)){
+ for (key in obj) {
+ if (key != 'prototype' && key != 'length' && key != 'name' && obj.hasOwnProperty(key)) {
+ iterator.call(context, obj[key], key);
+ }
+ }
+ } else if (obj.forEach && obj.forEach !== forEach) {
+ obj.forEach(iterator, context);
+ } else if (isArrayLike(obj)) {
+ for (key = 0; key < obj.length; key++)
+ iterator.call(context, obj[key], key);
+ } else {
+ for (key in obj) {
+ if (obj.hasOwnProperty(key)) {
+ iterator.call(context, obj[key], key);
+ }
+ }
+ }
+ }
+ return obj;
+}
+
+function sortedKeys(obj) {
+ var keys = [];
+ for (var key in obj) {
+ if (obj.hasOwnProperty(key)) {
+ keys.push(key);
+ }
+ }
+ return keys.sort();
+}
+
+function forEachSorted(obj, iterator, context) {
+ var keys = sortedKeys(obj);
+ for ( var i = 0; i < keys.length; i++) {
+ iterator.call(context, obj[keys[i]], keys[i]);
+ }
+ return keys;
+}
+
+
+/**
+ * when using forEach the params are value, key, but it is often useful to have key, value.
+ * @param {function(string, *)} iteratorFn
+ * @returns {function(*, string)}
+ */
+function reverseParams(iteratorFn) {
+ return function(value, key) { iteratorFn(key, value) };
+}
+
+/**
+ * A consistent way of creating unique IDs in angular. The ID is a sequence of alpha numeric
+ * characters such as '012ABC'. The reason why we are not using simply a number counter is that
+ * the number string gets longer over time, and it can also overflow, where as the nextId
+ * will grow much slower, it is a string, and it will never overflow.
+ *
+ * @returns an unique alpha-numeric string
+ */
+function nextUid() {
+ var index = uid.length;
+ var digit;
+
+ while(index) {
+ index--;
+ digit = uid[index].charCodeAt(0);
+ if (digit == 57 /*'9'*/) {
+ uid[index] = 'A';
+ return uid.join('');
+ }
+ if (digit == 90 /*'Z'*/) {
+ uid[index] = '0';
+ } else {
+ uid[index] = String.fromCharCode(digit + 1);
+ return uid.join('');
+ }
+ }
+ uid.unshift('0');
+ return uid.join('');
+}
+
+
+/**
+ * Set or clear the hashkey for an object.
+ * @param obj object
+ * @param h the hashkey (!truthy to delete the hashkey)
+ */
+function setHashKey(obj, h) {
+ if (h) {
+ obj.$$hashKey = h;
+ }
+ else {
+ delete obj.$$hashKey;
+ }
+}
+
+/**
+ * @ngdoc function
+ * @name angular.extend
+ * @function
+ *
+ * @description
+ * Extends the destination object `dst` by copying all of the properties from the `src` object(s)
+ * to `dst`. You can specify multiple `src` objects.
+ *
+ * @param {Object} dst Destination object.
+ * @param {...Object} src Source object(s).
+ * @returns {Object} Reference to `dst`.
+ */
+function extend(dst) {
+ var h = dst.$$hashKey;
+ forEach(arguments, function(obj){
+ if (obj !== dst) {
+ forEach(obj, function(value, key){
+ dst[key] = value;
+ });
+ }
+ });
+
+ setHashKey(dst,h);
+ return dst;
+}
+
+function int(str) {
+ return parseInt(str, 10);
+}
+
+
+function inherit(parent, extra) {
+ return extend(new (extend(function() {}, {prototype:parent}))(), extra);
+}
+
+var START_SPACE = /^\s*/;
+var END_SPACE = /\s*$/;
+function stripWhitespace(str) {
+ return isString(str) ? str.replace(START_SPACE, '').replace(END_SPACE, '') : str;
+}
+
+/**
+ * @ngdoc function
+ * @name angular.noop
+ * @function
+ *
+ * @description
+ * A function that performs no operations. This function can be useful when writing code in the
+ * functional style.
+
+ function foo(callback) {
+ var result = calculateResult();
+ (callback || angular.noop)(result);
+ }
+
+ */
+function noop() {}
+noop.$inject = [];
+
+
+/**
+ * @ngdoc function
+ * @name angular.identity
+ * @function
+ *
+ * @description
+ * A function that returns its first argument. This function is useful when writing code in the
+ * functional style.
+ *
+
+ */
+function identity($) {return $;}
+identity.$inject = [];
+
+
+function valueFn(value) {return function() {return value;};}
+
+/**
+ * @ngdoc function
+ * @name angular.isUndefined
+ * @function
+ *
+ * @description
+ * Determines if a reference is undefined.
+ *
+ * @param {*} value Reference to check.
+ * @returns {boolean} True if `value` is undefined.
+ */
+function isUndefined(value){return typeof value == 'undefined';}
+
+
+/**
+ * @ngdoc function
+ * @name angular.isDefined
+ * @function
+ *
+ * @description
+ * Determines if a reference is defined.
+ *
+ * @param {*} value Reference to check.
+ * @returns {boolean} True if `value` is defined.
+ */
+function isDefined(value){return typeof value != 'undefined';}
+
+
+/**
+ * @ngdoc function
+ * @name angular.isObject
+ * @function
+ *
+ * @description
+ * Determines if a reference is an `Object`. Unlike `typeof` in JavaScript, `null`s are not
+ * considered to be objects.
+ *
+ * @param {*} value Reference to check.
+ * @returns {boolean} True if `value` is an `Object` but not `null`.
+ */
+function isObject(value){return value != null && typeof value == 'object';}
+
+
+/**
+ * @ngdoc function
+ * @name angular.isString
+ * @function
+ *
+ * @description
+ * Determines if a reference is a `String`.
+ *
+ * @param {*} value Reference to check.
+ * @returns {boolean} True if `value` is a `String`.
+ */
+function isString(value){return typeof value == 'string';}
+
+
+/**
+ * @ngdoc function
+ * @name angular.isNumber
+ * @function
+ *
+ * @description
+ * Determines if a reference is a `Number`.
+ *
+ * @param {*} value Reference to check.
+ * @returns {boolean} True if `value` is a `Number`.
+ */
+function isNumber(value){return typeof value == 'number';}
+
+
+/**
+ * @ngdoc function
+ * @name angular.isDate
+ * @function
+ *
+ * @description
+ * Determines if a value is a date.
+ *
+ * @param {*} value Reference to check.
+ * @returns {boolean} True if `value` is a `Date`.
+ */
+function isDate(value){
+ return toString.apply(value) == '[object Date]';
+}
+
+
+/**
+ * @ngdoc function
+ * @name angular.isArray
+ * @function
+ *
+ * @description
+ * Determines if a reference is an `Array`.
+ *
+ * @param {*} value Reference to check.
+ * @returns {boolean} True if `value` is an `Array`.
+ */
+function isArray(value) {
+ return toString.apply(value) == '[object Array]';
+}
+
+
+/**
+ * @ngdoc function
+ * @name angular.isFunction
+ * @function
+ *
+ * @description
+ * Determines if a reference is a `Function`.
+ *
+ * @param {*} value Reference to check.
+ * @returns {boolean} True if `value` is a `Function`.
+ */
+function isFunction(value){return typeof value == 'function';}
+
+
+/**
+ * Checks if `obj` is a window object.
+ *
+ * @private
+ * @param {*} obj Object to check
+ * @returns {boolean} True if `obj` is a window obj.
+ */
+function isWindow(obj) {
+ return obj && obj.document && obj.location && obj.alert && obj.setInterval;
+}
+
+
+function isScope(obj) {
+ return obj && obj.$evalAsync && obj.$watch;
+}
+
+
+function isFile(obj) {
+ return toString.apply(obj) === '[object File]';
+}
+
+
+function isBoolean(value) {
+ return typeof value == 'boolean';
+}
+
+
+function trim(value) {
+ return isString(value) ? value.replace(/^\s*/, '').replace(/\s*$/, '') : value;
+}
+
+/**
+ * @ngdoc function
+ * @name angular.isElement
+ * @function
+ *
+ * @description
+ * Determines if a reference is a DOM element (or wrapped jQuery element).
+ *
+ * @param {*} value Reference to check.
+ * @returns {boolean} True if `value` is a DOM element (or wrapped jQuery element).
+ */
+function isElement(node) {
+ return node &&
+ (node.nodeName // we are a direct element
+ || (node.bind && node.find)); // we have a bind and find method part of jQuery API
+}
+
+/**
+ * @param str 'key1,key2,...'
+ * @returns {object} in the form of {key1:true, key2:true, ...}
+ */
+function makeMap(str){
+ var obj = {}, items = str.split(","), i;
+ for ( i = 0; i < items.length; i++ )
+ obj[ items[i] ] = true;
+ return obj;
+}
+
+
+if (msie < 9) {
+ nodeName_ = function(element) {
+ element = element.nodeName ? element : element[0];
+ return (element.scopeName && element.scopeName != 'HTML')
+ ? uppercase(element.scopeName + ':' + element.nodeName) : element.nodeName;
+ };
+} else {
+ nodeName_ = function(element) {
+ return element.nodeName ? element.nodeName : element[0].nodeName;
+ };
+}
+
+
+function map(obj, iterator, context) {
+ var results = [];
+ forEach(obj, function(value, index, list) {
+ results.push(iterator.call(context, value, index, list));
+ });
+ return results;
+}
+
+
+/**
+ * @description
+ * Determines the number of elements in an array, the number of properties an object has, or
+ * the length of a string.
+ *
+ * Note: This function is used to augment the Object type in Angular expressions. See
+ * {@link angular.Object} for more information about Angular arrays.
+ *
+ * @param {Object|Array|string} obj Object, array, or string to inspect.
+ * @param {boolean} [ownPropsOnly=false] Count only "own" properties in an object
+ * @returns {number} The size of `obj` or `0` if `obj` is neither an object nor an array.
+ */
+function size(obj, ownPropsOnly) {
+ var size = 0, key;
+
+ if (isArray(obj) || isString(obj)) {
+ return obj.length;
+ } else if (isObject(obj)){
+ for (key in obj)
+ if (!ownPropsOnly || obj.hasOwnProperty(key))
+ size++;
+ }
+
+ return size;
+}
+
+
+function includes(array, obj) {
+ return indexOf(array, obj) != -1;
+}
+
+function indexOf(array, obj) {
+ if (array.indexOf) return array.indexOf(obj);
+
+ for ( var i = 0; i < array.length; i++) {
+ if (obj === array[i]) return i;
+ }
+ return -1;
+}
+
+function arrayRemove(array, value) {
+ var index = indexOf(array, value);
+ if (index >=0)
+ array.splice(index, 1);
+ return value;
+}
+
+function isLeafNode (node) {
+ if (node) {
+ switch (node.nodeName) {
+ case "OPTION":
+ case "PRE":
+ case "TITLE":
+ return true;
+ }
+ }
+ return false;
+}
+
+/**
+ * @ngdoc function
+ * @name angular.copy
+ * @function
+ *
+ * @description
+ * Creates a deep copy of `source`, which should be an object or an array.
+ *
+ * * If no destination is supplied, a copy of the object or array is created.
+ * * If a destination is provided, all of its elements (for array) or properties (for objects)
+ * are deleted and then all elements/properties from the source are copied to it.
+ * * If `source` is not an object or array, `source` is returned.
+ *
+ * Note: this function is used to augment the Object type in Angular expressions. See
+ * {@link ng.$filter} for more information about Angular arrays.
+ *
+ * @param {*} source The source that will be used to make a copy.
+ * Can be any type, including primitives, `null`, and `undefined`.
+ * @param {(Object|Array)=} destination Destination into which the source is copied. If
+ * provided, must be of the same type as `source`.
+ * @returns {*} The copy or updated `destination`, if `destination` was specified.
+ */
+function copy(source, destination){
+ if (isWindow(source) || isScope(source)) throw Error("Can't copy Window or Scope");
+ if (!destination) {
+ destination = source;
+ if (source) {
+ if (isArray(source)) {
+ destination = copy(source, []);
+ } else if (isDate(source)) {
+ destination = new Date(source.getTime());
+ } else if (isObject(source)) {
+ destination = copy(source, {});
+ }
+ }
+ } else {
+ if (source === destination) throw Error("Can't copy equivalent objects or arrays");
+ if (isArray(source)) {
+ destination.length = 0;
+ for ( var i = 0; i < source.length; i++) {
+ destination.push(copy(source[i]));
+ }
+ } else {
+ var h = destination.$$hashKey;
+ forEach(destination, function(value, key){
+ delete destination[key];
+ });
+ for ( var key in source) {
+ destination[key] = copy(source[key]);
+ }
+ setHashKey(destination,h);
+ }
+ }
+ return destination;
+}
+
+/**
+ * Create a shallow copy of an object
+ */
+function shallowCopy(src, dst) {
+ dst = dst || {};
+
+ for(var key in src) {
+ if (src.hasOwnProperty(key) && key.substr(0, 2) !== '$$') {
+ dst[key] = src[key];
+ }
+ }
+
+ return dst;
+}
+
+
+/**
+ * @ngdoc function
+ * @name angular.equals
+ * @function
+ *
+ * @description
+ * Determines if two objects or two values are equivalent. Supports value types, arrays and
+ * objects.
+ *
+ * Two objects or values are considered equivalent if at least one of the following is true:
+ *
+ * * Both objects or values pass `===` comparison.
+ * * Both objects or values are of the same type and all of their properties pass `===` comparison.
+ * * Both values are NaN. (In JavasScript, NaN == NaN => false. But we consider two NaN as equal)
+ *
+ * During a property comparison, properties of `function` type and properties with names
+ * that begin with `$` are ignored.
+ *
+ * Scope and DOMWindow objects are being compared only by identify (`===`).
+ *
+ * @param {*} o1 Object or value to compare.
+ * @param {*} o2 Object or value to compare.
+ * @returns {boolean} True if arguments are equal.
+ */
+function equals(o1, o2) {
+ if (o1 === o2) return true;
+ if (o1 === null || o2 === null) return false;
+ if (o1 !== o1 && o2 !== o2) return true; // NaN === NaN
+ var t1 = typeof o1, t2 = typeof o2, length, key, keySet;
+ if (t1 == t2) {
+ if (t1 == 'object') {
+ if (isArray(o1)) {
+ if ((length = o1.length) == o2.length) {
+ for(key=0; key 2 ? sliceArgs(arguments, 2) : [];
+ if (isFunction(fn) && !(fn instanceof RegExp)) {
+ return curryArgs.length
+ ? function() {
+ return arguments.length
+ ? fn.apply(self, curryArgs.concat(slice.call(arguments, 0)))
+ : fn.apply(self, curryArgs);
+ }
+ : function() {
+ return arguments.length
+ ? fn.apply(self, arguments)
+ : fn.call(self);
+ };
+ } else {
+ // in IE, native methods are not functions so they cannot be bound (note: they don't need to be)
+ return fn;
+ }
+}
+
+
+function toJsonReplacer(key, value) {
+ var val = value;
+
+ if (/^\$+/.test(key)) {
+ val = undefined;
+ } else if (isWindow(value)) {
+ val = '$WINDOW';
+ } else if (value && document === value) {
+ val = '$DOCUMENT';
+ } else if (isScope(value)) {
+ val = '$SCOPE';
+ }
+
+ return val;
+}
+
+
+/**
+ * @ngdoc function
+ * @name angular.toJson
+ * @function
+ *
+ * @description
+ * Serializes input into a JSON-formatted string.
+ *
+ * @param {Object|Array|Date|string|number} obj Input to be serialized into JSON.
+ * @param {boolean=} pretty If set to true, the JSON output will contain newlines and whitespace.
+ * @returns {string} Jsonified string representing `obj`.
+ */
+function toJson(obj, pretty) {
+ return JSON.stringify(obj, toJsonReplacer, pretty ? ' ' : null);
+}
+
+
+/**
+ * @ngdoc function
+ * @name angular.fromJson
+ * @function
+ *
+ * @description
+ * Deserializes a JSON string.
+ *
+ * @param {string} json JSON string to deserialize.
+ * @returns {Object|Array|Date|string|number} Deserialized thingy.
+ */
+function fromJson(json) {
+ return isString(json)
+ ? JSON.parse(json)
+ : json;
+}
+
+
+function toBoolean(value) {
+ if (value && value.length !== 0) {
+ var v = lowercase("" + value);
+ value = !(v == 'f' || v == '0' || v == 'false' || v == 'no' || v == 'n' || v == '[]');
+ } else {
+ value = false;
+ }
+ return value;
+}
+
+/**
+ * @returns {string} Returns the string representation of the element.
+ */
+function startingTag(element) {
+ element = jqLite(element).clone();
+ try {
+ // turns out IE does not let you set .html() on elements which
+ // are not allowed to have children. So we just ignore it.
+ element.html('');
+ } catch(e) {}
+ // As Per DOM Standards
+ var TEXT_NODE = 3;
+ var elemHtml = jqLite('
').append(element).html();
+ try {
+ return element[0].nodeType === TEXT_NODE ? lowercase(elemHtml) :
+ elemHtml.
+ match(/^(<[^>]+>)/)[1].
+ replace(/^<([\w\-]+)/, function(match, nodeName) { return '<' + lowercase(nodeName); });
+ } catch(e) {
+ return lowercase(elemHtml);
+ }
+
+}
+
+
+/////////////////////////////////////////////////
+
+/**
+ * Parses an escaped url query string into key-value pairs.
+ * @returns Object.<(string|boolean)>
+ */
+function parseKeyValue(/**string*/keyValue) {
+ var obj = {}, key_value, key;
+ forEach((keyValue || "").split('&'), function(keyValue){
+ if (keyValue) {
+ key_value = keyValue.split('=');
+ key = decodeURIComponent(key_value[0]);
+ obj[key] = isDefined(key_value[1]) ? decodeURIComponent(key_value[1]) : true;
+ }
+ });
+ return obj;
+}
+
+function toKeyValue(obj) {
+ var parts = [];
+ forEach(obj, function(value, key) {
+ parts.push(encodeUriQuery(key, true) + (value === true ? '' : '=' + encodeUriQuery(value, true)));
+ });
+ return parts.length ? parts.join('&') : '';
+}
+
+
+/**
+ * We need our custom method because encodeURIComponent is too aggressive and doesn't follow
+ * http://www.ietf.org/rfc/rfc3986.txt with regards to the character set (pchar) allowed in path
+ * segments:
+ * segment = *pchar
+ * pchar = unreserved / pct-encoded / sub-delims / ":" / "@"
+ * pct-encoded = "%" HEXDIG HEXDIG
+ * unreserved = ALPHA / DIGIT / "-" / "." / "_" / "~"
+ * sub-delims = "!" / "$" / "&" / "'" / "(" / ")"
+ * / "*" / "+" / "," / ";" / "="
+ */
+function encodeUriSegment(val) {
+ return encodeUriQuery(val, true).
+ replace(/%26/gi, '&').
+ replace(/%3D/gi, '=').
+ replace(/%2B/gi, '+');
+}
+
+
+/**
+ * This method is intended for encoding *key* or *value* parts of query component. We need a custom
+ * method because encodeURIComponent is too aggressive and encodes stuff that doesn't have to be
+ * encoded per http://tools.ietf.org/html/rfc3986:
+ * query = *( pchar / "/" / "?" )
+ * pchar = unreserved / pct-encoded / sub-delims / ":" / "@"
+ * unreserved = ALPHA / DIGIT / "-" / "." / "_" / "~"
+ * pct-encoded = "%" HEXDIG HEXDIG
+ * sub-delims = "!" / "$" / "&" / "'" / "(" / ")"
+ * / "*" / "+" / "," / ";" / "="
+ */
+function encodeUriQuery(val, pctEncodeSpaces) {
+ return encodeURIComponent(val).
+ replace(/%40/gi, '@').
+ replace(/%3A/gi, ':').
+ replace(/%24/g, '$').
+ replace(/%2C/gi, ',').
+ replace(/%20/g, (pctEncodeSpaces ? '%20' : '+'));
+}
+
+
+/**
+ * @ngdoc directive
+ * @name ng.directive:ngApp
+ *
+ * @element ANY
+ * @param {angular.Module} ngApp an optional application
+ * {@link angular.module module} name to load.
+ *
+ * @description
+ *
+ * Use this directive to auto-bootstrap an application. Only
+ * one directive can be used per HTML document. The directive
+ * designates the root of the application and is typically placed
+ * at the root of the page.
+ *
+ * In the example below if the `ngApp` directive would not be placed
+ * on the `html` element then the document would not be compiled
+ * and the `{{ 1+2 }}` would not be resolved to `3`.
+ *
+ * `ngApp` is the easiest way to bootstrap an application.
+ *
+
+
+ I can add: 1 + 2 = {{ 1+2 }}
+
+
+ *
+ */
+function angularInit(element, bootstrap) {
+ var elements = [element],
+ appElement,
+ module,
+ names = ['ng:app', 'ng-app', 'x-ng-app', 'data-ng-app'],
+ NG_APP_CLASS_REGEXP = /\sng[:\-]app(:\s*([\w\d_]+);?)?\s/;
+
+ function append(element) {
+ element && elements.push(element);
+ }
+
+ forEach(names, function(name) {
+ names[name] = true;
+ append(document.getElementById(name));
+ name = name.replace(':', '\\:');
+ if (element.querySelectorAll) {
+ forEach(element.querySelectorAll('.' + name), append);
+ forEach(element.querySelectorAll('.' + name + '\\:'), append);
+ forEach(element.querySelectorAll('[' + name + ']'), append);
+ }
+ });
+
+ forEach(elements, function(element) {
+ if (!appElement) {
+ var className = ' ' + element.className + ' ';
+ var match = NG_APP_CLASS_REGEXP.exec(className);
+ if (match) {
+ appElement = element;
+ module = (match[2] || '').replace(/\s+/g, ',');
+ } else {
+ forEach(element.attributes, function(attr) {
+ if (!appElement && names[attr.name]) {
+ appElement = element;
+ module = attr.value;
+ }
+ });
+ }
+ }
+ });
+ if (appElement) {
+ bootstrap(appElement, module ? [module] : []);
+ }
+}
+
+/**
+ * @ngdoc function
+ * @name angular.bootstrap
+ * @description
+ * Use this function to manually start up angular application.
+ *
+ * See: {@link guide/bootstrap Bootstrap}
+ *
+ * @param {Element} element DOM element which is the root of angular application.
+ * @param {Array=} modules an array of module declarations. See: {@link angular.module modules}
+ * @returns {AUTO.$injector} Returns the newly created injector for this app.
+ */
+function bootstrap(element, modules) {
+ var resumeBootstrapInternal = function() {
+ element = jqLite(element);
+ modules = modules || [];
+ modules.unshift(['$provide', function($provide) {
+ $provide.value('$rootElement', element);
+ }]);
+ modules.unshift('ng');
+ var injector = createInjector(modules);
+ injector.invoke(['$rootScope', '$rootElement', '$compile', '$injector', '$animator',
+ function(scope, element, compile, injector, animator) {
+ scope.$apply(function() {
+ element.data('$injector', injector);
+ compile(element)(scope);
+ });
+ animator.enabled(true);
+ }]
+ );
+ return injector;
+ };
+
+ var NG_DEFER_BOOTSTRAP = /^NG_DEFER_BOOTSTRAP!/;
+
+ if (window && !NG_DEFER_BOOTSTRAP.test(window.name)) {
+ return resumeBootstrapInternal();
+ }
+
+ window.name = window.name.replace(NG_DEFER_BOOTSTRAP, '');
+ angular.resumeBootstrap = function(extraModules) {
+ forEach(extraModules, function(module) {
+ modules.push(module);
+ });
+ resumeBootstrapInternal();
+ };
+}
+
+var SNAKE_CASE_REGEXP = /[A-Z]/g;
+function snake_case(name, separator){
+ separator = separator || '_';
+ return name.replace(SNAKE_CASE_REGEXP, function(letter, pos) {
+ return (pos ? separator : '') + letter.toLowerCase();
+ });
+}
+
+function bindJQuery() {
+ // bind to jQuery if present;
+ jQuery = window.jQuery;
+ // reset to jQuery or default to us.
+ if (jQuery) {
+ jqLite = jQuery;
+ extend(jQuery.fn, {
+ scope: JQLitePrototype.scope,
+ controller: JQLitePrototype.controller,
+ injector: JQLitePrototype.injector,
+ inheritedData: JQLitePrototype.inheritedData
+ });
+ JQLitePatchJQueryRemove('remove', true);
+ JQLitePatchJQueryRemove('empty');
+ JQLitePatchJQueryRemove('html');
+ } else {
+ jqLite = JQLite;
+ }
+ angular.element = jqLite;
+}
+
+/**
+ * throw error if the argument is falsy.
+ */
+function assertArg(arg, name, reason) {
+ if (!arg) {
+ throw new Error("Argument '" + (name || '?') + "' is " + (reason || "required"));
+ }
+ return arg;
+}
+
+function assertArgFn(arg, name, acceptArrayAnnotation) {
+ if (acceptArrayAnnotation && isArray(arg)) {
+ arg = arg[arg.length - 1];
+ }
+
+ assertArg(isFunction(arg), name, 'not a function, got ' +
+ (arg && typeof arg == 'object' ? arg.constructor.name || 'Object' : typeof arg));
+ return arg;
+}
+
+/**
+ * @ngdoc interface
+ * @name angular.Module
+ * @description
+ *
+ * Interface for configuring angular {@link angular.module modules}.
+ */
+
+function setupModuleLoader(window) {
+
+ function ensure(obj, name, factory) {
+ return obj[name] || (obj[name] = factory());
+ }
+
+ return ensure(ensure(window, 'angular', Object), 'module', function() {
+ /** @type {Object.} */
+ var modules = {};
+
+ /**
+ * @ngdoc function
+ * @name angular.module
+ * @description
+ *
+ * The `angular.module` is a global place for creating and registering Angular modules. All
+ * modules (angular core or 3rd party) that should be available to an application must be
+ * registered using this mechanism.
+ *
+ *
+ * # Module
+ *
+ * A module is a collocation of services, directives, filters, and configuration information. Module
+ * is used to configure the {@link AUTO.$injector $injector}.
+ *
+ *
+ * // Create a new module
+ * var myModule = angular.module('myModule', []);
+ *
+ * // register a new service
+ * myModule.value('appName', 'MyCoolApp');
+ *
+ * // configure existing services inside initialization blocks.
+ * myModule.config(function($locationProvider) {
+ * // Configure existing providers
+ * $locationProvider.hashPrefix('!');
+ * });
+ *
+ *
+ * Then you can create an injector and load your modules like this:
+ *
+ *
+ * var injector = angular.injector(['ng', 'MyModule'])
+ *
+ *
+ * However it's more likely that you'll just use
+ * {@link ng.directive:ngApp ngApp} or
+ * {@link angular.bootstrap} to simplify this process for you.
+ *
+ * @param {!string} name The name of the module to create or retrieve.
+ * @param {Array.=} requires If specified then new module is being created. If unspecified then the
+ * the module is being retrieved for further configuration.
+ * @param {Function} configFn Optional configuration function for the module. Same as
+ * {@link angular.Module#config Module#config()}.
+ * @returns {module} new module with the {@link angular.Module} api.
+ */
+ return function module(name, requires, configFn) {
+ if (requires && modules.hasOwnProperty(name)) {
+ modules[name] = null;
+ }
+ return ensure(modules, name, function() {
+ if (!requires) {
+ throw Error('No module: ' + name);
+ }
+
+ /** @type {!Array.>} */
+ var invokeQueue = [];
+
+ /** @type {!Array.} */
+ var runBlocks = [];
+
+ var config = invokeLater('$injector', 'invoke');
+
+ /** @type {angular.Module} */
+ var moduleInstance = {
+ // Private state
+ _invokeQueue: invokeQueue,
+ _runBlocks: runBlocks,
+
+ /**
+ * @ngdoc property
+ * @name angular.Module#requires
+ * @propertyOf angular.Module
+ * @returns {Array.} List of module names which must be loaded before this module.
+ * @description
+ * Holds the list of modules which the injector will load before the current module is loaded.
+ */
+ requires: requires,
+
+ /**
+ * @ngdoc property
+ * @name angular.Module#name
+ * @propertyOf angular.Module
+ * @returns {string} Name of the module.
+ * @description
+ */
+ name: name,
+
+
+ /**
+ * @ngdoc method
+ * @name angular.Module#provider
+ * @methodOf angular.Module
+ * @param {string} name service name
+ * @param {Function} providerType Construction function for creating new instance of the service.
+ * @description
+ * See {@link AUTO.$provide#provider $provide.provider()}.
+ */
+ provider: invokeLater('$provide', 'provider'),
+
+ /**
+ * @ngdoc method
+ * @name angular.Module#factory
+ * @methodOf angular.Module
+ * @param {string} name service name
+ * @param {Function} providerFunction Function for creating new instance of the service.
+ * @description
+ * See {@link AUTO.$provide#factory $provide.factory()}.
+ */
+ factory: invokeLater('$provide', 'factory'),
+
+ /**
+ * @ngdoc method
+ * @name angular.Module#service
+ * @methodOf angular.Module
+ * @param {string} name service name
+ * @param {Function} constructor A constructor function that will be instantiated.
+ * @description
+ * See {@link AUTO.$provide#service $provide.service()}.
+ */
+ service: invokeLater('$provide', 'service'),
+
+ /**
+ * @ngdoc method
+ * @name angular.Module#value
+ * @methodOf angular.Module
+ * @param {string} name service name
+ * @param {*} object Service instance object.
+ * @description
+ * See {@link AUTO.$provide#value $provide.value()}.
+ */
+ value: invokeLater('$provide', 'value'),
+
+ /**
+ * @ngdoc method
+ * @name angular.Module#constant
+ * @methodOf angular.Module
+ * @param {string} name constant name
+ * @param {*} object Constant value.
+ * @description
+ * Because the constant are fixed, they get applied before other provide methods.
+ * See {@link AUTO.$provide#constant $provide.constant()}.
+ */
+ constant: invokeLater('$provide', 'constant', 'unshift'),
+
+ /**
+ * @ngdoc method
+ * @name angular.Module#animation
+ * @methodOf angular.Module
+ * @param {string} name animation name
+ * @param {Function} animationFactory Factory function for creating new instance of an animation.
+ * @description
+ *
+ * Defines an animation hook that can be later used with {@link ng.directive:ngAnimate ngAnimate}
+ * alongside {@link ng.directive:ngAnimate#Description common ng directives} as well as custom directives.
+ *
+ * module.animation('animation-name', function($inject1, $inject2) {
+ * return {
+ * //this gets called in preparation to setup an animation
+ * setup : function(element) { ... },
+ *
+ * //this gets called once the animation is run
+ * start : function(element, done, memo) { ... }
+ * }
+ * })
+ *
+ *
+ * See {@link ng.$animationProvider#register $animationProvider.register()} and
+ * {@link ng.directive:ngAnimate ngAnimate} for more information.
+ */
+ animation: invokeLater('$animationProvider', 'register'),
+
+ /**
+ * @ngdoc method
+ * @name angular.Module#filter
+ * @methodOf angular.Module
+ * @param {string} name Filter name.
+ * @param {Function} filterFactory Factory function for creating new instance of filter.
+ * @description
+ * See {@link ng.$filterProvider#register $filterProvider.register()}.
+ */
+ filter: invokeLater('$filterProvider', 'register'),
+
+ /**
+ * @ngdoc method
+ * @name angular.Module#controller
+ * @methodOf angular.Module
+ * @param {string} name Controller name.
+ * @param {Function} constructor Controller constructor function.
+ * @description
+ * See {@link ng.$controllerProvider#register $controllerProvider.register()}.
+ */
+ controller: invokeLater('$controllerProvider', 'register'),
+
+ /**
+ * @ngdoc method
+ * @name angular.Module#directive
+ * @methodOf angular.Module
+ * @param {string} name directive name
+ * @param {Function} directiveFactory Factory function for creating new instance of
+ * directives.
+ * @description
+ * See {@link ng.$compileProvider#directive $compileProvider.directive()}.
+ */
+ directive: invokeLater('$compileProvider', 'directive'),
+
+ /**
+ * @ngdoc method
+ * @name angular.Module#config
+ * @methodOf angular.Module
+ * @param {Function} configFn Execute this function on module load. Useful for service
+ * configuration.
+ * @description
+ * Use this method to register work which needs to be performed on module loading.
+ */
+ config: config,
+
+ /**
+ * @ngdoc method
+ * @name angular.Module#run
+ * @methodOf angular.Module
+ * @param {Function} initializationFn Execute this function after injector creation.
+ * Useful for application initialization.
+ * @description
+ * Use this method to register work which should be performed when the injector is done
+ * loading all modules.
+ */
+ run: function(block) {
+ runBlocks.push(block);
+ return this;
+ }
+ };
+
+ if (configFn) {
+ config(configFn);
+ }
+
+ return moduleInstance;
+
+ /**
+ * @param {string} provider
+ * @param {string} method
+ * @param {String=} insertMethod
+ * @returns {angular.Module}
+ */
+ function invokeLater(provider, method, insertMethod) {
+ return function() {
+ invokeQueue[insertMethod || 'push']([provider, method, arguments]);
+ return moduleInstance;
+ }
+ }
+ });
+ };
+ });
+
+}
+
+/**
+ * @ngdoc property
+ * @name angular.version
+ * @description
+ * An object that contains information about the current AngularJS version. This object has the
+ * following properties:
+ *
+ * - `full` – `{string}` – Full version string, such as "0.9.18".
+ * - `major` – `{number}` – Major version number, such as "0".
+ * - `minor` – `{number}` – Minor version number, such as "9".
+ * - `dot` – `{number}` – Dot version number, such as "18".
+ * - `codeName` – `{string}` – Code name of the release, such as "jiggling-armfat".
+ */
+var version = {
+ full: '1.1.5', // all of these placeholder strings will be replaced by grunt's
+ major: 1, // package task
+ minor: 1,
+ dot: 5,
+ codeName: 'triangle-squarification'
+};
+
+
+function publishExternalAPI(angular){
+ extend(angular, {
+ 'bootstrap': bootstrap,
+ 'copy': copy,
+ 'extend': extend,
+ 'equals': equals,
+ 'element': jqLite,
+ 'forEach': forEach,
+ 'injector': createInjector,
+ 'noop':noop,
+ 'bind':bind,
+ 'toJson': toJson,
+ 'fromJson': fromJson,
+ 'identity':identity,
+ 'isUndefined': isUndefined,
+ 'isDefined': isDefined,
+ 'isString': isString,
+ 'isFunction': isFunction,
+ 'isObject': isObject,
+ 'isNumber': isNumber,
+ 'isElement': isElement,
+ 'isArray': isArray,
+ 'version': version,
+ 'isDate': isDate,
+ 'lowercase': lowercase,
+ 'uppercase': uppercase,
+ 'callbacks': {counter: 0},
+ 'noConflict': noConflict
+ });
+
+ angularModule = setupModuleLoader(window);
+ try {
+ angularModule('ngLocale');
+ } catch (e) {
+ angularModule('ngLocale', []).provider('$locale', $LocaleProvider);
+ }
+
+ angularModule('ng', ['ngLocale'], ['$provide',
+ function ngModule($provide) {
+ $provide.provider('$compile', $CompileProvider).
+ directive({
+ a: htmlAnchorDirective,
+ input: inputDirective,
+ textarea: inputDirective,
+ form: formDirective,
+ script: scriptDirective,
+ select: selectDirective,
+ style: styleDirective,
+ option: optionDirective,
+ ngBind: ngBindDirective,
+ ngBindHtmlUnsafe: ngBindHtmlUnsafeDirective,
+ ngBindTemplate: ngBindTemplateDirective,
+ ngClass: ngClassDirective,
+ ngClassEven: ngClassEvenDirective,
+ ngClassOdd: ngClassOddDirective,
+ ngCsp: ngCspDirective,
+ ngCloak: ngCloakDirective,
+ ngController: ngControllerDirective,
+ ngForm: ngFormDirective,
+ ngHide: ngHideDirective,
+ ngIf: ngIfDirective,
+ ngInclude: ngIncludeDirective,
+ ngInit: ngInitDirective,
+ ngNonBindable: ngNonBindableDirective,
+ ngPluralize: ngPluralizeDirective,
+ ngRepeat: ngRepeatDirective,
+ ngShow: ngShowDirective,
+ ngSubmit: ngSubmitDirective,
+ ngStyle: ngStyleDirective,
+ ngSwitch: ngSwitchDirective,
+ ngSwitchWhen: ngSwitchWhenDirective,
+ ngSwitchDefault: ngSwitchDefaultDirective,
+ ngOptions: ngOptionsDirective,
+ ngView: ngViewDirective,
+ ngTransclude: ngTranscludeDirective,
+ ngModel: ngModelDirective,
+ ngList: ngListDirective,
+ ngChange: ngChangeDirective,
+ required: requiredDirective,
+ ngRequired: requiredDirective,
+ ngValue: ngValueDirective
+ }).
+ directive(ngAttributeAliasDirectives).
+ directive(ngEventDirectives);
+ $provide.provider({
+ $anchorScroll: $AnchorScrollProvider,
+ $animation: $AnimationProvider,
+ $animator: $AnimatorProvider,
+ $browser: $BrowserProvider,
+ $cacheFactory: $CacheFactoryProvider,
+ $controller: $ControllerProvider,
+ $document: $DocumentProvider,
+ $exceptionHandler: $ExceptionHandlerProvider,
+ $filter: $FilterProvider,
+ $interpolate: $InterpolateProvider,
+ $http: $HttpProvider,
+ $httpBackend: $HttpBackendProvider,
+ $location: $LocationProvider,
+ $log: $LogProvider,
+ $parse: $ParseProvider,
+ $route: $RouteProvider,
+ $routeParams: $RouteParamsProvider,
+ $rootScope: $RootScopeProvider,
+ $q: $QProvider,
+ $sniffer: $SnifferProvider,
+ $templateCache: $TemplateCacheProvider,
+ $timeout: $TimeoutProvider,
+ $window: $WindowProvider
+ });
+ }
+ ]);
+}
+
+//////////////////////////////////
+//JQLite
+//////////////////////////////////
+
+/**
+ * @ngdoc function
+ * @name angular.element
+ * @function
+ *
+ * @description
+ * Wraps a raw DOM element or HTML string as a [jQuery](http://jquery.com) element.
+ * `angular.element` can be either an alias for [jQuery](http://api.jquery.com/jQuery/) function, if
+ * jQuery is available, or a function that wraps the element or string in Angular's jQuery lite
+ * implementation (commonly referred to as jqLite).
+ *
+ * Real jQuery always takes precedence over jqLite, provided it was loaded before `DOMContentLoaded`
+ * event fired.
+ *
+ * jqLite is a tiny, API-compatible subset of jQuery that allows
+ * Angular to manipulate the DOM. jqLite implements only the most commonly needed functionality
+ * within a very small footprint, so only a subset of the jQuery API - methods, arguments and
+ * invocation styles - are supported.
+ *
+ * Note: All element references in Angular are always wrapped with jQuery or jqLite; they are never
+ * raw DOM references.
+ *
+ * ## Angular's jQuery lite provides the following methods:
+ *
+ * - [addClass()](http://api.jquery.com/addClass/)
+ * - [after()](http://api.jquery.com/after/)
+ * - [append()](http://api.jquery.com/append/)
+ * - [attr()](http://api.jquery.com/attr/)
+ * - [bind()](http://api.jquery.com/bind/) - Does not support namespaces
+ * - [children()](http://api.jquery.com/children/) - Does not support selectors
+ * - [clone()](http://api.jquery.com/clone/)
+ * - [contents()](http://api.jquery.com/contents/)
+ * - [css()](http://api.jquery.com/css/)
+ * - [data()](http://api.jquery.com/data/)
+ * - [eq()](http://api.jquery.com/eq/)
+ * - [find()](http://api.jquery.com/find/) - Limited to lookups by tag name
+ * - [hasClass()](http://api.jquery.com/hasClass/)
+ * - [html()](http://api.jquery.com/html/)
+ * - [next()](http://api.jquery.com/next/) - Does not support selectors
+ * - [parent()](http://api.jquery.com/parent/) - Does not support selectors
+ * - [prepend()](http://api.jquery.com/prepend/)
+ * - [prop()](http://api.jquery.com/prop/)
+ * - [ready()](http://api.jquery.com/ready/)
+ * - [remove()](http://api.jquery.com/remove/)
+ * - [removeAttr()](http://api.jquery.com/removeAttr/)
+ * - [removeClass()](http://api.jquery.com/removeClass/)
+ * - [removeData()](http://api.jquery.com/removeData/)
+ * - [replaceWith()](http://api.jquery.com/replaceWith/)
+ * - [text()](http://api.jquery.com/text/)
+ * - [toggleClass()](http://api.jquery.com/toggleClass/)
+ * - [triggerHandler()](http://api.jquery.com/triggerHandler/) - Passes a dummy event object to handlers.
+ * - [unbind()](http://api.jquery.com/unbind/) - Does not support namespaces
+ * - [val()](http://api.jquery.com/val/)
+ * - [wrap()](http://api.jquery.com/wrap/)
+ *
+ * ## In addition to the above, Angular provides additional methods to both jQuery and jQuery lite:
+ *
+ * - `controller(name)` - retrieves the controller of the current element or its parent. By default
+ * retrieves controller associated with the `ngController` directive. If `name` is provided as
+ * camelCase directive name, then the controller for this directive will be retrieved (e.g.
+ * `'ngModel'`).
+ * - `injector()` - retrieves the injector of the current element or its parent.
+ * - `scope()` - retrieves the {@link api/ng.$rootScope.Scope scope} of the current
+ * element or its parent.
+ * - `inheritedData()` - same as `data()`, but walks up the DOM until a value is found or the top
+ * parent element is reached.
+ *
+ * @param {string|DOMElement} element HTML string or DOMElement to be wrapped into jQuery.
+ * @returns {Object} jQuery object.
+ */
+
+var jqCache = JQLite.cache = {},
+ jqName = JQLite.expando = 'ng-' + new Date().getTime(),
+ jqId = 1,
+ addEventListenerFn = (window.document.addEventListener
+ ? function(element, type, fn) {element.addEventListener(type, fn, false);}
+ : function(element, type, fn) {element.attachEvent('on' + type, fn);}),
+ removeEventListenerFn = (window.document.removeEventListener
+ ? function(element, type, fn) {element.removeEventListener(type, fn, false); }
+ : function(element, type, fn) {element.detachEvent('on' + type, fn); });
+
+function jqNextId() { return ++jqId; }
+
+
+var SPECIAL_CHARS_REGEXP = /([\:\-\_]+(.))/g;
+var MOZ_HACK_REGEXP = /^moz([A-Z])/;
+
+/**
+ * Converts snake_case to camelCase.
+ * Also there is special case for Moz prefix starting with upper case letter.
+ * @param name Name to normalize
+ */
+function camelCase(name) {
+ return name.
+ replace(SPECIAL_CHARS_REGEXP, function(_, separator, letter, offset) {
+ return offset ? letter.toUpperCase() : letter;
+ }).
+ replace(MOZ_HACK_REGEXP, 'Moz$1');
+}
+
+/////////////////////////////////////////////
+// jQuery mutation patch
+//
+// In conjunction with bindJQuery intercepts all jQuery's DOM destruction apis and fires a
+// $destroy event on all DOM nodes being removed.
+//
+/////////////////////////////////////////////
+
+function JQLitePatchJQueryRemove(name, dispatchThis) {
+ var originalJqFn = jQuery.fn[name];
+ originalJqFn = originalJqFn.$original || originalJqFn;
+ removePatch.$original = originalJqFn;
+ jQuery.fn[name] = removePatch;
+
+ function removePatch() {
+ var list = [this],
+ fireEvent = dispatchThis,
+ set, setIndex, setLength,
+ element, childIndex, childLength, children,
+ fns, events;
+
+ while(list.length) {
+ set = list.shift();
+ for(setIndex = 0, setLength = set.length; setIndex < setLength; setIndex++) {
+ element = jqLite(set[setIndex]);
+ if (fireEvent) {
+ element.triggerHandler('$destroy');
+ } else {
+ fireEvent = !fireEvent;
+ }
+ for(childIndex = 0, childLength = (children = element.children()).length;
+ childIndex < childLength;
+ childIndex++) {
+ list.push(jQuery(children[childIndex]));
+ }
+ }
+ }
+ return originalJqFn.apply(this, arguments);
+ }
+}
+
+/////////////////////////////////////////////
+function JQLite(element) {
+ if (element instanceof JQLite) {
+ return element;
+ }
+ if (!(this instanceof JQLite)) {
+ if (isString(element) && element.charAt(0) != '<') {
+ throw Error('selectors not implemented');
+ }
+ return new JQLite(element);
+ }
+
+ if (isString(element)) {
+ var div = document.createElement('div');
+ // Read about the NoScope elements here:
+ // http://msdn.microsoft.com/en-us/library/ms533897(VS.85).aspx
+ div.innerHTML = '
' + element; // IE insanity to make NoScope elements work!
+ div.removeChild(div.firstChild); // remove the superfluous div
+ JQLiteAddNodes(this, div.childNodes);
+ this.remove(); // detach the elements from the temporary DOM div.
+ } else {
+ JQLiteAddNodes(this, element);
+ }
+}
+
+function JQLiteClone(element) {
+ return element.cloneNode(true);
+}
+
+function JQLiteDealoc(element){
+ JQLiteRemoveData(element);
+ for ( var i = 0, children = element.childNodes || []; i < children.length; i++) {
+ JQLiteDealoc(children[i]);
+ }
+}
+
+function JQLiteUnbind(element, type, fn) {
+ var events = JQLiteExpandoStore(element, 'events'),
+ handle = JQLiteExpandoStore(element, 'handle');
+
+ if (!handle) return; //no listeners registered
+
+ if (isUndefined(type)) {
+ forEach(events, function(eventHandler, type) {
+ removeEventListenerFn(element, type, eventHandler);
+ delete events[type];
+ });
+ } else {
+ if (isUndefined(fn)) {
+ removeEventListenerFn(element, type, events[type]);
+ delete events[type];
+ } else {
+ arrayRemove(events[type], fn);
+ }
+ }
+}
+
+function JQLiteRemoveData(element) {
+ var expandoId = element[jqName],
+ expandoStore = jqCache[expandoId];
+
+ if (expandoStore) {
+ if (expandoStore.handle) {
+ expandoStore.events.$destroy && expandoStore.handle({}, '$destroy');
+ JQLiteUnbind(element);
+ }
+ delete jqCache[expandoId];
+ element[jqName] = undefined; // ie does not allow deletion of attributes on elements.
+ }
+}
+
+function JQLiteExpandoStore(element, key, value) {
+ var expandoId = element[jqName],
+ expandoStore = jqCache[expandoId || -1];
+
+ if (isDefined(value)) {
+ if (!expandoStore) {
+ element[jqName] = expandoId = jqNextId();
+ expandoStore = jqCache[expandoId] = {};
+ }
+ expandoStore[key] = value;
+ } else {
+ return expandoStore && expandoStore[key];
+ }
+}
+
+function JQLiteData(element, key, value) {
+ var data = JQLiteExpandoStore(element, 'data'),
+ isSetter = isDefined(value),
+ keyDefined = !isSetter && isDefined(key),
+ isSimpleGetter = keyDefined && !isObject(key);
+
+ if (!data && !isSimpleGetter) {
+ JQLiteExpandoStore(element, 'data', data = {});
+ }
+
+ if (isSetter) {
+ data[key] = value;
+ } else {
+ if (keyDefined) {
+ if (isSimpleGetter) {
+ // don't create data in this case.
+ return data && data[key];
+ } else {
+ extend(data, key);
+ }
+ } else {
+ return data;
+ }
+ }
+}
+
+function JQLiteHasClass(element, selector) {
+ return ((" " + element.className + " ").replace(/[\n\t]/g, " ").
+ indexOf( " " + selector + " " ) > -1);
+}
+
+function JQLiteRemoveClass(element, cssClasses) {
+ if (cssClasses) {
+ forEach(cssClasses.split(' '), function(cssClass) {
+ element.className = trim(
+ (" " + element.className + " ")
+ .replace(/[\n\t]/g, " ")
+ .replace(" " + trim(cssClass) + " ", " ")
+ );
+ });
+ }
+}
+
+function JQLiteAddClass(element, cssClasses) {
+ if (cssClasses) {
+ forEach(cssClasses.split(' '), function(cssClass) {
+ if (!JQLiteHasClass(element, cssClass)) {
+ element.className = trim(element.className + ' ' + trim(cssClass));
+ }
+ });
+ }
+}
+
+function JQLiteAddNodes(root, elements) {
+ if (elements) {
+ elements = (!elements.nodeName && isDefined(elements.length) && !isWindow(elements))
+ ? elements
+ : [ elements ];
+ for(var i=0; i < elements.length; i++) {
+ root.push(elements[i]);
+ }
+ }
+}
+
+function JQLiteController(element, name) {
+ return JQLiteInheritedData(element, '$' + (name || 'ngController' ) + 'Controller');
+}
+
+function JQLiteInheritedData(element, name, value) {
+ element = jqLite(element);
+
+ // if element is the document object work with the html element instead
+ // this makes $(document).scope() possible
+ if(element[0].nodeType == 9) {
+ element = element.find('html');
+ }
+
+ while (element.length) {
+ if (value = element.data(name)) return value;
+ element = element.parent();
+ }
+}
+
+//////////////////////////////////////////
+// Functions which are declared directly.
+//////////////////////////////////////////
+var JQLitePrototype = JQLite.prototype = {
+ ready: function(fn) {
+ var fired = false;
+
+ function trigger() {
+ if (fired) return;
+ fired = true;
+ fn();
+ }
+
+ // check if document already is loaded
+ if (document.readyState === 'complete'){
+ setTimeout(trigger);
+ } else {
+ this.bind('DOMContentLoaded', trigger); // works for modern browsers and IE9
+ // we can not use jqLite since we are not done loading and jQuery could be loaded later.
+ JQLite(window).bind('load', trigger); // fallback to window.onload for others
+ }
+ },
+ toString: function() {
+ var value = [];
+ forEach(this, function(e){ value.push('' + e);});
+ return '[' + value.join(', ') + ']';
+ },
+
+ eq: function(index) {
+ return (index >= 0) ? jqLite(this[index]) : jqLite(this[this.length + index]);
+ },
+
+ length: 0,
+ push: push,
+ sort: [].sort,
+ splice: [].splice
+};
+
+//////////////////////////////////////////
+// Functions iterating getter/setters.
+// these functions return self on setter and
+// value on get.
+//////////////////////////////////////////
+var BOOLEAN_ATTR = {};
+forEach('multiple,selected,checked,disabled,readOnly,required,open'.split(','), function(value) {
+ BOOLEAN_ATTR[lowercase(value)] = value;
+});
+var BOOLEAN_ELEMENTS = {};
+forEach('input,select,option,textarea,button,form,details'.split(','), function(value) {
+ BOOLEAN_ELEMENTS[uppercase(value)] = true;
+});
+
+function getBooleanAttrName(element, name) {
+ // check dom last since we will most likely fail on name
+ var booleanAttr = BOOLEAN_ATTR[name.toLowerCase()];
+
+ // booleanAttr is here twice to minimize DOM access
+ return booleanAttr && BOOLEAN_ELEMENTS[element.nodeName] && booleanAttr;
+}
+
+forEach({
+ data: JQLiteData,
+ inheritedData: JQLiteInheritedData,
+
+ scope: function(element) {
+ return JQLiteInheritedData(element, '$scope');
+ },
+
+ controller: JQLiteController ,
+
+ injector: function(element) {
+ return JQLiteInheritedData(element, '$injector');
+ },
+
+ removeAttr: function(element,name) {
+ element.removeAttribute(name);
+ },
+
+ hasClass: JQLiteHasClass,
+
+ css: function(element, name, value) {
+ name = camelCase(name);
+
+ if (isDefined(value)) {
+ element.style[name] = value;
+ } else {
+ var val;
+
+ if (msie <= 8) {
+ // this is some IE specific weirdness that jQuery 1.6.4 does not sure why
+ val = element.currentStyle && element.currentStyle[name];
+ if (val === '') val = 'auto';
+ }
+
+ val = val || element.style[name];
+
+ if (msie <= 8) {
+ // jquery weirdness :-/
+ val = (val === '') ? undefined : val;
+ }
+
+ return val;
+ }
+ },
+
+ attr: function(element, name, value){
+ var lowercasedName = lowercase(name);
+ if (BOOLEAN_ATTR[lowercasedName]) {
+ if (isDefined(value)) {
+ if (!!value) {
+ element[name] = true;
+ element.setAttribute(name, lowercasedName);
+ } else {
+ element[name] = false;
+ element.removeAttribute(lowercasedName);
+ }
+ } else {
+ return (element[name] ||
+ (element.attributes.getNamedItem(name)|| noop).specified)
+ ? lowercasedName
+ : undefined;
+ }
+ } else if (isDefined(value)) {
+ element.setAttribute(name, value);
+ } else if (element.getAttribute) {
+ // the extra argument "2" is to get the right thing for a.href in IE, see jQuery code
+ // some elements (e.g. Document) don't have get attribute, so return undefined
+ var ret = element.getAttribute(name, 2);
+ // normalize non-existing attributes to undefined (as jQuery)
+ return ret === null ? undefined : ret;
+ }
+ },
+
+ prop: function(element, name, value) {
+ if (isDefined(value)) {
+ element[name] = value;
+ } else {
+ return element[name];
+ }
+ },
+
+ text: extend((msie < 9)
+ ? function(element, value) {
+ if (element.nodeType == 1 /** Element */) {
+ if (isUndefined(value))
+ return element.innerText;
+ element.innerText = value;
+ } else {
+ if (isUndefined(value))
+ return element.nodeValue;
+ element.nodeValue = value;
+ }
+ }
+ : function(element, value) {
+ if (isUndefined(value)) {
+ return element.textContent;
+ }
+ element.textContent = value;
+ }, {$dv:''}),
+
+ val: function(element, value) {
+ if (isUndefined(value)) {
+ return element.value;
+ }
+ element.value = value;
+ },
+
+ html: function(element, value) {
+ if (isUndefined(value)) {
+ return element.innerHTML;
+ }
+ for (var i = 0, childNodes = element.childNodes; i < childNodes.length; i++) {
+ JQLiteDealoc(childNodes[i]);
+ }
+ element.innerHTML = value;
+ }
+}, function(fn, name){
+ /**
+ * Properties: writes return selection, reads return first value
+ */
+ JQLite.prototype[name] = function(arg1, arg2) {
+ var i, key;
+
+ // JQLiteHasClass has only two arguments, but is a getter-only fn, so we need to special-case it
+ // in a way that survives minification.
+ if (((fn.length == 2 && (fn !== JQLiteHasClass && fn !== JQLiteController)) ? arg1 : arg2) === undefined) {
+ if (isObject(arg1)) {
+
+ // we are a write, but the object properties are the key/values
+ for(i=0; i < this.length; i++) {
+ if (fn === JQLiteData) {
+ // data() takes the whole object in jQuery
+ fn(this[i], arg1);
+ } else {
+ for (key in arg1) {
+ fn(this[i], key, arg1[key]);
+ }
+ }
+ }
+ // return self for chaining
+ return this;
+ } else {
+ // we are a read, so read the first child.
+ if (this.length)
+ return fn(this[0], arg1, arg2);
+ }
+ } else {
+ // we are a write, so apply to all children
+ for(i=0; i < this.length; i++) {
+ fn(this[i], arg1, arg2);
+ }
+ // return self for chaining
+ return this;
+ }
+ return fn.$dv;
+ };
+});
+
+function createEventHandler(element, events) {
+ var eventHandler = function (event, type) {
+ if (!event.preventDefault) {
+ event.preventDefault = function() {
+ event.returnValue = false; //ie
+ };
+ }
+
+ if (!event.stopPropagation) {
+ event.stopPropagation = function() {
+ event.cancelBubble = true; //ie
+ };
+ }
+
+ if (!event.target) {
+ event.target = event.srcElement || document;
+ }
+
+ if (isUndefined(event.defaultPrevented)) {
+ var prevent = event.preventDefault;
+ event.preventDefault = function() {
+ event.defaultPrevented = true;
+ prevent.call(event);
+ };
+ event.defaultPrevented = false;
+ }
+
+ event.isDefaultPrevented = function() {
+ return event.defaultPrevented || event.returnValue == false;
+ };
+
+ forEach(events[type || event.type], function(fn) {
+ fn.call(element, event);
+ });
+
+ // Remove monkey-patched methods (IE),
+ // as they would cause memory leaks in IE8.
+ if (msie <= 8) {
+ // IE7/8 does not allow to delete property on native object
+ event.preventDefault = null;
+ event.stopPropagation = null;
+ event.isDefaultPrevented = null;
+ } else {
+ // It shouldn't affect normal browsers (native methods are defined on prototype).
+ delete event.preventDefault;
+ delete event.stopPropagation;
+ delete event.isDefaultPrevented;
+ }
+ };
+ eventHandler.elem = element;
+ return eventHandler;
+}
+
+//////////////////////////////////////////
+// Functions iterating traversal.
+// These functions chain results into a single
+// selector.
+//////////////////////////////////////////
+forEach({
+ removeData: JQLiteRemoveData,
+
+ dealoc: JQLiteDealoc,
+
+ bind: function bindFn(element, type, fn){
+ var events = JQLiteExpandoStore(element, 'events'),
+ handle = JQLiteExpandoStore(element, 'handle');
+
+ if (!events) JQLiteExpandoStore(element, 'events', events = {});
+ if (!handle) JQLiteExpandoStore(element, 'handle', handle = createEventHandler(element, events));
+
+ forEach(type.split(' '), function(type){
+ var eventFns = events[type];
+
+ if (!eventFns) {
+ if (type == 'mouseenter' || type == 'mouseleave') {
+ var contains = document.body.contains || document.body.compareDocumentPosition ?
+ function( a, b ) {
+ var adown = a.nodeType === 9 ? a.documentElement : a,
+ bup = b && b.parentNode;
+ return a === bup || !!( bup && bup.nodeType === 1 && (
+ adown.contains ?
+ adown.contains( bup ) :
+ a.compareDocumentPosition && a.compareDocumentPosition( bup ) & 16
+ ));
+ } :
+ function( a, b ) {
+ if ( b ) {
+ while ( (b = b.parentNode) ) {
+ if ( b === a ) {
+ return true;
+ }
+ }
+ }
+ return false;
+ };
+
+ events[type] = [];
+
+ // Refer to jQuery's implementation of mouseenter & mouseleave
+ // Read about mouseenter and mouseleave:
+ // http://www.quirksmode.org/js/events_mouse.html#link8
+ var eventmap = { mouseleave : "mouseout", mouseenter : "mouseover"}
+ bindFn(element, eventmap[type], function(event) {
+ var ret, target = this, related = event.relatedTarget;
+ // For mousenter/leave call the handler if related is outside the target.
+ // NB: No relatedTarget if the mouse left/entered the browser window
+ if ( !related || (related !== target && !contains(target, related)) ){
+ handle(event, type);
+ }
+
+ });
+
+ } else {
+ addEventListenerFn(element, type, handle);
+ events[type] = [];
+ }
+ eventFns = events[type]
+ }
+ eventFns.push(fn);
+ });
+ },
+
+ unbind: JQLiteUnbind,
+
+ replaceWith: function(element, replaceNode) {
+ var index, parent = element.parentNode;
+ JQLiteDealoc(element);
+ forEach(new JQLite(replaceNode), function(node){
+ if (index) {
+ parent.insertBefore(node, index.nextSibling);
+ } else {
+ parent.replaceChild(node, element);
+ }
+ index = node;
+ });
+ },
+
+ children: function(element) {
+ var children = [];
+ forEach(element.childNodes, function(element){
+ if (element.nodeType === 1)
+ children.push(element);
+ });
+ return children;
+ },
+
+ contents: function(element) {
+ return element.childNodes || [];
+ },
+
+ append: function(element, node) {
+ forEach(new JQLite(node), function(child){
+ if (element.nodeType === 1 || element.nodeType === 11) {
+ element.appendChild(child);
+ }
+ });
+ },
+
+ prepend: function(element, node) {
+ if (element.nodeType === 1) {
+ var index = element.firstChild;
+ forEach(new JQLite(node), function(child){
+ if (index) {
+ element.insertBefore(child, index);
+ } else {
+ element.appendChild(child);
+ index = child;
+ }
+ });
+ }
+ },
+
+ wrap: function(element, wrapNode) {
+ wrapNode = jqLite(wrapNode)[0];
+ var parent = element.parentNode;
+ if (parent) {
+ parent.replaceChild(wrapNode, element);
+ }
+ wrapNode.appendChild(element);
+ },
+
+ remove: function(element) {
+ JQLiteDealoc(element);
+ var parent = element.parentNode;
+ if (parent) parent.removeChild(element);
+ },
+
+ after: function(element, newElement) {
+ var index = element, parent = element.parentNode;
+ forEach(new JQLite(newElement), function(node){
+ parent.insertBefore(node, index.nextSibling);
+ index = node;
+ });
+ },
+
+ addClass: JQLiteAddClass,
+ removeClass: JQLiteRemoveClass,
+
+ toggleClass: function(element, selector, condition) {
+ if (isUndefined(condition)) {
+ condition = !JQLiteHasClass(element, selector);
+ }
+ (condition ? JQLiteAddClass : JQLiteRemoveClass)(element, selector);
+ },
+
+ parent: function(element) {
+ var parent = element.parentNode;
+ return parent && parent.nodeType !== 11 ? parent : null;
+ },
+
+ next: function(element) {
+ if (element.nextElementSibling) {
+ return element.nextElementSibling;
+ }
+
+ // IE8 doesn't have nextElementSibling
+ var elm = element.nextSibling;
+ while (elm != null && elm.nodeType !== 1) {
+ elm = elm.nextSibling;
+ }
+ return elm;
+ },
+
+ find: function(element, selector) {
+ return element.getElementsByTagName(selector);
+ },
+
+ clone: JQLiteClone,
+
+ triggerHandler: function(element, eventName) {
+ var eventFns = (JQLiteExpandoStore(element, 'events') || {})[eventName];
+ var event;
+
+ forEach(eventFns, function(fn) {
+ fn.call(element, {preventDefault: noop});
+ });
+ }
+}, function(fn, name){
+ /**
+ * chaining functions
+ */
+ JQLite.prototype[name] = function(arg1, arg2) {
+ var value;
+ for(var i=0; i < this.length; i++) {
+ if (value == undefined) {
+ value = fn(this[i], arg1, arg2);
+ if (value !== undefined) {
+ // any function which returns a value needs to be wrapped
+ value = jqLite(value);
+ }
+ } else {
+ JQLiteAddNodes(value, fn(this[i], arg1, arg2));
+ }
+ }
+ return value == undefined ? this : value;
+ };
+});
+
+/**
+ * Computes a hash of an 'obj'.
+ * Hash of a:
+ * string is string
+ * number is number as string
+ * object is either result of calling $$hashKey function on the object or uniquely generated id,
+ * that is also assigned to the $$hashKey property of the object.
+ *
+ * @param obj
+ * @returns {string} hash string such that the same input will have the same hash string.
+ * The resulting string key is in 'type:hashKey' format.
+ */
+function hashKey(obj) {
+ var objType = typeof obj,
+ key;
+
+ if (objType == 'object' && obj !== null) {
+ if (typeof (key = obj.$$hashKey) == 'function') {
+ // must invoke on object to keep the right this
+ key = obj.$$hashKey();
+ } else if (key === undefined) {
+ key = obj.$$hashKey = nextUid();
+ }
+ } else {
+ key = obj;
+ }
+
+ return objType + ':' + key;
+}
+
+/**
+ * HashMap which can use objects as keys
+ */
+function HashMap(array){
+ forEach(array, this.put, this);
+}
+HashMap.prototype = {
+ /**
+ * Store key value pair
+ * @param key key to store can be any type
+ * @param value value to store can be any type
+ */
+ put: function(key, value) {
+ this[hashKey(key)] = value;
+ },
+
+ /**
+ * @param key
+ * @returns the value for the key
+ */
+ get: function(key) {
+ return this[hashKey(key)];
+ },
+
+ /**
+ * Remove the key/value pair
+ * @param key
+ */
+ remove: function(key) {
+ var value = this[key = hashKey(key)];
+ delete this[key];
+ return value;
+ }
+};
+
+/**
+ * @ngdoc function
+ * @name angular.injector
+ * @function
+ *
+ * @description
+ * Creates an injector function that can be used for retrieving services as well as for
+ * dependency injection (see {@link guide/di dependency injection}).
+ *
+
+ * @param {Array.} modules A list of module functions or their aliases. See
+ * {@link angular.module}. The `ng` module must be explicitly added.
+ * @returns {function()} Injector function. See {@link AUTO.$injector $injector}.
+ *
+ * @example
+ * Typical usage
+ *
+ * // create an injector
+ * var $injector = angular.injector(['ng']);
+ *
+ * // use the injector to kick off your application
+ * // use the type inference to auto inject arguments, or use implicit injection
+ * $injector.invoke(function($rootScope, $compile, $document){
+ * $compile($document)($rootScope);
+ * $rootScope.$digest();
+ * });
+ *
+ *
+ * # Injection Function Annotation
+ *
+ * JavaScript does not have annotations, and annotations are needed for dependency injection. The
+ * following are all valid ways of annotating function with injection arguments and are equivalent.
+ *
+ *
+ *
+ * ## Inference
+ *
+ * In JavaScript calling `toString()` on a function returns the function definition. The definition can then be
+ * parsed and the function arguments can be extracted. *NOTE:* This does not work with minification, and obfuscation
+ * tools since these tools change the argument names.
+ *
+ * ## `$inject` Annotation
+ * By adding a `$inject` property onto a function the injection parameters can be specified.
+ *
+ * ## Inline
+ * As an array of injection names, where the last item in the array is the function to call.
+ */
+
+/**
+ * @ngdoc method
+ * @name AUTO.$injector#get
+ * @methodOf AUTO.$injector
+ *
+ * @description
+ * Return an instance of the service.
+ *
+ * @param {string} name The name of the instance to retrieve.
+ * @return {*} The instance.
+ */
+
+/**
+ * @ngdoc method
+ * @name AUTO.$injector#invoke
+ * @methodOf AUTO.$injector
+ *
+ * @description
+ * Invoke the method and supply the method arguments from the `$injector`.
+ *
+ * @param {!function} fn The function to invoke. The function arguments come form the function annotation.
+ * @param {Object=} self The `this` for the invoked method.
+ * @param {Object=} locals Optional object. If preset then any argument names are read from this object first, before
+ * the `$injector` is consulted.
+ * @returns {*} the value returned by the invoked `fn` function.
+ */
+
+/**
+ * @ngdoc method
+ * @name AUTO.$injector#has
+ * @methodOf AUTO.$injector
+ *
+ * @description
+ * Allows the user to query if the particular service exist.
+ *
+ * @param {string} Name of the service to query.
+ * @returns {boolean} returns true if injector has given service.
+ */
+
+/**
+ * @ngdoc method
+ * @name AUTO.$injector#instantiate
+ * @methodOf AUTO.$injector
+ * @description
+ * Create a new instance of JS type. The method takes a constructor function invokes the new operator and supplies
+ * all of the arguments to the constructor function as specified by the constructor annotation.
+ *
+ * @param {function} Type Annotated constructor function.
+ * @param {Object=} locals Optional object. If preset then any argument names are read from this object first, before
+ * the `$injector` is consulted.
+ * @returns {Object} new instance of `Type`.
+ */
+
+/**
+ * @ngdoc method
+ * @name AUTO.$injector#annotate
+ * @methodOf AUTO.$injector
+ *
+ * @description
+ * Returns an array of service names which the function is requesting for injection. This API is used by the injector
+ * to determine which services need to be injected into the function when the function is invoked. There are three
+ * ways in which the function can be annotated with the needed dependencies.
+ *
+ * # Argument names
+ *
+ * The simplest form is to extract the dependencies from the arguments of the function. This is done by converting
+ * the function into a string using `toString()` method and extracting the argument names.
+ *
+ * // Given
+ * function MyController($scope, $route) {
+ * // ...
+ * }
+ *
+ * // Then
+ * expect(injector.annotate(MyController)).toEqual(['$scope', '$route']);
+ *
+ *
+ * This method does not work with code minfication / obfuscation. For this reason the following annotation strategies
+ * are supported.
+ *
+ * # The `$inject` property
+ *
+ * If a function has an `$inject` property and its value is an array of strings, then the strings represent names of
+ * services to be injected into the function.
+ *
+ *
+ * # The array notation
+ *
+ * It is often desirable to inline Injected functions and that's when setting the `$inject` property is very
+ * inconvenient. In these situations using the array notation to specify the dependencies in a way that survives
+ * minification is a better choice:
+ *
+ *
+ * // We wish to write this (not minification / obfuscation safe)
+ * injector.invoke(function($compile, $rootScope) {
+ * // ...
+ * });
+ *
+ * // We are forced to write break inlining
+ * var tmpFn = function(obfuscatedCompile, obfuscatedRootScope) {
+ * // ...
+ * };
+ * tmpFn.$inject = ['$compile', '$rootScope'];
+ * injector.invoke(tmpFn);
+ *
+ * // To better support inline function the inline annotation is supported
+ * injector.invoke(['$compile', '$rootScope', function(obfCompile, obfRootScope) {
+ * // ...
+ * }]);
+ *
+ * // Therefore
+ * expect(injector.annotate(
+ * ['$compile', '$rootScope', function(obfus_$compile, obfus_$rootScope) {}])
+ * ).toEqual(['$compile', '$rootScope']);
+ *
+ *
+ * @param {function|Array.} fn Function for which dependent service names need to be retrieved as described
+ * above.
+ *
+ * @returns {Array.} The names of the services which the function requires.
+ */
+
+
+
+
+/**
+ * @ngdoc object
+ * @name AUTO.$provide
+ *
+ * @description
+ *
+ * Use `$provide` to register new providers with the `$injector`. The providers are the factories for the instance.
+ * The providers share the same name as the instance they create with `Provider` suffixed to them.
+ *
+ * A provider is an object with a `$get()` method. The injector calls the `$get` method to create a new instance of
+ * a service. The Provider can have additional methods which would allow for configuration of the provider.
+ *
+ *
+ */
+
+/**
+ * @ngdoc method
+ * @name AUTO.$provide#provider
+ * @methodOf AUTO.$provide
+ * @description
+ *
+ * Register a provider for a service. The providers can be retrieved and can have additional configuration methods.
+ *
+ * @param {string} name The name of the instance. NOTE: the provider will be available under `name + 'Provider'` key.
+ * @param {(Object|function())} provider If the provider is:
+ *
+ * - `Object`: then it should have a `$get` method. The `$get` method will be invoked using
+ * {@link AUTO.$injector#invoke $injector.invoke()} when an instance needs to be created.
+ * - `Constructor`: a new instance of the provider will be created using
+ * {@link AUTO.$injector#instantiate $injector.instantiate()}, then treated as `object`.
+ *
+ * @returns {Object} registered provider instance
+ */
+
+/**
+ * @ngdoc method
+ * @name AUTO.$provide#factory
+ * @methodOf AUTO.$provide
+ * @description
+ *
+ * A short hand for configuring services if only `$get` method is required.
+ *
+ * @param {string} name The name of the instance.
+ * @param {function()} $getFn The $getFn for the instance creation. Internally this is a short hand for
+ * `$provide.provider(name, {$get: $getFn})`.
+ * @returns {Object} registered provider instance
+ */
+
+
+/**
+ * @ngdoc method
+ * @name AUTO.$provide#service
+ * @methodOf AUTO.$provide
+ * @description
+ *
+ * A short hand for registering service of given class.
+ *
+ * @param {string} name The name of the instance.
+ * @param {Function} constructor A class (constructor function) that will be instantiated.
+ * @returns {Object} registered provider instance
+ */
+
+
+/**
+ * @ngdoc method
+ * @name AUTO.$provide#value
+ * @methodOf AUTO.$provide
+ * @description
+ *
+ * A short hand for configuring services if the `$get` method is a constant.
+ *
+ * @param {string} name The name of the instance.
+ * @param {*} value The value.
+ * @returns {Object} registered provider instance
+ */
+
+
+/**
+ * @ngdoc method
+ * @name AUTO.$provide#constant
+ * @methodOf AUTO.$provide
+ * @description
+ *
+ * A constant value, but unlike {@link AUTO.$provide#value value} it can be injected
+ * into configuration function (other modules) and it is not interceptable by
+ * {@link AUTO.$provide#decorator decorator}.
+ *
+ * @param {string} name The name of the constant.
+ * @param {*} value The constant value.
+ * @returns {Object} registered instance
+ */
+
+
+/**
+ * @ngdoc method
+ * @name AUTO.$provide#decorator
+ * @methodOf AUTO.$provide
+ * @description
+ *
+ * Decoration of service, allows the decorator to intercept the service instance creation. The
+ * returned instance may be the original instance, or a new instance which delegates to the
+ * original instance.
+ *
+ * @param {string} name The name of the service to decorate.
+ * @param {function()} decorator This function will be invoked when the service needs to be
+ * instantiated. The function is called using the {@link AUTO.$injector#invoke
+ * injector.invoke} method and is therefore fully injectable. Local injection arguments:
+ *
+ * * `$delegate` - The original service instance, which can be monkey patched, configured,
+ * decorated or delegated to.
+ */
+
+
+function createInjector(modulesToLoad) {
+ var INSTANTIATING = {},
+ providerSuffix = 'Provider',
+ path = [],
+ loadedModules = new HashMap(),
+ providerCache = {
+ $provide: {
+ provider: supportObject(provider),
+ factory: supportObject(factory),
+ service: supportObject(service),
+ value: supportObject(value),
+ constant: supportObject(constant),
+ decorator: decorator
+ }
+ },
+ providerInjector = (providerCache.$injector =
+ createInternalInjector(providerCache, function() {
+ throw Error("Unknown provider: " + path.join(' <- '));
+ })),
+ instanceCache = {},
+ instanceInjector = (instanceCache.$injector =
+ createInternalInjector(instanceCache, function(servicename) {
+ var provider = providerInjector.get(servicename + providerSuffix);
+ return instanceInjector.invoke(provider.$get, provider);
+ }));
+
+
+ forEach(loadModules(modulesToLoad), function(fn) { instanceInjector.invoke(fn || noop); });
+
+ return instanceInjector;
+
+ ////////////////////////////////////
+ // $provider
+ ////////////////////////////////////
+
+ function supportObject(delegate) {
+ return function(key, value) {
+ if (isObject(key)) {
+ forEach(key, reverseParams(delegate));
+ } else {
+ return delegate(key, value);
+ }
+ }
+ }
+
+ function provider(name, provider_) {
+ if (isFunction(provider_) || isArray(provider_)) {
+ provider_ = providerInjector.instantiate(provider_);
+ }
+ if (!provider_.$get) {
+ throw Error('Provider ' + name + ' must define $get factory method.');
+ }
+ return providerCache[name + providerSuffix] = provider_;
+ }
+
+ function factory(name, factoryFn) { return provider(name, { $get: factoryFn }); }
+
+ function service(name, constructor) {
+ return factory(name, ['$injector', function($injector) {
+ return $injector.instantiate(constructor);
+ }]);
+ }
+
+ function value(name, value) { return factory(name, valueFn(value)); }
+
+ function constant(name, value) {
+ providerCache[name] = value;
+ instanceCache[name] = value;
+ }
+
+ function decorator(serviceName, decorFn) {
+ var origProvider = providerInjector.get(serviceName + providerSuffix),
+ orig$get = origProvider.$get;
+
+ origProvider.$get = function() {
+ var origInstance = instanceInjector.invoke(orig$get, origProvider);
+ return instanceInjector.invoke(decorFn, null, {$delegate: origInstance});
+ };
+ }
+
+ ////////////////////////////////////
+ // Module Loading
+ ////////////////////////////////////
+ function loadModules(modulesToLoad){
+ var runBlocks = [];
+ forEach(modulesToLoad, function(module) {
+ if (loadedModules.get(module)) return;
+ loadedModules.put(module, true);
+ if (isString(module)) {
+ var moduleFn = angularModule(module);
+ runBlocks = runBlocks.concat(loadModules(moduleFn.requires)).concat(moduleFn._runBlocks);
+
+ try {
+ for(var invokeQueue = moduleFn._invokeQueue, i = 0, ii = invokeQueue.length; i < ii; i++) {
+ var invokeArgs = invokeQueue[i],
+ provider = providerInjector.get(invokeArgs[0]);
+
+ provider[invokeArgs[1]].apply(provider, invokeArgs[2]);
+ }
+ } catch (e) {
+ if (e.message) e.message += ' from ' + module;
+ throw e;
+ }
+ } else if (isFunction(module)) {
+ try {
+ runBlocks.push(providerInjector.invoke(module));
+ } catch (e) {
+ if (e.message) e.message += ' from ' + module;
+ throw e;
+ }
+ } else if (isArray(module)) {
+ try {
+ runBlocks.push(providerInjector.invoke(module));
+ } catch (e) {
+ if (e.message) e.message += ' from ' + String(module[module.length - 1]);
+ throw e;
+ }
+ } else {
+ assertArgFn(module, 'module');
+ }
+ });
+ return runBlocks;
+ }
+
+ ////////////////////////////////////
+ // internal Injector
+ ////////////////////////////////////
+
+ function createInternalInjector(cache, factory) {
+
+ function getService(serviceName) {
+ if (typeof serviceName !== 'string') {
+ throw Error('Service name expected');
+ }
+ if (cache.hasOwnProperty(serviceName)) {
+ if (cache[serviceName] === INSTANTIATING) {
+ throw Error('Circular dependency: ' + path.join(' <- '));
+ }
+ return cache[serviceName];
+ } else {
+ try {
+ path.unshift(serviceName);
+ cache[serviceName] = INSTANTIATING;
+ return cache[serviceName] = factory(serviceName);
+ } finally {
+ path.shift();
+ }
+ }
+ }
+
+ function invoke(fn, self, locals){
+ var args = [],
+ $inject = annotate(fn),
+ length, i,
+ key;
+
+ for(i = 0, length = $inject.length; i < length; i++) {
+ key = $inject[i];
+ args.push(
+ locals && locals.hasOwnProperty(key)
+ ? locals[key]
+ : getService(key)
+ );
+ }
+ if (!fn.$inject) {
+ // this means that we must be an array.
+ fn = fn[length];
+ }
+
+
+ // Performance optimization: http://jsperf.com/apply-vs-call-vs-invoke
+ switch (self ? -1 : args.length) {
+ case 0: return fn();
+ case 1: return fn(args[0]);
+ case 2: return fn(args[0], args[1]);
+ case 3: return fn(args[0], args[1], args[2]);
+ case 4: return fn(args[0], args[1], args[2], args[3]);
+ case 5: return fn(args[0], args[1], args[2], args[3], args[4]);
+ case 6: return fn(args[0], args[1], args[2], args[3], args[4], args[5]);
+ case 7: return fn(args[0], args[1], args[2], args[3], args[4], args[5], args[6]);
+ case 8: return fn(args[0], args[1], args[2], args[3], args[4], args[5], args[6], args[7]);
+ case 9: return fn(args[0], args[1], args[2], args[3], args[4], args[5], args[6], args[7], args[8]);
+ case 10: return fn(args[0], args[1], args[2], args[3], args[4], args[5], args[6], args[7], args[8], args[9]);
+ default: return fn.apply(self, args);
+ }
+ }
+
+ function instantiate(Type, locals) {
+ var Constructor = function() {},
+ instance, returnedValue;
+
+ // Check if Type is annotated and use just the given function at n-1 as parameter
+ // e.g. someModule.factory('greeter', ['$window', function(renamed$window) {}]);
+ Constructor.prototype = (isArray(Type) ? Type[Type.length - 1] : Type).prototype;
+ instance = new Constructor();
+ returnedValue = invoke(Type, instance, locals);
+
+ return isObject(returnedValue) ? returnedValue : instance;
+ }
+
+ return {
+ invoke: invoke,
+ instantiate: instantiate,
+ get: getService,
+ annotate: annotate,
+ has: function(name) {
+ return providerCache.hasOwnProperty(name + providerSuffix) || cache.hasOwnProperty(name);
+ }
+ };
+ }
+}
+
+/**
+ * @ngdoc function
+ * @name ng.$anchorScroll
+ * @requires $window
+ * @requires $location
+ * @requires $rootScope
+ *
+ * @description
+ * When called, it checks current value of `$location.hash()` and scroll to related element,
+ * according to rules specified in
+ * {@link http://dev.w3.org/html5/spec/Overview.html#the-indicated-part-of-the-document Html5 spec}.
+ *
+ * It also watches the `$location.hash()` and scroll whenever it changes to match any anchor.
+ * This can be disabled by calling `$anchorScrollProvider.disableAutoScrolling()`.
+ */
+function $AnchorScrollProvider() {
+
+ var autoScrollingEnabled = true;
+
+ this.disableAutoScrolling = function() {
+ autoScrollingEnabled = false;
+ };
+
+ this.$get = ['$window', '$location', '$rootScope', function($window, $location, $rootScope) {
+ var document = $window.document;
+
+ // helper function to get first anchor from a NodeList
+ // can't use filter.filter, as it accepts only instances of Array
+ // and IE can't convert NodeList to an array using [].slice
+ // TODO(vojta): use filter if we change it to accept lists as well
+ function getFirstAnchor(list) {
+ var result = null;
+ forEach(list, function(element) {
+ if (!result && lowercase(element.nodeName) === 'a') result = element;
+ });
+ return result;
+ }
+
+ function scroll() {
+ var hash = $location.hash(), elm;
+
+ // empty hash, scroll to the top of the page
+ if (!hash) $window.scrollTo(0, 0);
+
+ // element with given id
+ else if ((elm = document.getElementById(hash))) elm.scrollIntoView();
+
+ // first anchor with given name :-D
+ else if ((elm = getFirstAnchor(document.getElementsByName(hash)))) elm.scrollIntoView();
+
+ // no element and hash == 'top', scroll to the top of the page
+ else if (hash === 'top') $window.scrollTo(0, 0);
+ }
+
+ // does not scroll when user clicks on anchor link that is currently on
+ // (no url change, no $location.hash() change), browser native does scroll
+ if (autoScrollingEnabled) {
+ $rootScope.$watch(function autoScrollWatch() {return $location.hash();},
+ function autoScrollWatchAction() {
+ $rootScope.$evalAsync(scroll);
+ });
+ }
+
+ return scroll;
+ }];
+}
+
+
+/**
+ * @ngdoc object
+ * @name ng.$animationProvider
+ * @description
+ *
+ * The $AnimationProvider provider allows developers to register and access custom JavaScript animations directly inside
+ * of a module.
+ *
+ */
+$AnimationProvider.$inject = ['$provide'];
+function $AnimationProvider($provide) {
+ var suffix = 'Animation';
+
+ /**
+ * @ngdoc function
+ * @name ng.$animation#register
+ * @methodOf ng.$animationProvider
+ *
+ * @description
+ * Registers a new injectable animation factory function. The factory function produces the animation object which
+ * has these two properties:
+ *
+ * * `setup`: `function(Element):*` A function which receives the starting state of the element. The purpose
+ * of this function is to get the element ready for animation. Optionally the function returns an memento which
+ * is passed to the `start` function.
+ * * `start`: `function(Element, doneFunction, *)` The element to animate, the `doneFunction` to be called on
+ * element animation completion, and an optional memento from the `setup` function.
+ *
+ * @param {string} name The name of the animation.
+ * @param {function} factory The factory function that will be executed to return the animation object.
+ *
+ */
+ this.register = function(name, factory) {
+ $provide.factory(camelCase(name) + suffix, factory);
+ };
+
+ this.$get = ['$injector', function($injector) {
+ /**
+ * @ngdoc function
+ * @name ng.$animation
+ * @function
+ *
+ * @description
+ * The $animation service is used to retrieve any defined animation functions. When executed, the $animation service
+ * will return a object that contains the setup and start functions that were defined for the animation.
+ *
+ * @param {String} name Name of the animation function to retrieve. Animation functions are registered and stored
+ * inside of the AngularJS DI so a call to $animate('custom') is the same as injecting `customAnimation`
+ * via dependency injection.
+ * @return {Object} the animation object which contains the `setup` and `start` functions that perform the animation.
+ */
+ return function $animation(name) {
+ if (name) {
+ var animationName = camelCase(name) + suffix;
+ if ($injector.has(animationName)) {
+ return $injector.get(animationName);
+ }
+ }
+ };
+ }];
+}
+
+// NOTE: this is a pseudo directive.
+
+/**
+ * @ngdoc directive
+ * @name ng.directive:ngAnimate
+ *
+ * @description
+ * The `ngAnimate` directive works as an attribute that is attached alongside pre-existing directives.
+ * It effects how the directive will perform DOM manipulation. This allows for complex animations to take place
+ * without burdening the directive which uses the animation with animation details. The built in directives
+ * `ngRepeat`, `ngInclude`, `ngSwitch`, `ngShow`, `ngHide` and `ngView` already accept `ngAnimate` directive.
+ * Custom directives can take advantage of animation through {@link ng.$animator $animator service}.
+ *
+ * Below is a more detailed breakdown of the supported callback events provided by pre-exisitng ng directives:
+ *
+ * | Directive | Supported Animations |
+ * |========================================================== |====================================================|
+ * | {@link ng.directive:ngRepeat#animations ngRepeat} | enter, leave and move |
+ * | {@link ng.directive:ngView#animations ngView} | enter and leave |
+ * | {@link ng.directive:ngInclude#animations ngInclude} | enter and leave |
+ * | {@link ng.directive:ngSwitch#animations ngSwitch} | enter and leave |
+ * | {@link ng.directive:ngIf#animations ngIf} | enter and leave |
+ * | {@link ng.directive:ngShow#animations ngShow & ngHide} | show and hide |
+ *
+ * You can find out more information about animations upon visiting each directive page.
+ *
+ * Below is an example of a directive that makes use of the ngAnimate attribute:
+ *
+ *
+ *
+ *
+ *
+ *
+ *
+ *
+ *
+ *
+ *
+ *
+ *
+ *
+ * The `event1` and `event2` attributes refer to the animation events specific to the directive that has been assigned.
+ *
+ * Keep in mind that if an animation is running, no child element of such animation can also be animated.
+ *
+ *
CSS-defined Animations
+ * By default, ngAnimate attaches two CSS classes per animation event to the DOM element to achieve the animation.
+ * It is up to you, the developer, to ensure that the animations take place using cross-browser CSS3 transitions as
+ * well as CSS animations.
+ *
+ * The following code below demonstrates how to perform animations using **CSS transitions** with ngAnimate:
+ *
+ *
+ *
+ *
+ *
+ *
+ *
+ * The following code below demonstrates how to perform animations using **CSS animations** with ngAnimate:
+ *
+ *
+ *
+ *
+ *
+ *
+ *
+ * ngAnimate will first examine any CSS animation code and then fallback to using CSS transitions.
+ *
+ * Upon DOM mutation, the event class is added first, then the browser is allowed to reflow the content and then,
+ * the active class is added to trigger the animation. The ngAnimate directive will automatically extract the duration
+ * of the animation to determine when the animation ends. Once the animation is over then both CSS classes will be
+ * removed from the DOM. If a browser does not support CSS transitions or CSS animations then the animation will start and end
+ * immediately resulting in a DOM element that is at it's final state. This final state is when the DOM element
+ * has no CSS transition/animation classes surrounding it.
+ *
+ *
JavaScript-defined Animations
+ * In the event that you do not want to use CSS3 transitions or CSS3 animations or if you wish to offer animations to browsers that do not
+ * yet support them, then you can make use of JavaScript animations defined inside of your AngularJS module.
+ *
+ *
+ * var ngModule = angular.module('YourApp', []);
+ * ngModule.animation('animate-enter', function() {
+ * return {
+ * setup : function(element) {
+ * //prepare the element for animation
+ * element.css({ 'opacity': 0 });
+ * var memo = "..."; //this value is passed to the start function
+ * return memo;
+ * },
+ * start : function(element, done, memo) {
+ * //start the animation
+ * element.animate({
+ * 'opacity' : 1
+ * }, function() {
+ * //call when the animation is complete
+ * done()
+ * });
+ * }
+ * }
+ * });
+ *
+ *
+ * As you can see, the JavaScript code follows a similar template to the CSS3 animations. Once defined, the animation
+ * can be used in the same way with the ngAnimate attribute. Keep in mind that, when using JavaScript-enabled
+ * animations, ngAnimate will also add in the same CSS classes that CSS-enabled animations do (even if you're not using
+ * CSS animations) to animated the element, but it will not attempt to find any CSS3 transition or animation duration/delay values.
+ * It will instead close off the animation once the provided done function is executed. So it's important that you
+ * make sure your animations remember to fire off the done function once the animations are complete.
+ *
+ * @param {expression} ngAnimate Used to configure the DOM manipulation animations.
+ *
+ */
+
+var $AnimatorProvider = function() {
+ var NG_ANIMATE_CONTROLLER = '$ngAnimateController';
+ var rootAnimateController = {running:true};
+
+ this.$get = ['$animation', '$window', '$sniffer', '$rootElement', '$rootScope',
+ function($animation, $window, $sniffer, $rootElement, $rootScope) {
+ $rootElement.data(NG_ANIMATE_CONTROLLER, rootAnimateController);
+
+ /**
+ * @ngdoc function
+ * @name ng.$animator
+ * @function
+ *
+ * @description
+ * The $animator.create service provides the DOM manipulation API which is decorated with animations.
+ *
+ * @param {Scope} scope the scope for the ng-animate.
+ * @param {Attributes} attr the attributes object which contains the ngAnimate key / value pair. (The attributes are
+ * passed into the linking function of the directive using the `$animator`.)
+ * @return {object} the animator object which contains the enter, leave, move, show, hide and animate methods.
+ */
+ var AnimatorService = function(scope, attrs) {
+ var animator = {};
+
+ /**
+ * @ngdoc function
+ * @name ng.animator#enter
+ * @methodOf ng.$animator
+ * @function
+ *
+ * @description
+ * Injects the element object into the DOM (inside of the parent element) and then runs the enter animation.
+ *
+ * @param {jQuery/jqLite element} element the element that will be the focus of the enter animation
+ * @param {jQuery/jqLite element} parent the parent element of the element that will be the focus of the enter animation
+ * @param {jQuery/jqLite element} after the sibling element (which is the previous element) of the element that will be the focus of the enter animation
+ */
+ animator.enter = animateActionFactory('enter', insert, noop);
+
+ /**
+ * @ngdoc function
+ * @name ng.animator#leave
+ * @methodOf ng.$animator
+ * @function
+ *
+ * @description
+ * Runs the leave animation operation and, upon completion, removes the element from the DOM.
+ *
+ * @param {jQuery/jqLite element} element the element that will be the focus of the leave animation
+ * @param {jQuery/jqLite element} parent the parent element of the element that will be the focus of the leave animation
+ */
+ animator.leave = animateActionFactory('leave', noop, remove);
+
+ /**
+ * @ngdoc function
+ * @name ng.animator#move
+ * @methodOf ng.$animator
+ * @function
+ *
+ * @description
+ * Fires the move DOM operation. Just before the animation starts, the animator will either append it into the parent container or
+ * add the element directly after the after element if present. Then the move animation will be run.
+ *
+ * @param {jQuery/jqLite element} element the element that will be the focus of the move animation
+ * @param {jQuery/jqLite element} parent the parent element of the element that will be the focus of the move animation
+ * @param {jQuery/jqLite element} after the sibling element (which is the previous element) of the element that will be the focus of the move animation
+ */
+ animator.move = animateActionFactory('move', move, noop);
+
+ /**
+ * @ngdoc function
+ * @name ng.animator#show
+ * @methodOf ng.$animator
+ * @function
+ *
+ * @description
+ * Reveals the element by setting the CSS property `display` to `block` and then starts the show animation directly after.
+ *
+ * @param {jQuery/jqLite element} element the element that will be rendered visible or hidden
+ */
+ animator.show = animateActionFactory('show', show, noop);
+
+ /**
+ * @ngdoc function
+ * @name ng.animator#hide
+ * @methodOf ng.$animator
+ *
+ * @description
+ * Starts the hide animation first and sets the CSS `display` property to `none` upon completion.
+ *
+ * @param {jQuery/jqLite element} element the element that will be rendered visible or hidden
+ */
+ animator.hide = animateActionFactory('hide', noop, hide);
+
+ /**
+ * @ngdoc function
+ * @name ng.animator#animate
+ * @methodOf ng.$animator
+ *
+ * @description
+ * Triggers a custom animation event to be executed on the given element
+ *
+ * @param {jQuery/jqLite element} element that will be animated
+ */
+ animator.animate = function(event, element) {
+ animateActionFactory(event, noop, noop)(element);
+ }
+ return animator;
+
+ function animateActionFactory(type, beforeFn, afterFn) {
+ return function(element, parent, after) {
+ var ngAnimateValue = scope.$eval(attrs.ngAnimate);
+ var className = ngAnimateValue
+ ? isObject(ngAnimateValue) ? ngAnimateValue[type] : ngAnimateValue + '-' + type
+ : '';
+ var animationPolyfill = $animation(className);
+ var polyfillSetup = animationPolyfill && animationPolyfill.setup;
+ var polyfillStart = animationPolyfill && animationPolyfill.start;
+ var polyfillCancel = animationPolyfill && animationPolyfill.cancel;
+
+ if (!className) {
+ beforeFn(element, parent, after);
+ afterFn(element, parent, after);
+ } else {
+ var activeClassName = className + '-active';
+
+ if (!parent) {
+ parent = after ? after.parent() : element.parent();
+ }
+ if ((!$sniffer.transitions && !polyfillSetup && !polyfillStart) ||
+ (parent.inheritedData(NG_ANIMATE_CONTROLLER) || noop).running) {
+ beforeFn(element, parent, after);
+ afterFn(element, parent, after);
+ return;
+ }
+
+ var animationData = element.data(NG_ANIMATE_CONTROLLER) || {};
+ if(animationData.running) {
+ (polyfillCancel || noop)(element);
+ animationData.done();
+ }
+
+ element.data(NG_ANIMATE_CONTROLLER, {running:true, done:done});
+ element.addClass(className);
+ beforeFn(element, parent, after);
+ if (element.length == 0) return done();
+
+ var memento = (polyfillSetup || noop)(element);
+
+ // $window.setTimeout(beginAnimation, 0); this was causing the element not to animate
+ // keep at 1 for animation dom rerender
+ $window.setTimeout(beginAnimation, 1);
+ }
+
+ function parseMaxTime(str) {
+ var total = 0, values = isString(str) ? str.split(/\s*,\s*/) : [];
+ forEach(values, function(value) {
+ total = Math.max(parseFloat(value) || 0, total);
+ });
+ return total;
+ }
+
+ function beginAnimation() {
+ element.addClass(activeClassName);
+ if (polyfillStart) {
+ polyfillStart(element, done, memento);
+ } else if (isFunction($window.getComputedStyle)) {
+ //one day all browsers will have these properties
+ var w3cAnimationProp = 'animation';
+ var w3cTransitionProp = 'transition';
+
+ //but some still use vendor-prefixed styles
+ var vendorAnimationProp = $sniffer.vendorPrefix + 'Animation';
+ var vendorTransitionProp = $sniffer.vendorPrefix + 'Transition';
+
+ var durationKey = 'Duration',
+ delayKey = 'Delay',
+ animationIterationCountKey = 'IterationCount',
+ duration = 0;
+
+ //we want all the styles defined before and after
+ var ELEMENT_NODE = 1;
+ forEach(element, function(element) {
+ if (element.nodeType == ELEMENT_NODE) {
+ var w3cProp = w3cTransitionProp,
+ vendorProp = vendorTransitionProp,
+ iterations = 1,
+ elementStyles = $window.getComputedStyle(element) || {};
+
+ //use CSS Animations over CSS Transitions
+ if(parseFloat(elementStyles[w3cAnimationProp + durationKey]) > 0 ||
+ parseFloat(elementStyles[vendorAnimationProp + durationKey]) > 0) {
+ w3cProp = w3cAnimationProp;
+ vendorProp = vendorAnimationProp;
+ iterations = Math.max(parseInt(elementStyles[w3cProp + animationIterationCountKey]) || 0,
+ parseInt(elementStyles[vendorProp + animationIterationCountKey]) || 0,
+ iterations);
+ }
+
+ var parsedDelay = Math.max(parseMaxTime(elementStyles[w3cProp + delayKey]),
+ parseMaxTime(elementStyles[vendorProp + delayKey]));
+
+ var parsedDuration = Math.max(parseMaxTime(elementStyles[w3cProp + durationKey]),
+ parseMaxTime(elementStyles[vendorProp + durationKey]));
+
+ duration = Math.max(parsedDelay + (iterations * parsedDuration), duration);
+ }
+ });
+ $window.setTimeout(done, duration * 1000);
+ } else {
+ done();
+ }
+ }
+
+ function done() {
+ if(!done.run) {
+ done.run = true;
+ afterFn(element, parent, after);
+ element.removeClass(className);
+ element.removeClass(activeClassName);
+ element.removeData(NG_ANIMATE_CONTROLLER);
+ }
+ }
+ };
+ }
+
+ function show(element) {
+ element.css('display', '');
+ }
+
+ function hide(element) {
+ element.css('display', 'none');
+ }
+
+ function insert(element, parent, after) {
+ if (after) {
+ after.after(element);
+ } else {
+ parent.append(element);
+ }
+ }
+
+ function remove(element) {
+ element.remove();
+ }
+
+ function move(element, parent, after) {
+ // Do not remove element before insert. Removing will cause data associated with the
+ // element to be dropped. Insert will implicitly do the remove.
+ insert(element, parent, after);
+ }
+ };
+
+ /**
+ * @ngdoc function
+ * @name ng.animator#enabled
+ * @methodOf ng.$animator
+ * @function
+ *
+ * @param {Boolean=} If provided then set the animation on or off.
+ * @return {Boolean} Current animation state.
+ *
+ * @description
+ * Globally enables/disables animations.
+ *
+ */
+ AnimatorService.enabled = function(value) {
+ if (arguments.length) {
+ rootAnimateController.running = !value;
+ }
+ return !rootAnimateController.running;
+ };
+
+ return AnimatorService;
+ }];
+};
+
+/**
+ * ! This is a private undocumented service !
+ *
+ * @name ng.$browser
+ * @requires $log
+ * @description
+ * This object has two goals:
+ *
+ * - hide all the global state in the browser caused by the window object
+ * - abstract away all the browser specific features and inconsistencies
+ *
+ * For tests we provide {@link ngMock.$browser mock implementation} of the `$browser`
+ * service, which can be used for convenient testing of the application without the interaction with
+ * the real browser apis.
+ */
+/**
+ * @param {object} window The global window object.
+ * @param {object} document jQuery wrapped document.
+ * @param {function()} XHR XMLHttpRequest constructor.
+ * @param {object} $log console.log or an object with the same interface.
+ * @param {object} $sniffer $sniffer service
+ */
+function Browser(window, document, $log, $sniffer) {
+ var self = this,
+ rawDocument = document[0],
+ location = window.location,
+ history = window.history,
+ setTimeout = window.setTimeout,
+ clearTimeout = window.clearTimeout,
+ pendingDeferIds = {};
+
+ self.isMock = false;
+
+ var outstandingRequestCount = 0;
+ var outstandingRequestCallbacks = [];
+
+ // TODO(vojta): remove this temporary api
+ self.$$completeOutstandingRequest = completeOutstandingRequest;
+ self.$$incOutstandingRequestCount = function() { outstandingRequestCount++; };
+
+ /**
+ * Executes the `fn` function(supports currying) and decrements the `outstandingRequestCallbacks`
+ * counter. If the counter reaches 0, all the `outstandingRequestCallbacks` are executed.
+ */
+ function completeOutstandingRequest(fn) {
+ try {
+ fn.apply(null, sliceArgs(arguments, 1));
+ } finally {
+ outstandingRequestCount--;
+ if (outstandingRequestCount === 0) {
+ while(outstandingRequestCallbacks.length) {
+ try {
+ outstandingRequestCallbacks.pop()();
+ } catch (e) {
+ $log.error(e);
+ }
+ }
+ }
+ }
+ }
+
+ /**
+ * @private
+ * Note: this method is used only by scenario runner
+ * TODO(vojta): prefix this method with $$ ?
+ * @param {function()} callback Function that will be called when no outstanding request
+ */
+ self.notifyWhenNoOutstandingRequests = function(callback) {
+ // force browser to execute all pollFns - this is needed so that cookies and other pollers fire
+ // at some deterministic time in respect to the test runner's actions. Leaving things up to the
+ // regular poller would result in flaky tests.
+ forEach(pollFns, function(pollFn){ pollFn(); });
+
+ if (outstandingRequestCount === 0) {
+ callback();
+ } else {
+ outstandingRequestCallbacks.push(callback);
+ }
+ };
+
+ //////////////////////////////////////////////////////////////
+ // Poll Watcher API
+ //////////////////////////////////////////////////////////////
+ var pollFns = [],
+ pollTimeout;
+
+ /**
+ * @name ng.$browser#addPollFn
+ * @methodOf ng.$browser
+ *
+ * @param {function()} fn Poll function to add
+ *
+ * @description
+ * Adds a function to the list of functions that poller periodically executes,
+ * and starts polling if not started yet.
+ *
+ * @returns {function()} the added function
+ */
+ self.addPollFn = function(fn) {
+ if (isUndefined(pollTimeout)) startPoller(100, setTimeout);
+ pollFns.push(fn);
+ return fn;
+ };
+
+ /**
+ * @param {number} interval How often should browser call poll functions (ms)
+ * @param {function()} setTimeout Reference to a real or fake `setTimeout` function.
+ *
+ * @description
+ * Configures the poller to run in the specified intervals, using the specified
+ * setTimeout fn and kicks it off.
+ */
+ function startPoller(interval, setTimeout) {
+ (function check() {
+ forEach(pollFns, function(pollFn){ pollFn(); });
+ pollTimeout = setTimeout(check, interval);
+ })();
+ }
+
+ //////////////////////////////////////////////////////////////
+ // URL API
+ //////////////////////////////////////////////////////////////
+
+ var lastBrowserUrl = location.href,
+ baseElement = document.find('base');
+
+ /**
+ * @name ng.$browser#url
+ * @methodOf ng.$browser
+ *
+ * @description
+ * GETTER:
+ * Without any argument, this method just returns current value of location.href.
+ *
+ * SETTER:
+ * With at least one argument, this method sets url to new value.
+ * If html5 history api supported, pushState/replaceState is used, otherwise
+ * location.href/location.replace is used.
+ * Returns its own instance to allow chaining
+ *
+ * NOTE: this api is intended for use only by the $location service. Please use the
+ * {@link ng.$location $location service} to change url.
+ *
+ * @param {string} url New url (when used as setter)
+ * @param {boolean=} replace Should new url replace current history record ?
+ */
+ self.url = function(url, replace) {
+ // setter
+ if (url) {
+ if (lastBrowserUrl == url) return;
+ lastBrowserUrl = url;
+ if ($sniffer.history) {
+ if (replace) history.replaceState(null, '', url);
+ else {
+ history.pushState(null, '', url);
+ // Crazy Opera Bug: http://my.opera.com/community/forums/topic.dml?id=1185462
+ baseElement.attr('href', baseElement.attr('href'));
+ }
+ } else {
+ if (replace) location.replace(url);
+ else location.href = url;
+ }
+ return self;
+ // getter
+ } else {
+ // the replacement is a workaround for https://bugzilla.mozilla.org/show_bug.cgi?id=407172
+ return location.href.replace(/%27/g,"'");
+ }
+ };
+
+ var urlChangeListeners = [],
+ urlChangeInit = false;
+
+ function fireUrlChange() {
+ if (lastBrowserUrl == self.url()) return;
+
+ lastBrowserUrl = self.url();
+ forEach(urlChangeListeners, function(listener) {
+ listener(self.url());
+ });
+ }
+
+ /**
+ * @name ng.$browser#onUrlChange
+ * @methodOf ng.$browser
+ * @TODO(vojta): refactor to use node's syntax for events
+ *
+ * @description
+ * Register callback function that will be called, when url changes.
+ *
+ * It's only called when the url is changed by outside of angular:
+ * - user types different url into address bar
+ * - user clicks on history (forward/back) button
+ * - user clicks on a link
+ *
+ * It's not called when url is changed by $browser.url() method
+ *
+ * The listener gets called with new url as parameter.
+ *
+ * NOTE: this api is intended for use only by the $location service. Please use the
+ * {@link ng.$location $location service} to monitor url changes in angular apps.
+ *
+ * @param {function(string)} listener Listener function to be called when url changes.
+ * @return {function(string)} Returns the registered listener fn - handy if the fn is anonymous.
+ */
+ self.onUrlChange = function(callback) {
+ if (!urlChangeInit) {
+ // We listen on both (hashchange/popstate) when available, as some browsers (e.g. Opera)
+ // don't fire popstate when user change the address bar and don't fire hashchange when url
+ // changed by push/replaceState
+
+ // html5 history api - popstate event
+ if ($sniffer.history) jqLite(window).bind('popstate', fireUrlChange);
+ // hashchange event
+ if ($sniffer.hashchange) jqLite(window).bind('hashchange', fireUrlChange);
+ // polling
+ else self.addPollFn(fireUrlChange);
+
+ urlChangeInit = true;
+ }
+
+ urlChangeListeners.push(callback);
+ return callback;
+ };
+
+ //////////////////////////////////////////////////////////////
+ // Misc API
+ //////////////////////////////////////////////////////////////
+
+ /**
+ * Returns current
+ * (always relative - without domain)
+ *
+ * @returns {string=}
+ */
+ self.baseHref = function() {
+ var href = baseElement.attr('href');
+ return href ? href.replace(/^https?\:\/\/[^\/]*/, '') : '';
+ };
+
+ //////////////////////////////////////////////////////////////
+ // Cookies API
+ //////////////////////////////////////////////////////////////
+ var lastCookies = {};
+ var lastCookieString = '';
+ var cookiePath = self.baseHref();
+
+ /**
+ * @name ng.$browser#cookies
+ * @methodOf ng.$browser
+ *
+ * @param {string=} name Cookie name
+ * @param {string=} value Cookie value
+ *
+ * @description
+ * The cookies method provides a 'private' low level access to browser cookies.
+ * It is not meant to be used directly, use the $cookie service instead.
+ *
+ * The return values vary depending on the arguments that the method was called with as follows:
+ *
+ *
cookies() -> hash of all cookies, this is NOT a copy of the internal state, so do not modify it
+ *
cookies(name, value) -> set name to value, if value is undefined delete the cookie
+ *
cookies(name) -> the same as (name, undefined) == DELETES (no one calls it right now that way)
+ *
+ *
+ * @returns {Object} Hash of all cookies (if called without any parameter)
+ */
+ self.cookies = function(name, value) {
+ var cookieLength, cookieArray, cookie, i, index;
+
+ if (name) {
+ if (value === undefined) {
+ rawDocument.cookie = escape(name) + "=;path=" + cookiePath + ";expires=Thu, 01 Jan 1970 00:00:00 GMT";
+ } else {
+ if (isString(value)) {
+ cookieLength = (rawDocument.cookie = escape(name) + '=' + escape(value) + ';path=' + cookiePath).length + 1;
+
+ // per http://www.ietf.org/rfc/rfc2109.txt browser must allow at minimum:
+ // - 300 cookies
+ // - 20 cookies per unique domain
+ // - 4096 bytes per cookie
+ if (cookieLength > 4096) {
+ $log.warn("Cookie '"+ name +"' possibly not set or overflowed because it was too large ("+
+ cookieLength + " > 4096 bytes)!");
+ }
+ }
+ }
+ } else {
+ if (rawDocument.cookie !== lastCookieString) {
+ lastCookieString = rawDocument.cookie;
+ cookieArray = lastCookieString.split("; ");
+ lastCookies = {};
+
+ for (i = 0; i < cookieArray.length; i++) {
+ cookie = cookieArray[i];
+ index = cookie.indexOf('=');
+ if (index > 0) { //ignore nameless cookies
+ var name = unescape(cookie.substring(0, index));
+ // the first value that is seen for a cookie is the most
+ // specific one. values for the same cookie name that
+ // follow are for less specific paths.
+ if (lastCookies[name] === undefined) {
+ lastCookies[name] = unescape(cookie.substring(index + 1));
+ }
+ }
+ }
+ }
+ return lastCookies;
+ }
+ };
+
+
+ /**
+ * @name ng.$browser#defer
+ * @methodOf ng.$browser
+ * @param {function()} fn A function, who's execution should be defered.
+ * @param {number=} [delay=0] of milliseconds to defer the function execution.
+ * @returns {*} DeferId that can be used to cancel the task via `$browser.defer.cancel()`.
+ *
+ * @description
+ * Executes a fn asynchronously via `setTimeout(fn, delay)`.
+ *
+ * Unlike when calling `setTimeout` directly, in test this function is mocked and instead of using
+ * `setTimeout` in tests, the fns are queued in an array, which can be programmatically flushed
+ * via `$browser.defer.flush()`.
+ *
+ */
+ self.defer = function(fn, delay) {
+ var timeoutId;
+ outstandingRequestCount++;
+ timeoutId = setTimeout(function() {
+ delete pendingDeferIds[timeoutId];
+ completeOutstandingRequest(fn);
+ }, delay || 0);
+ pendingDeferIds[timeoutId] = true;
+ return timeoutId;
+ };
+
+
+ /**
+ * @name ng.$browser#defer.cancel
+ * @methodOf ng.$browser.defer
+ *
+ * @description
+ * Cancels a defered task identified with `deferId`.
+ *
+ * @param {*} deferId Token returned by the `$browser.defer` function.
+ * @returns {boolean} Returns `true` if the task hasn't executed yet and was successfully canceled.
+ */
+ self.defer.cancel = function(deferId) {
+ if (pendingDeferIds[deferId]) {
+ delete pendingDeferIds[deferId];
+ clearTimeout(deferId);
+ completeOutstandingRequest(noop);
+ return true;
+ }
+ return false;
+ };
+
+}
+
+function $BrowserProvider(){
+ this.$get = ['$window', '$log', '$sniffer', '$document',
+ function( $window, $log, $sniffer, $document){
+ return new Browser($window, $document, $log, $sniffer);
+ }];
+}
+
+/**
+ * @ngdoc object
+ * @name ng.$cacheFactory
+ *
+ * @description
+ * Factory that constructs cache objects.
+ *
+ *
+ * @param {string} cacheId Name or id of the newly created cache.
+ * @param {object=} options Options object that specifies the cache behavior. Properties:
+ *
+ * - `{number=}` `capacity` — turns the cache into LRU cache.
+ *
+ * @returns {object} Newly created cache object with the following set of methods:
+ *
+ * - `{object}` `info()` — Returns id, size, and options of cache.
+ * - `{{*}}` `put({string} key, {*} value)` — Puts a new key-value pair into the cache and returns it.
+ * - `{{*}}` `get({string} key)` — Returns cached value for `key` or undefined for cache miss.
+ * - `{void}` `remove({string} key)` — Removes a key-value pair from the cache.
+ * - `{void}` `removeAll()` — Removes all cached values.
+ * - `{void}` `destroy()` — Removes references to this cache from $cacheFactory.
+ *
+ */
+function $CacheFactoryProvider() {
+
+ this.$get = function() {
+ var caches = {};
+
+ function cacheFactory(cacheId, options) {
+ if (cacheId in caches) {
+ throw Error('cacheId ' + cacheId + ' taken');
+ }
+
+ var size = 0,
+ stats = extend({}, options, {id: cacheId}),
+ data = {},
+ capacity = (options && options.capacity) || Number.MAX_VALUE,
+ lruHash = {},
+ freshEnd = null,
+ staleEnd = null;
+
+ return caches[cacheId] = {
+
+ put: function(key, value) {
+ var lruEntry = lruHash[key] || (lruHash[key] = {key: key});
+
+ refresh(lruEntry);
+
+ if (isUndefined(value)) return;
+ if (!(key in data)) size++;
+ data[key] = value;
+
+ if (size > capacity) {
+ this.remove(staleEnd.key);
+ }
+
+ return value;
+ },
+
+
+ get: function(key) {
+ var lruEntry = lruHash[key];
+
+ if (!lruEntry) return;
+
+ refresh(lruEntry);
+
+ return data[key];
+ },
+
+
+ remove: function(key) {
+ var lruEntry = lruHash[key];
+
+ if (!lruEntry) return;
+
+ if (lruEntry == freshEnd) freshEnd = lruEntry.p;
+ if (lruEntry == staleEnd) staleEnd = lruEntry.n;
+ link(lruEntry.n,lruEntry.p);
+
+ delete lruHash[key];
+ delete data[key];
+ size--;
+ },
+
+
+ removeAll: function() {
+ data = {};
+ size = 0;
+ lruHash = {};
+ freshEnd = staleEnd = null;
+ },
+
+
+ destroy: function() {
+ data = null;
+ stats = null;
+ lruHash = null;
+ delete caches[cacheId];
+ },
+
+
+ info: function() {
+ return extend({}, stats, {size: size});
+ }
+ };
+
+
+ /**
+ * makes the `entry` the freshEnd of the LRU linked list
+ */
+ function refresh(entry) {
+ if (entry != freshEnd) {
+ if (!staleEnd) {
+ staleEnd = entry;
+ } else if (staleEnd == entry) {
+ staleEnd = entry.n;
+ }
+
+ link(entry.n, entry.p);
+ link(entry, freshEnd);
+ freshEnd = entry;
+ freshEnd.n = null;
+ }
+ }
+
+
+ /**
+ * bidirectionally links two entries of the LRU linked list
+ */
+ function link(nextEntry, prevEntry) {
+ if (nextEntry != prevEntry) {
+ if (nextEntry) nextEntry.p = prevEntry; //p stands for previous, 'prev' didn't minify
+ if (prevEntry) prevEntry.n = nextEntry; //n stands for next, 'next' didn't minify
+ }
+ }
+ }
+
+
+ cacheFactory.info = function() {
+ var info = {};
+ forEach(caches, function(cache, cacheId) {
+ info[cacheId] = cache.info();
+ });
+ return info;
+ };
+
+
+ cacheFactory.get = function(cacheId) {
+ return caches[cacheId];
+ };
+
+
+ return cacheFactory;
+ };
+}
+
+/**
+ * @ngdoc object
+ * @name ng.$templateCache
+ *
+ * @description
+ * Cache used for storing html templates.
+ *
+ * See {@link ng.$cacheFactory $cacheFactory}.
+ *
+ */
+function $TemplateCacheProvider() {
+ this.$get = ['$cacheFactory', function($cacheFactory) {
+ return $cacheFactory('templates');
+ }];
+}
+
+/* ! VARIABLE/FUNCTION NAMING CONVENTIONS THAT APPLY TO THIS FILE!
+ *
+ * DOM-related variables:
+ *
+ * - "node" - DOM Node
+ * - "element" - DOM Element or Node
+ * - "$node" or "$element" - jqLite-wrapped node or element
+ *
+ *
+ * Compiler related stuff:
+ *
+ * - "linkFn" - linking fn of a single directive
+ * - "nodeLinkFn" - function that aggregates all linking fns for a particular node
+ * - "childLinkFn" - function that aggregates all linking fns for child nodes of a particular node
+ * - "compositeLinkFn" - function that aggregates all linking fns for a compilation root (nodeList)
+ */
+
+
+var NON_ASSIGNABLE_MODEL_EXPRESSION = 'Non-assignable model expression: ';
+
+
+/**
+ * @ngdoc function
+ * @name ng.$compile
+ * @function
+ *
+ * @description
+ * Compiles a piece of HTML string or DOM into a template and produces a template function, which
+ * can then be used to link {@link ng.$rootScope.Scope scope} and the template together.
+ *
+ * The compilation is a process of walking the DOM tree and trying to match DOM elements to
+ * {@link ng.$compileProvider#directive directives}. For each match it
+ * executes corresponding template function and collects the
+ * instance functions into a single template function which is then returned.
+ *
+ * The template function can then be used once to produce the view or as it is the case with
+ * {@link ng.directive:ngRepeat repeater} many-times, in which
+ * case each call results in a view that is a DOM clone of the original template.
+ *
+
+
+
+
+
+
+
+
+
+
+ it('should auto compile', function() {
+ expect(element('div[compile]').text()).toBe('Hello Angular');
+ input('html').enter('{{name}}!');
+ expect(element('div[compile]').text()).toBe('Angular!');
+ });
+
+
+
+ *
+ *
+ * @param {string|DOMElement} element Element or HTML string to compile into a template function.
+ * @param {function(angular.Scope[, cloneAttachFn]} transclude function available to directives.
+ * @param {number} maxPriority only apply directives lower then given priority (Only effects the
+ * root element(s), not their children)
+ * @returns {function(scope[, cloneAttachFn])} a link function which is used to bind template
+ * (a DOM element/tree) to a scope. Where:
+ *
+ * * `scope` - A {@link ng.$rootScope.Scope Scope} to bind to.
+ * * `cloneAttachFn` - If `cloneAttachFn` is provided, then the link function will clone the
+ * `template` and call the `cloneAttachFn` function allowing the caller to attach the
+ * cloned elements to the DOM document at the appropriate place. The `cloneAttachFn` is
+ * called as: `cloneAttachFn(clonedElement, scope)` where:
+ *
+ * * `clonedElement` - is a clone of the original `element` passed into the compiler.
+ * * `scope` - is the current scope with which the linking function is working with.
+ *
+ * Calling the linking function returns the element of the template. It is either the original element
+ * passed in, or the clone of the element if the `cloneAttachFn` is provided.
+ *
+ * After linking the view is not updated until after a call to $digest which typically is done by
+ * Angular automatically.
+ *
+ * If you need access to the bound view, there are two ways to do it:
+ *
+ * - If you are not asking the linking function to clone the template, create the DOM element(s)
+ * before you send them to the compiler and keep this reference around.
+ *
+ * var element = $compile('
{{total}}
')(scope);
+ *
+ *
+ * - if on the other hand, you need the element to be cloned, the view reference from the original
+ * example would not point to the clone, but rather to the original template that was cloned. In
+ * this case, you can access the clone via the cloneAttachFn:
+ *
+ * var templateHTML = angular.element('
{{total}}
'),
+ * scope = ....;
+ *
+ * var clonedElement = $compile(templateHTML)(scope, function(clonedElement, scope) {
+ * //attach the clone to DOM document at the right place
+ * });
+ *
+ * //now we have reference to the cloned DOM via `clone`
+ *
+ *
+ *
+ * For information on how the compiler works, see the
+ * {@link guide/compiler Angular HTML Compiler} section of the Developer Guide.
+ */
+
+
+/**
+ * @ngdoc service
+ * @name ng.$compileProvider
+ * @function
+ *
+ * @description
+ */
+$CompileProvider.$inject = ['$provide'];
+function $CompileProvider($provide) {
+ var hasDirectives = {},
+ Suffix = 'Directive',
+ COMMENT_DIRECTIVE_REGEXP = /^\s*directive\:\s*([\d\w\-_]+)\s+(.*)$/,
+ CLASS_DIRECTIVE_REGEXP = /(([\d\w\-_]+)(?:\:([^;]+))?;?)/,
+ MULTI_ROOT_TEMPLATE_ERROR = 'Template must have exactly one root element. was: ',
+ urlSanitizationWhitelist = /^\s*(https?|ftp|mailto|file):/;
+
+
+ /**
+ * @ngdoc function
+ * @name ng.$compileProvider#directive
+ * @methodOf ng.$compileProvider
+ * @function
+ *
+ * @description
+ * Register a new directives with the compiler.
+ *
+ * @param {string} name Name of the directive in camel-case. (ie ngBind which will match as
+ * ng-bind).
+ * @param {function} directiveFactory An injectable directive factory function. See {@link guide/directive} for more
+ * info.
+ * @returns {ng.$compileProvider} Self for chaining.
+ */
+ this.directive = function registerDirective(name, directiveFactory) {
+ if (isString(name)) {
+ assertArg(directiveFactory, 'directive');
+ if (!hasDirectives.hasOwnProperty(name)) {
+ hasDirectives[name] = [];
+ $provide.factory(name + Suffix, ['$injector', '$exceptionHandler',
+ function($injector, $exceptionHandler) {
+ var directives = [];
+ forEach(hasDirectives[name], function(directiveFactory) {
+ try {
+ var directive = $injector.invoke(directiveFactory);
+ if (isFunction(directive)) {
+ directive = { compile: valueFn(directive) };
+ } else if (!directive.compile && directive.link) {
+ directive.compile = valueFn(directive.link);
+ }
+ directive.priority = directive.priority || 0;
+ directive.name = directive.name || name;
+ directive.require = directive.require || (directive.controller && directive.name);
+ directive.restrict = directive.restrict || 'A';
+ directives.push(directive);
+ } catch (e) {
+ $exceptionHandler(e);
+ }
+ });
+ return directives;
+ }]);
+ }
+ hasDirectives[name].push(directiveFactory);
+ } else {
+ forEach(name, reverseParams(registerDirective));
+ }
+ return this;
+ };
+
+
+ /**
+ * @ngdoc function
+ * @name ng.$compileProvider#urlSanitizationWhitelist
+ * @methodOf ng.$compileProvider
+ * @function
+ *
+ * @description
+ * Retrieves or overrides the default regular expression that is used for whitelisting of safe
+ * urls during a[href] sanitization.
+ *
+ * The sanitization is a security measure aimed at prevent XSS attacks via html links.
+ *
+ * Any url about to be assigned to a[href] via data-binding is first normalized and turned into an
+ * absolute url. Afterwards the url is matched against the `urlSanitizationWhitelist` regular
+ * expression. If a match is found the original url is written into the dom. Otherwise the
+ * absolute url is prefixed with `'unsafe:'` string and only then it is written into the DOM.
+ *
+ * @param {RegExp=} regexp New regexp to whitelist urls with.
+ * @returns {RegExp|ng.$compileProvider} Current RegExp if called without value or self for
+ * chaining otherwise.
+ */
+ this.urlSanitizationWhitelist = function(regexp) {
+ if (isDefined(regexp)) {
+ urlSanitizationWhitelist = regexp;
+ return this;
+ }
+ return urlSanitizationWhitelist;
+ };
+
+
+ this.$get = [
+ '$injector', '$interpolate', '$exceptionHandler', '$http', '$templateCache', '$parse',
+ '$controller', '$rootScope', '$document',
+ function($injector, $interpolate, $exceptionHandler, $http, $templateCache, $parse,
+ $controller, $rootScope, $document) {
+
+ var Attributes = function(element, attr) {
+ this.$$element = element;
+ this.$attr = attr || {};
+ };
+
+ Attributes.prototype = {
+ $normalize: directiveNormalize,
+
+
+ /**
+ * Set a normalized attribute on the element in a way such that all directives
+ * can share the attribute. This function properly handles boolean attributes.
+ * @param {string} key Normalized key. (ie ngAttribute)
+ * @param {string|boolean} value The value to set. If `null` attribute will be deleted.
+ * @param {boolean=} writeAttr If false, does not write the value to DOM element attribute.
+ * Defaults to true.
+ * @param {string=} attrName Optional none normalized name. Defaults to key.
+ */
+ $set: function(key, value, writeAttr, attrName) {
+ var booleanKey = getBooleanAttrName(this.$$element[0], key),
+ $$observers = this.$$observers,
+ normalizedVal;
+
+ if (booleanKey) {
+ this.$$element.prop(key, value);
+ attrName = booleanKey;
+ }
+
+ this[key] = value;
+
+ // translate normalized key to actual key
+ if (attrName) {
+ this.$attr[key] = attrName;
+ } else {
+ attrName = this.$attr[key];
+ if (!attrName) {
+ this.$attr[key] = attrName = snake_case(key, '-');
+ }
+ }
+
+
+ // sanitize a[href] values
+ if (nodeName_(this.$$element[0]) === 'A' && key === 'href') {
+ urlSanitizationNode.setAttribute('href', value);
+
+ // href property always returns normalized absolute url, so we can match against that
+ normalizedVal = urlSanitizationNode.href;
+ if (!normalizedVal.match(urlSanitizationWhitelist)) {
+ this[key] = value = 'unsafe:' + normalizedVal;
+ }
+ }
+
+
+ if (writeAttr !== false) {
+ if (value === null || value === undefined) {
+ this.$$element.removeAttr(attrName);
+ } else {
+ this.$$element.attr(attrName, value);
+ }
+ }
+
+ // fire observers
+ $$observers && forEach($$observers[key], function(fn) {
+ try {
+ fn(value);
+ } catch (e) {
+ $exceptionHandler(e);
+ }
+ });
+ },
+
+
+ /**
+ * Observe an interpolated attribute.
+ * The observer will never be called, if given attribute is not interpolated.
+ *
+ * @param {string} key Normalized key. (ie ngAttribute) .
+ * @param {function(*)} fn Function that will be called whenever the attribute value changes.
+ * @returns {function(*)} the `fn` Function passed in.
+ */
+ $observe: function(key, fn) {
+ var attrs = this,
+ $$observers = (attrs.$$observers || (attrs.$$observers = {})),
+ listeners = ($$observers[key] || ($$observers[key] = []));
+
+ listeners.push(fn);
+ $rootScope.$evalAsync(function() {
+ if (!listeners.$$inter) {
+ // no one registered attribute interpolation function, so lets call it manually
+ fn(attrs[key]);
+ }
+ });
+ return fn;
+ }
+ };
+
+ var urlSanitizationNode = $document[0].createElement('a'),
+ startSymbol = $interpolate.startSymbol(),
+ endSymbol = $interpolate.endSymbol(),
+ denormalizeTemplate = (startSymbol == '{{' || endSymbol == '}}')
+ ? identity
+ : function denormalizeTemplate(template) {
+ return template.replace(/\{\{/g, startSymbol).replace(/}}/g, endSymbol);
+ },
+ NG_ATTR_BINDING = /^ngAttr[A-Z]/;
+
+
+ return compile;
+
+ //================================
+
+ function compile($compileNodes, transcludeFn, maxPriority) {
+ if (!($compileNodes instanceof jqLite)) {
+ // jquery always rewraps, whereas we need to preserve the original selector so that we can modify it.
+ $compileNodes = jqLite($compileNodes);
+ }
+ // We can not compile top level text elements since text nodes can be merged and we will
+ // not be able to attach scope data to them, so we will wrap them in
+ forEach($compileNodes, function(node, index){
+ if (node.nodeType == 3 /* text node */ && node.nodeValue.match(/\S+/) /* non-empty */ ) {
+ $compileNodes[index] = jqLite(node).wrap('').parent()[0];
+ }
+ });
+ var compositeLinkFn = compileNodes($compileNodes, transcludeFn, $compileNodes, maxPriority);
+ return function publicLinkFn(scope, cloneConnectFn){
+ assertArg(scope, 'scope');
+ // important!!: we must call our jqLite.clone() since the jQuery one is trying to be smart
+ // and sometimes changes the structure of the DOM.
+ var $linkNode = cloneConnectFn
+ ? JQLitePrototype.clone.call($compileNodes) // IMPORTANT!!!
+ : $compileNodes;
+
+ // Attach scope only to non-text nodes.
+ for(var i = 0, ii = $linkNode.length; i
+ addDirective(directives,
+ directiveNormalize(nodeName_(node).toLowerCase()), 'E', maxPriority);
+
+ // iterate over the attributes
+ for (var attr, name, nName, ngAttrName, value, nAttrs = node.attributes,
+ j = 0, jj = nAttrs && nAttrs.length; j < jj; j++) {
+ attr = nAttrs[j];
+ if (attr.specified) {
+ name = attr.name;
+ // support ngAttr attribute binding
+ ngAttrName = directiveNormalize(name);
+ if (NG_ATTR_BINDING.test(ngAttrName)) {
+ name = ngAttrName.substr(6).toLowerCase();
+ }
+ nName = directiveNormalize(name.toLowerCase());
+ attrsMap[nName] = name;
+ attrs[nName] = value = trim((msie && name == 'href')
+ ? decodeURIComponent(node.getAttribute(name, 2))
+ : attr.value);
+ if (getBooleanAttrName(node, nName)) {
+ attrs[nName] = true; // presence means true
+ }
+ addAttrInterpolateDirective(node, directives, value, nName);
+ addDirective(directives, nName, 'A', maxPriority);
+ }
+ }
+
+ // use class as directive
+ className = node.className;
+ if (isString(className) && className !== '') {
+ while (match = CLASS_DIRECTIVE_REGEXP.exec(className)) {
+ nName = directiveNormalize(match[2]);
+ if (addDirective(directives, nName, 'C', maxPriority)) {
+ attrs[nName] = trim(match[3]);
+ }
+ className = className.substr(match.index + match[0].length);
+ }
+ }
+ break;
+ case 3: /* Text Node */
+ addTextInterpolateDirective(directives, node.nodeValue);
+ break;
+ case 8: /* Comment */
+ try {
+ match = COMMENT_DIRECTIVE_REGEXP.exec(node.nodeValue);
+ if (match) {
+ nName = directiveNormalize(match[1]);
+ if (addDirective(directives, nName, 'M', maxPriority)) {
+ attrs[nName] = trim(match[2]);
+ }
+ }
+ } catch (e) {
+ // turns out that under some circumstances IE9 throws errors when one attempts to read comment's node value.
+ // Just ignore it and continue. (Can't seem to reproduce in test case.)
+ }
+ break;
+ }
+
+ directives.sort(byPriority);
+ return directives;
+ }
+
+
+ /**
+ * Once the directives have been collected, their compile functions are executed. This method
+ * is responsible for inlining directive templates as well as terminating the application
+ * of the directives if the terminal directive has been reached.
+ *
+ * @param {Array} directives Array of collected directives to execute their compile function.
+ * this needs to be pre-sorted by priority order.
+ * @param {Node} compileNode The raw DOM node to apply the compile functions to
+ * @param {Object} templateAttrs The shared attribute function
+ * @param {function(angular.Scope[, cloneAttachFn]} transcludeFn A linking function, where the
+ * scope argument is auto-generated to the new child of the transcluded parent scope.
+ * @param {JQLite} jqCollection If we are working on the root of the compile tree then this
+ * argument has the root jqLite array so that we can replace nodes on it.
+ * @returns linkFn
+ */
+ function applyDirectivesToNode(directives, compileNode, templateAttrs, transcludeFn, jqCollection) {
+ var terminalPriority = -Number.MAX_VALUE,
+ preLinkFns = [],
+ postLinkFns = [],
+ newScopeDirective = null,
+ newIsolateScopeDirective = null,
+ templateDirective = null,
+ $compileNode = templateAttrs.$$element = jqLite(compileNode),
+ directive,
+ directiveName,
+ $template,
+ transcludeDirective,
+ childTranscludeFn = transcludeFn,
+ controllerDirectives,
+ linkFn,
+ directiveValue;
+
+ // executes all directives on the current element
+ for(var i = 0, ii = directives.length; i < ii; i++) {
+ directive = directives[i];
+ $template = undefined;
+
+ if (terminalPriority > directive.priority) {
+ break; // prevent further processing of directives
+ }
+
+ if (directiveValue = directive.scope) {
+ assertNoDuplicate('isolated scope', newIsolateScopeDirective, directive, $compileNode);
+ if (isObject(directiveValue)) {
+ safeAddClass($compileNode, 'ng-isolate-scope');
+ newIsolateScopeDirective = directive;
+ }
+ safeAddClass($compileNode, 'ng-scope');
+ newScopeDirective = newScopeDirective || directive;
+ }
+
+ directiveName = directive.name;
+
+ if (directiveValue = directive.controller) {
+ controllerDirectives = controllerDirectives || {};
+ assertNoDuplicate("'" + directiveName + "' controller",
+ controllerDirectives[directiveName], directive, $compileNode);
+ controllerDirectives[directiveName] = directive;
+ }
+
+ if (directiveValue = directive.transclude) {
+ assertNoDuplicate('transclusion', transcludeDirective, directive, $compileNode);
+ transcludeDirective = directive;
+ terminalPriority = directive.priority;
+ if (directiveValue == 'element') {
+ $template = jqLite(compileNode);
+ $compileNode = templateAttrs.$$element =
+ jqLite(document.createComment(' ' + directiveName + ': ' + templateAttrs[directiveName] + ' '));
+ compileNode = $compileNode[0];
+ replaceWith(jqCollection, jqLite($template[0]), compileNode);
+ childTranscludeFn = compile($template, transcludeFn, terminalPriority);
+ } else {
+ $template = jqLite(JQLiteClone(compileNode)).contents();
+ $compileNode.html(''); // clear contents
+ childTranscludeFn = compile($template, transcludeFn);
+ }
+ }
+
+ if (directive.template) {
+ assertNoDuplicate('template', templateDirective, directive, $compileNode);
+ templateDirective = directive;
+
+ directiveValue = (isFunction(directive.template))
+ ? directive.template($compileNode, templateAttrs)
+ : directive.template;
+
+ directiveValue = denormalizeTemplate(directiveValue);
+
+ if (directive.replace) {
+ $template = jqLite('
' +
+ trim(directiveValue) +
+ '
').contents();
+ compileNode = $template[0];
+
+ if ($template.length != 1 || compileNode.nodeType !== 1) {
+ throw new Error(MULTI_ROOT_TEMPLATE_ERROR + directiveValue);
+ }
+
+ replaceWith(jqCollection, $compileNode, compileNode);
+
+ var newTemplateAttrs = {$attr: {}};
+
+ // combine directives from the original node and from the template:
+ // - take the array of directives for this element
+ // - split it into two parts, those that were already applied and those that weren't
+ // - collect directives from the template, add them to the second group and sort them
+ // - append the second group with new directives to the first group
+ directives = directives.concat(
+ collectDirectives(
+ compileNode,
+ directives.splice(i + 1, directives.length - (i + 1)),
+ newTemplateAttrs
+ )
+ );
+ mergeTemplateAttributes(templateAttrs, newTemplateAttrs);
+
+ ii = directives.length;
+ } else {
+ $compileNode.html(directiveValue);
+ }
+ }
+
+ if (directive.templateUrl) {
+ assertNoDuplicate('template', templateDirective, directive, $compileNode);
+ templateDirective = directive;
+ nodeLinkFn = compileTemplateUrl(directives.splice(i, directives.length - i),
+ nodeLinkFn, $compileNode, templateAttrs, jqCollection, directive.replace,
+ childTranscludeFn);
+ ii = directives.length;
+ } else if (directive.compile) {
+ try {
+ linkFn = directive.compile($compileNode, templateAttrs, childTranscludeFn);
+ if (isFunction(linkFn)) {
+ addLinkFns(null, linkFn);
+ } else if (linkFn) {
+ addLinkFns(linkFn.pre, linkFn.post);
+ }
+ } catch (e) {
+ $exceptionHandler(e, startingTag($compileNode));
+ }
+ }
+
+ if (directive.terminal) {
+ nodeLinkFn.terminal = true;
+ terminalPriority = Math.max(terminalPriority, directive.priority);
+ }
+
+ }
+
+ nodeLinkFn.scope = newScopeDirective && newScopeDirective.scope;
+ nodeLinkFn.transclude = transcludeDirective && childTranscludeFn;
+
+ // might be normal or delayed nodeLinkFn depending on if templateUrl is present
+ return nodeLinkFn;
+
+ ////////////////////
+
+ function addLinkFns(pre, post) {
+ if (pre) {
+ pre.require = directive.require;
+ preLinkFns.push(pre);
+ }
+ if (post) {
+ post.require = directive.require;
+ postLinkFns.push(post);
+ }
+ }
+
+
+ function getControllers(require, $element) {
+ var value, retrievalMethod = 'data', optional = false;
+ if (isString(require)) {
+ while((value = require.charAt(0)) == '^' || value == '?') {
+ require = require.substr(1);
+ if (value == '^') {
+ retrievalMethod = 'inheritedData';
+ }
+ optional = optional || value == '?';
+ }
+ value = $element[retrievalMethod]('$' + require + 'Controller');
+ if (!value && !optional) {
+ throw Error("No controller: " + require);
+ }
+ return value;
+ } else if (isArray(require)) {
+ value = [];
+ forEach(require, function(require) {
+ value.push(getControllers(require, $element));
+ });
+ }
+ return value;
+ }
+
+
+ function nodeLinkFn(childLinkFn, scope, linkNode, $rootElement, boundTranscludeFn) {
+ var attrs, $element, i, ii, linkFn, controller;
+
+ if (compileNode === linkNode) {
+ attrs = templateAttrs;
+ } else {
+ attrs = shallowCopy(templateAttrs, new Attributes(jqLite(linkNode), templateAttrs.$attr));
+ }
+ $element = attrs.$$element;
+
+ if (newIsolateScopeDirective) {
+ var LOCAL_REGEXP = /^\s*([@=&])(\??)\s*(\w*)\s*$/;
+
+ var parentScope = scope.$parent || scope;
+
+ forEach(newIsolateScopeDirective.scope, function(definiton, scopeName) {
+ var match = definiton.match(LOCAL_REGEXP) || [],
+ attrName = match[3] || scopeName,
+ optional = (match[2] == '?'),
+ mode = match[1], // @, =, or &
+ lastValue,
+ parentGet, parentSet;
+
+ scope.$$isolateBindings[scopeName] = mode + attrName;
+
+ switch (mode) {
+
+ case '@': {
+ attrs.$observe(attrName, function(value) {
+ scope[scopeName] = value;
+ });
+ attrs.$$observers[attrName].$$scope = parentScope;
+ if( attrs[attrName] ) {
+ // If the attribute has been provided then we trigger an interpolation to ensure the value is there for use in the link fn
+ scope[scopeName] = $interpolate(attrs[attrName])(parentScope);
+ }
+ break;
+ }
+
+ case '=': {
+ if (optional && !attrs[attrName]) {
+ return;
+ }
+ parentGet = $parse(attrs[attrName]);
+ parentSet = parentGet.assign || function() {
+ // reset the change, or we will throw this exception on every $digest
+ lastValue = scope[scopeName] = parentGet(parentScope);
+ throw Error(NON_ASSIGNABLE_MODEL_EXPRESSION + attrs[attrName] +
+ ' (directive: ' + newIsolateScopeDirective.name + ')');
+ };
+ lastValue = scope[scopeName] = parentGet(parentScope);
+ scope.$watch(function parentValueWatch() {
+ var parentValue = parentGet(parentScope);
+
+ if (parentValue !== scope[scopeName]) {
+ // we are out of sync and need to copy
+ if (parentValue !== lastValue) {
+ // parent changed and it has precedence
+ lastValue = scope[scopeName] = parentValue;
+ } else {
+ // if the parent can be assigned then do so
+ parentSet(parentScope, parentValue = lastValue = scope[scopeName]);
+ }
+ }
+ return parentValue;
+ });
+ break;
+ }
+
+ case '&': {
+ parentGet = $parse(attrs[attrName]);
+ scope[scopeName] = function(locals) {
+ return parentGet(parentScope, locals);
+ };
+ break;
+ }
+
+ default: {
+ throw Error('Invalid isolate scope definition for directive ' +
+ newIsolateScopeDirective.name + ': ' + definiton);
+ }
+ }
+ });
+ }
+
+ if (controllerDirectives) {
+ forEach(controllerDirectives, function(directive) {
+ var locals = {
+ $scope: scope,
+ $element: $element,
+ $attrs: attrs,
+ $transclude: boundTranscludeFn
+ };
+
+ controller = directive.controller;
+ if (controller == '@') {
+ controller = attrs[directive.name];
+ }
+
+ $element.data(
+ '$' + directive.name + 'Controller',
+ $controller(controller, locals));
+ });
+ }
+
+ // PRELINKING
+ for(i = 0, ii = preLinkFns.length; i < ii; i++) {
+ try {
+ linkFn = preLinkFns[i];
+ linkFn(scope, $element, attrs,
+ linkFn.require && getControllers(linkFn.require, $element));
+ } catch (e) {
+ $exceptionHandler(e, startingTag($element));
+ }
+ }
+
+ // RECURSION
+ childLinkFn && childLinkFn(scope, linkNode.childNodes, undefined, boundTranscludeFn);
+
+ // POSTLINKING
+ for(i = 0, ii = postLinkFns.length; i < ii; i++) {
+ try {
+ linkFn = postLinkFns[i];
+ linkFn(scope, $element, attrs,
+ linkFn.require && getControllers(linkFn.require, $element));
+ } catch (e) {
+ $exceptionHandler(e, startingTag($element));
+ }
+ }
+ }
+ }
+
+
+ /**
+ * looks up the directive and decorates it with exception handling and proper parameters. We
+ * call this the boundDirective.
+ *
+ * @param {string} name name of the directive to look up.
+ * @param {string} location The directive must be found in specific format.
+ * String containing any of theses characters:
+ *
+ * * `E`: element name
+ * * `A': attribute
+ * * `C`: class
+ * * `M`: comment
+ * @returns true if directive was added.
+ */
+ function addDirective(tDirectives, name, location, maxPriority) {
+ var match = false;
+ if (hasDirectives.hasOwnProperty(name)) {
+ for(var directive, directives = $injector.get(name + Suffix),
+ i = 0, ii = directives.length; i directive.priority) &&
+ directive.restrict.indexOf(location) != -1) {
+ tDirectives.push(directive);
+ match = true;
+ }
+ } catch(e) { $exceptionHandler(e); }
+ }
+ }
+ return match;
+ }
+
+
+ /**
+ * When the element is replaced with HTML template then the new attributes
+ * on the template need to be merged with the existing attributes in the DOM.
+ * The desired effect is to have both of the attributes present.
+ *
+ * @param {object} dst destination attributes (original DOM)
+ * @param {object} src source attributes (from the directive template)
+ */
+ function mergeTemplateAttributes(dst, src) {
+ var srcAttr = src.$attr,
+ dstAttr = dst.$attr,
+ $element = dst.$$element;
+
+ // reapply the old attributes to the new element
+ forEach(dst, function(value, key) {
+ if (key.charAt(0) != '$') {
+ if (src[key]) {
+ value += (key === 'style' ? ';' : ' ') + src[key];
+ }
+ dst.$set(key, value, true, srcAttr[key]);
+ }
+ });
+
+ // copy the new attributes on the old attrs object
+ forEach(src, function(value, key) {
+ if (key == 'class') {
+ safeAddClass($element, value);
+ dst['class'] = (dst['class'] ? dst['class'] + ' ' : '') + value;
+ } else if (key == 'style') {
+ $element.attr('style', $element.attr('style') + ';' + value);
+ } else if (key.charAt(0) != '$' && !dst.hasOwnProperty(key)) {
+ dst[key] = value;
+ dstAttr[key] = srcAttr[key];
+ }
+ });
+ }
+
+
+ function compileTemplateUrl(directives, beforeTemplateNodeLinkFn, $compileNode, tAttrs,
+ $rootElement, replace, childTranscludeFn) {
+ var linkQueue = [],
+ afterTemplateNodeLinkFn,
+ afterTemplateChildLinkFn,
+ beforeTemplateCompileNode = $compileNode[0],
+ origAsyncDirective = directives.shift(),
+ // The fact that we have to copy and patch the directive seems wrong!
+ derivedSyncDirective = extend({}, origAsyncDirective, {
+ controller: null, templateUrl: null, transclude: null, scope: null
+ }),
+ templateUrl = (isFunction(origAsyncDirective.templateUrl))
+ ? origAsyncDirective.templateUrl($compileNode, tAttrs)
+ : origAsyncDirective.templateUrl;
+
+ $compileNode.html('');
+
+ $http.get(templateUrl, {cache: $templateCache}).
+ success(function(content) {
+ var compileNode, tempTemplateAttrs, $template;
+
+ content = denormalizeTemplate(content);
+
+ if (replace) {
+ $template = jqLite('
' + trim(content) + '
').contents();
+ compileNode = $template[0];
+
+ if ($template.length != 1 || compileNode.nodeType !== 1) {
+ throw new Error(MULTI_ROOT_TEMPLATE_ERROR + content);
+ }
+
+ tempTemplateAttrs = {$attr: {}};
+ replaceWith($rootElement, $compileNode, compileNode);
+ collectDirectives(compileNode, directives, tempTemplateAttrs);
+ mergeTemplateAttributes(tAttrs, tempTemplateAttrs);
+ } else {
+ compileNode = beforeTemplateCompileNode;
+ $compileNode.html(content);
+ }
+
+ directives.unshift(derivedSyncDirective);
+ afterTemplateNodeLinkFn = applyDirectivesToNode(directives, compileNode, tAttrs, childTranscludeFn);
+ afterTemplateChildLinkFn = compileNodes($compileNode[0].childNodes, childTranscludeFn);
+
+
+ while(linkQueue.length) {
+ var scope = linkQueue.shift(),
+ beforeTemplateLinkNode = linkQueue.shift(),
+ linkRootElement = linkQueue.shift(),
+ controller = linkQueue.shift(),
+ linkNode = compileNode;
+
+ if (beforeTemplateLinkNode !== beforeTemplateCompileNode) {
+ // it was cloned therefore we have to clone as well.
+ linkNode = JQLiteClone(compileNode);
+ replaceWith(linkRootElement, jqLite(beforeTemplateLinkNode), linkNode);
+ }
+
+ afterTemplateNodeLinkFn(function() {
+ beforeTemplateNodeLinkFn(afterTemplateChildLinkFn, scope, linkNode, $rootElement, controller);
+ }, scope, linkNode, $rootElement, controller);
+ }
+ linkQueue = null;
+ }).
+ error(function(response, code, headers, config) {
+ throw Error('Failed to load template: ' + config.url);
+ });
+
+ return function delayedNodeLinkFn(ignoreChildLinkFn, scope, node, rootElement, controller) {
+ if (linkQueue) {
+ linkQueue.push(scope);
+ linkQueue.push(node);
+ linkQueue.push(rootElement);
+ linkQueue.push(controller);
+ } else {
+ afterTemplateNodeLinkFn(function() {
+ beforeTemplateNodeLinkFn(afterTemplateChildLinkFn, scope, node, rootElement, controller);
+ }, scope, node, rootElement, controller);
+ }
+ };
+ }
+
+
+ /**
+ * Sorting function for bound directives.
+ */
+ function byPriority(a, b) {
+ return b.priority - a.priority;
+ }
+
+
+ function assertNoDuplicate(what, previousDirective, directive, element) {
+ if (previousDirective) {
+ throw Error('Multiple directives [' + previousDirective.name + ', ' +
+ directive.name + '] asking for ' + what + ' on: ' + startingTag(element));
+ }
+ }
+
+
+ function addTextInterpolateDirective(directives, text) {
+ var interpolateFn = $interpolate(text, true);
+ if (interpolateFn) {
+ directives.push({
+ priority: 0,
+ compile: valueFn(function textInterpolateLinkFn(scope, node) {
+ var parent = node.parent(),
+ bindings = parent.data('$binding') || [];
+ bindings.push(interpolateFn);
+ safeAddClass(parent.data('$binding', bindings), 'ng-binding');
+ scope.$watch(interpolateFn, function interpolateFnWatchAction(value) {
+ node[0].nodeValue = value;
+ });
+ })
+ });
+ }
+ }
+
+
+ function addAttrInterpolateDirective(node, directives, value, name) {
+ var interpolateFn = $interpolate(value, true);
+
+ // no interpolation found -> ignore
+ if (!interpolateFn) return;
+
+
+ directives.push({
+ priority: 100,
+ compile: valueFn(function attrInterpolateLinkFn(scope, element, attr) {
+ var $$observers = (attr.$$observers || (attr.$$observers = {}));
+
+ // we need to interpolate again, in case the attribute value has been updated
+ // (e.g. by another directive's compile function)
+ interpolateFn = $interpolate(attr[name], true);
+
+ // if attribute was updated so that there is no interpolation going on we don't want to
+ // register any observers
+ if (!interpolateFn) return;
+
+ attr[name] = interpolateFn(scope);
+ ($$observers[name] || ($$observers[name] = [])).$$inter = true;
+ (attr.$$observers && attr.$$observers[name].$$scope || scope).
+ $watch(interpolateFn, function interpolateFnWatchAction(value) {
+ attr.$set(name, value);
+ });
+ })
+ });
+ }
+
+
+ /**
+ * This is a special jqLite.replaceWith, which can replace items which
+ * have no parents, provided that the containing jqLite collection is provided.
+ *
+ * @param {JqLite=} $rootElement The root of the compile tree. Used so that we can replace nodes
+ * in the root of the tree.
+ * @param {JqLite} $element The jqLite element which we are going to replace. We keep the shell,
+ * but replace its DOM node reference.
+ * @param {Node} newNode The new DOM node.
+ */
+ function replaceWith($rootElement, $element, newNode) {
+ var oldNode = $element[0],
+ parent = oldNode.parentNode,
+ i, ii;
+
+ if ($rootElement) {
+ for(i = 0, ii = $rootElement.length; i < ii; i++) {
+ if ($rootElement[i] == oldNode) {
+ $rootElement[i] = newNode;
+ break;
+ }
+ }
+ }
+
+ if (parent) {
+ parent.replaceChild(newNode, oldNode);
+ }
+
+ newNode[jqLite.expando] = oldNode[jqLite.expando];
+ $element[0] = newNode;
+ }
+ }];
+}
+
+var PREFIX_REGEXP = /^(x[\:\-_]|data[\:\-_])/i;
+/**
+ * Converts all accepted directives format into proper directive name.
+ * All of these will become 'myDirective':
+ * my:DiRective
+ * my-directive
+ * x-my-directive
+ * data-my:directive
+ *
+ * Also there is special case for Moz prefix starting with upper case letter.
+ * @param name Name to normalize
+ */
+function directiveNormalize(name) {
+ return camelCase(name.replace(PREFIX_REGEXP, ''));
+}
+
+/**
+ * @ngdoc object
+ * @name ng.$compile.directive.Attributes
+ * @description
+ *
+ * A shared object between directive compile / linking functions which contains normalized DOM element
+ * attributes. The the values reflect current binding state `{{ }}`. The normalization is needed
+ * since all of these are treated as equivalent in Angular:
+ *
+ *
+ */
+
+/**
+ * @ngdoc property
+ * @name ng.$compile.directive.Attributes#$attr
+ * @propertyOf ng.$compile.directive.Attributes
+ * @returns {object} A map of DOM element attribute names to the normalized name. This is
+ * needed to do reverse lookup from normalized name back to actual name.
+ */
+
+
+/**
+ * @ngdoc function
+ * @name ng.$compile.directive.Attributes#$set
+ * @methodOf ng.$compile.directive.Attributes
+ * @function
+ *
+ * @description
+ * Set DOM element attribute value.
+ *
+ *
+ * @param {string} name Normalized element attribute name of the property to modify. The name is
+ * revers translated using the {@link ng.$compile.directive.Attributes#$attr $attr}
+ * property to the original name.
+ * @param {string} value Value to set the attribute to. The value can be an interpolated string.
+ */
+
+
+
+/**
+ * Closure compiler type information
+ */
+
+function nodesetLinkingFn(
+ /* angular.Scope */ scope,
+ /* NodeList */ nodeList,
+ /* Element */ rootElement,
+ /* function(Function) */ boundTranscludeFn
+){}
+
+function directiveLinkingFn(
+ /* nodesetLinkingFn */ nodesetLinkingFn,
+ /* angular.Scope */ scope,
+ /* Node */ node,
+ /* Element */ rootElement,
+ /* function(Function) */ boundTranscludeFn
+){}
+
+/**
+ * @ngdoc object
+ * @name ng.$controllerProvider
+ * @description
+ * The {@link ng.$controller $controller service} is used by Angular to create new
+ * controllers.
+ *
+ * This provider allows controller registration via the
+ * {@link ng.$controllerProvider#register register} method.
+ */
+function $ControllerProvider() {
+ var controllers = {},
+ CNTRL_REG = /^(\S+)(\s+as\s+(\w+))?$/;
+
+
+ /**
+ * @ngdoc function
+ * @name ng.$controllerProvider#register
+ * @methodOf ng.$controllerProvider
+ * @param {string} name Controller name
+ * @param {Function|Array} constructor Controller constructor fn (optionally decorated with DI
+ * annotations in the array notation).
+ */
+ this.register = function(name, constructor) {
+ if (isObject(name)) {
+ extend(controllers, name)
+ } else {
+ controllers[name] = constructor;
+ }
+ };
+
+
+ this.$get = ['$injector', '$window', function($injector, $window) {
+
+ /**
+ * @ngdoc function
+ * @name ng.$controller
+ * @requires $injector
+ *
+ * @param {Function|string} constructor If called with a function then it's considered to be the
+ * controller constructor function. Otherwise it's considered to be a string which is used
+ * to retrieve the controller constructor using the following steps:
+ *
+ * * check if a controller with given name is registered via `$controllerProvider`
+ * * check if evaluating the string on the current scope returns a constructor
+ * * check `window[constructor]` on the global `window` object
+ *
+ * @param {Object} locals Injection locals for Controller.
+ * @return {Object} Instance of given controller.
+ *
+ * @description
+ * `$controller` service is responsible for instantiating controllers.
+ *
+ * It's just a simple call to {@link AUTO.$injector $injector}, but extracted into
+ * a service, so that one can override this service with {@link https://gist.github.com/1649788
+ * BC version}.
+ */
+ return function(expression, locals) {
+ var instance, match, constructor, identifier;
+
+ if(isString(expression)) {
+ match = expression.match(CNTRL_REG),
+ constructor = match[1],
+ identifier = match[3];
+ expression = controllers.hasOwnProperty(constructor)
+ ? controllers[constructor]
+ : getter(locals.$scope, constructor, true) || getter($window, constructor, true);
+
+ assertArgFn(expression, constructor, true);
+ }
+
+ instance = $injector.instantiate(expression, locals);
+
+ if (identifier) {
+ if (typeof locals.$scope !== 'object') {
+ throw new Error('Can not export controller as "' + identifier + '". ' +
+ 'No scope object provided!');
+ }
+
+ locals.$scope[identifier] = instance;
+ }
+
+ return instance;
+ };
+ }];
+}
+
+/**
+ * @ngdoc object
+ * @name ng.$document
+ * @requires $window
+ *
+ * @description
+ * A {@link angular.element jQuery (lite)}-wrapped reference to the browser's `window.document`
+ * element.
+ */
+function $DocumentProvider(){
+ this.$get = ['$window', function(window){
+ return jqLite(window.document);
+ }];
+}
+
+/**
+ * @ngdoc function
+ * @name ng.$exceptionHandler
+ * @requires $log
+ *
+ * @description
+ * Any uncaught exception in angular expressions is delegated to this service.
+ * The default implementation simply delegates to `$log.error` which logs it into
+ * the browser console.
+ *
+ * In unit tests, if `angular-mocks.js` is loaded, this service is overridden by
+ * {@link ngMock.$exceptionHandler mock $exceptionHandler} which aids in testing.
+ *
+ * @param {Error} exception Exception associated with the error.
+ * @param {string=} cause optional information about the context in which
+ * the error was thrown.
+ *
+ */
+function $ExceptionHandlerProvider() {
+ this.$get = ['$log', function($log) {
+ return function(exception, cause) {
+ $log.error.apply($log, arguments);
+ };
+ }];
+}
+
+/**
+ * @ngdoc object
+ * @name ng.$interpolateProvider
+ * @function
+ *
+ * @description
+ *
+ * Used for configuring the interpolation markup. Defaults to `{{` and `}}`.
+ */
+function $InterpolateProvider() {
+ var startSymbol = '{{';
+ var endSymbol = '}}';
+
+ /**
+ * @ngdoc method
+ * @name ng.$interpolateProvider#startSymbol
+ * @methodOf ng.$interpolateProvider
+ * @description
+ * Symbol to denote start of expression in the interpolated string. Defaults to `{{`.
+ *
+ * @param {string=} value new value to set the starting symbol to.
+ * @returns {string|self} Returns the symbol when used as getter and self if used as setter.
+ */
+ this.startSymbol = function(value){
+ if (value) {
+ startSymbol = value;
+ return this;
+ } else {
+ return startSymbol;
+ }
+ };
+
+ /**
+ * @ngdoc method
+ * @name ng.$interpolateProvider#endSymbol
+ * @methodOf ng.$interpolateProvider
+ * @description
+ * Symbol to denote the end of expression in the interpolated string. Defaults to `}}`.
+ *
+ * @param {string=} value new value to set the ending symbol to.
+ * @returns {string|self} Returns the symbol when used as getter and self if used as setter.
+ */
+ this.endSymbol = function(value){
+ if (value) {
+ endSymbol = value;
+ return this;
+ } else {
+ return endSymbol;
+ }
+ };
+
+
+ this.$get = ['$parse', '$exceptionHandler', function($parse, $exceptionHandler) {
+ var startSymbolLength = startSymbol.length,
+ endSymbolLength = endSymbol.length;
+
+ /**
+ * @ngdoc function
+ * @name ng.$interpolate
+ * @function
+ *
+ * @requires $parse
+ *
+ * @description
+ *
+ * Compiles a string with markup into an interpolation function. This service is used by the
+ * HTML {@link ng.$compile $compile} service for data binding. See
+ * {@link ng.$interpolateProvider $interpolateProvider} for configuring the
+ * interpolation markup.
+ *
+ *
+
+ var $interpolate = ...; // injected
+ var exp = $interpolate('Hello {{name}}!');
+ expect(exp({name:'Angular'}).toEqual('Hello Angular!');
+
+ *
+ *
+ * @param {string} text The text with markup to interpolate.
+ * @param {boolean=} mustHaveExpression if set to true then the interpolation string must have
+ * embedded expression in order to return an interpolation function. Strings with no
+ * embedded expression will return null for the interpolation function.
+ * @returns {function(context)} an interpolation function which is used to compute the interpolated
+ * string. The function has these parameters:
+ *
+ * * `context`: an object against which any expressions embedded in the strings are evaluated
+ * against.
+ *
+ */
+ function $interpolate(text, mustHaveExpression) {
+ var startIndex,
+ endIndex,
+ index = 0,
+ parts = [],
+ length = text.length,
+ hasInterpolation = false,
+ fn,
+ exp,
+ concat = [];
+
+ while(index < length) {
+ if ( ((startIndex = text.indexOf(startSymbol, index)) != -1) &&
+ ((endIndex = text.indexOf(endSymbol, startIndex + startSymbolLength)) != -1) ) {
+ (index != startIndex) && parts.push(text.substring(index, startIndex));
+ parts.push(fn = $parse(exp = text.substring(startIndex + startSymbolLength, endIndex)));
+ fn.exp = exp;
+ index = endIndex + endSymbolLength;
+ hasInterpolation = true;
+ } else {
+ // we did not find anything, so we have to add the remainder to the parts array
+ (index != length) && parts.push(text.substring(index));
+ index = length;
+ }
+ }
+
+ if (!(length = parts.length)) {
+ // we added, nothing, must have been an empty string.
+ parts.push('');
+ length = 1;
+ }
+
+ if (!mustHaveExpression || hasInterpolation) {
+ concat.length = length;
+ fn = function(context) {
+ try {
+ for(var i = 0, ii = length, part; i=} search New search params - string or hash object
+ * @param {string=} paramValue If `search` is a string, then `paramValue` will override only a
+ * single search parameter. If the value is `null`, the parameter will be deleted.
+ *
+ * @return {string} search
+ */
+ search: function(search, paramValue) {
+ if (isUndefined(search))
+ return this.$$search;
+
+ if (isDefined(paramValue)) {
+ if (paramValue === null) {
+ delete this.$$search[search];
+ } else {
+ this.$$search[search] = paramValue;
+ }
+ } else {
+ this.$$search = isString(search) ? parseKeyValue(search) : search;
+ }
+
+ this.$$compose();
+ return this;
+ },
+
+ /**
+ * @ngdoc method
+ * @name ng.$location#hash
+ * @methodOf ng.$location
+ *
+ * @description
+ * This method is getter / setter.
+ *
+ * Return hash fragment when called without any parameter.
+ *
+ * Change hash fragment when called with parameter and return `$location`.
+ *
+ * @param {string=} hash New hash fragment
+ * @return {string} hash
+ */
+ hash: locationGetterSetter('$$hash', identity),
+
+ /**
+ * @ngdoc method
+ * @name ng.$location#replace
+ * @methodOf ng.$location
+ *
+ * @description
+ * If called, all changes to $location during current `$digest` will be replacing current history
+ * record, instead of adding new one.
+ */
+ replace: function() {
+ this.$$replace = true;
+ return this;
+ }
+};
+
+function locationGetter(property) {
+ return function() {
+ return this[property];
+ };
+}
+
+
+function locationGetterSetter(property, preprocess) {
+ return function(value) {
+ if (isUndefined(value))
+ return this[property];
+
+ this[property] = preprocess(value);
+ this.$$compose();
+
+ return this;
+ };
+}
+
+
+/**
+ * @ngdoc object
+ * @name ng.$location
+ *
+ * @requires $browser
+ * @requires $sniffer
+ * @requires $rootElement
+ *
+ * @description
+ * The $location service parses the URL in the browser address bar (based on the
+ * {@link https://developer.mozilla.org/en/window.location window.location}) and makes the URL
+ * available to your application. Changes to the URL in the address bar are reflected into
+ * $location service and changes to $location are reflected into the browser address bar.
+ *
+ * **The $location service:**
+ *
+ * - Exposes the current URL in the browser address bar, so you can
+ * - Watch and observe the URL.
+ * - Change the URL.
+ * - Synchronizes the URL with the browser when the user
+ * - Changes the address bar.
+ * - Clicks the back or forward button (or clicks a History link).
+ * - Clicks on a link.
+ * - Represents the URL object as a set of methods (protocol, host, port, path, search, hash).
+ *
+ * For more information see {@link guide/dev_guide.services.$location Developer Guide: Angular
+ * Services: Using $location}
+ */
+
+/**
+ * @ngdoc object
+ * @name ng.$locationProvider
+ * @description
+ * Use the `$locationProvider` to configure how the application deep linking paths are stored.
+ */
+function $LocationProvider(){
+ var hashPrefix = '',
+ html5Mode = false;
+
+ /**
+ * @ngdoc property
+ * @name ng.$locationProvider#hashPrefix
+ * @methodOf ng.$locationProvider
+ * @description
+ * @param {string=} prefix Prefix for hash part (containing path and search)
+ * @returns {*} current value if used as getter or itself (chaining) if used as setter
+ */
+ this.hashPrefix = function(prefix) {
+ if (isDefined(prefix)) {
+ hashPrefix = prefix;
+ return this;
+ } else {
+ return hashPrefix;
+ }
+ };
+
+ /**
+ * @ngdoc property
+ * @name ng.$locationProvider#html5Mode
+ * @methodOf ng.$locationProvider
+ * @description
+ * @param {string=} mode Use HTML5 strategy if available.
+ * @returns {*} current value if used as getter or itself (chaining) if used as setter
+ */
+ this.html5Mode = function(mode) {
+ if (isDefined(mode)) {
+ html5Mode = mode;
+ return this;
+ } else {
+ return html5Mode;
+ }
+ };
+
+ this.$get = ['$rootScope', '$browser', '$sniffer', '$rootElement',
+ function( $rootScope, $browser, $sniffer, $rootElement) {
+ var $location,
+ LocationMode,
+ baseHref = $browser.baseHref(),
+ initialUrl = $browser.url(),
+ appBase;
+
+ if (html5Mode) {
+ appBase = baseHref ? serverBase(initialUrl) + baseHref : initialUrl;
+ LocationMode = $sniffer.history ? LocationHtml5Url : LocationHashbangInHtml5Url;
+ } else {
+ appBase = stripHash(initialUrl);
+ LocationMode = LocationHashbangUrl;
+ }
+ $location = new LocationMode(appBase, '#' + hashPrefix);
+ $location.$$parse($location.$$rewrite(initialUrl));
+
+ $rootElement.bind('click', function(event) {
+ // TODO(vojta): rewrite link when opening in new tab/window (in legacy browser)
+ // currently we open nice url link and redirect then
+
+ if (event.ctrlKey || event.metaKey || event.which == 2) return;
+
+ var elm = jqLite(event.target);
+
+ // traverse the DOM up to find first A tag
+ while (lowercase(elm[0].nodeName) !== 'a') {
+ // ignore rewriting if no A tag (reached root element, or no parent - removed from document)
+ if (elm[0] === $rootElement[0] || !(elm = elm.parent())[0]) return;
+ }
+
+ var absHref = elm.prop('href');
+ var rewrittenUrl = $location.$$rewrite(absHref);
+
+ if (absHref && !elm.attr('target') && rewrittenUrl && !event.isDefaultPrevented()) {
+ event.preventDefault();
+ if (rewrittenUrl != $browser.url()) {
+ // update location manually
+ $location.$$parse(rewrittenUrl);
+ $rootScope.$apply();
+ // hack to work around FF6 bug 684208 when scenario runner clicks on links
+ window.angular['ff-684208-preventDefault'] = true;
+ }
+ }
+ });
+
+
+ // rewrite hashbang url <> html5 url
+ if ($location.absUrl() != initialUrl) {
+ $browser.url($location.absUrl(), true);
+ }
+
+ // update $location when $browser url changes
+ $browser.onUrlChange(function(newUrl) {
+ if ($location.absUrl() != newUrl) {
+ if ($rootScope.$broadcast('$locationChangeStart', newUrl, $location.absUrl()).defaultPrevented) {
+ $browser.url($location.absUrl());
+ return;
+ }
+ $rootScope.$evalAsync(function() {
+ var oldUrl = $location.absUrl();
+
+ $location.$$parse(newUrl);
+ afterLocationChange(oldUrl);
+ });
+ if (!$rootScope.$$phase) $rootScope.$digest();
+ }
+ });
+
+ // update browser
+ var changeCounter = 0;
+ $rootScope.$watch(function $locationWatch() {
+ var oldUrl = $browser.url();
+ var currentReplace = $location.$$replace;
+
+ if (!changeCounter || oldUrl != $location.absUrl()) {
+ changeCounter++;
+ $rootScope.$evalAsync(function() {
+ if ($rootScope.$broadcast('$locationChangeStart', $location.absUrl(), oldUrl).
+ defaultPrevented) {
+ $location.$$parse(oldUrl);
+ } else {
+ $browser.url($location.absUrl(), currentReplace);
+ afterLocationChange(oldUrl);
+ }
+ });
+ }
+ $location.$$replace = false;
+
+ return changeCounter;
+ });
+
+ return $location;
+
+ function afterLocationChange(oldUrl) {
+ $rootScope.$broadcast('$locationChangeSuccess', $location.absUrl(), oldUrl);
+ }
+}];
+}
+
+/**
+ * @ngdoc object
+ * @name ng.$log
+ * @requires $window
+ *
+ * @description
+ * Simple service for logging. Default implementation writes the message
+ * into the browser's console (if present).
+ *
+ * The main purpose of this service is to simplify debugging and troubleshooting.
+ *
+ * @example
+
+
+ function LogCtrl($scope, $log) {
+ $scope.$log = $log;
+ $scope.message = 'Hello World!';
+ }
+
+
+
+
Reload this page with open console, enter text and hit the log button...
+ Message:
+
+
+
+
+
+
+
+
+ */
+
+/**
+ * @ngdoc object
+ * @name ng.$logProvider
+ * @description
+ * Use the `$logProvider` to configure how the application logs messages
+ */
+function $LogProvider(){
+ var debug = true,
+ self = this;
+
+ /**
+ * @ngdoc property
+ * @name ng.$logProvider#debugEnabled
+ * @methodOf ng.$logProvider
+ * @description
+ * @param {string=} flag enable or disable debug level messages
+ * @returns {*} current value if used as getter or itself (chaining) if used as setter
+ */
+ this.debugEnabled = function(flag) {
+ if (isDefined(flag)) {
+ debug = flag;
+ return this;
+ } else {
+ return debug;
+ }
+ };
+
+ this.$get = ['$window', function($window){
+ return {
+ /**
+ * @ngdoc method
+ * @name ng.$log#log
+ * @methodOf ng.$log
+ *
+ * @description
+ * Write a log message
+ */
+ log: consoleLog('log'),
+
+ /**
+ * @ngdoc method
+ * @name ng.$log#warn
+ * @methodOf ng.$log
+ *
+ * @description
+ * Write a warning message
+ */
+ warn: consoleLog('warn'),
+
+ /**
+ * @ngdoc method
+ * @name ng.$log#info
+ * @methodOf ng.$log
+ *
+ * @description
+ * Write an information message
+ */
+ info: consoleLog('info'),
+
+ /**
+ * @ngdoc method
+ * @name ng.$log#error
+ * @methodOf ng.$log
+ *
+ * @description
+ * Write an error message
+ */
+ error: consoleLog('error'),
+
+ /**
+ * @ngdoc method
+ * @name ng.$log#debug
+ * @methodOf ng.$log
+ *
+ * @description
+ * Write a debug message
+ */
+ debug: (function () {
+ var fn = consoleLog('debug');
+
+ return function() {
+ if (debug) {
+ fn.apply(self, arguments);
+ }
+ }
+ }())
+ };
+
+ function formatError(arg) {
+ if (arg instanceof Error) {
+ if (arg.stack) {
+ arg = (arg.message && arg.stack.indexOf(arg.message) === -1)
+ ? 'Error: ' + arg.message + '\n' + arg.stack
+ : arg.stack;
+ } else if (arg.sourceURL) {
+ arg = arg.message + '\n' + arg.sourceURL + ':' + arg.line;
+ }
+ }
+ return arg;
+ }
+
+ function consoleLog(type) {
+ var console = $window.console || {},
+ logFn = console[type] || console.log || noop;
+
+ if (logFn.apply) {
+ return function() {
+ var args = [];
+ forEach(arguments, function(arg) {
+ args.push(formatError(arg));
+ });
+ return logFn.apply(console, args);
+ };
+ }
+
+ // we are IE which either doesn't have window.console => this is noop and we do nothing,
+ // or we are IE where console.log doesn't have apply so we log at least first 2 args
+ return function(arg1, arg2) {
+ logFn(arg1, arg2);
+ }
+ }
+ }];
+}
+
+var OPERATORS = {
+ 'null':function(){return null;},
+ 'true':function(){return true;},
+ 'false':function(){return false;},
+ undefined:noop,
+ '+':function(self, locals, a,b){
+ a=a(self, locals); b=b(self, locals);
+ if (isDefined(a)) {
+ if (isDefined(b)) {
+ return a + b;
+ }
+ return a;
+ }
+ return isDefined(b)?b:undefined;},
+ '-':function(self, locals, a,b){a=a(self, locals); b=b(self, locals); return (isDefined(a)?a:0)-(isDefined(b)?b:0);},
+ '*':function(self, locals, a,b){return a(self, locals)*b(self, locals);},
+ '/':function(self, locals, a,b){return a(self, locals)/b(self, locals);},
+ '%':function(self, locals, a,b){return a(self, locals)%b(self, locals);},
+ '^':function(self, locals, a,b){return a(self, locals)^b(self, locals);},
+ '=':noop,
+ '===':function(self, locals, a, b){return a(self, locals)===b(self, locals);},
+ '!==':function(self, locals, a, b){return a(self, locals)!==b(self, locals);},
+ '==':function(self, locals, a,b){return a(self, locals)==b(self, locals);},
+ '!=':function(self, locals, a,b){return a(self, locals)!=b(self, locals);},
+ '<':function(self, locals, a,b){return a(self, locals)':function(self, locals, a,b){return a(self, locals)>b(self, locals);},
+ '<=':function(self, locals, a,b){return a(self, locals)<=b(self, locals);},
+ '>=':function(self, locals, a,b){return a(self, locals)>=b(self, locals);},
+ '&&':function(self, locals, a,b){return a(self, locals)&&b(self, locals);},
+ '||':function(self, locals, a,b){return a(self, locals)||b(self, locals);},
+ '&':function(self, locals, a,b){return a(self, locals)&b(self, locals);},
+// '|':function(self, locals, a,b){return a|b;},
+ '|':function(self, locals, a,b){return b(self, locals)(self, locals, a(self, locals));},
+ '!':function(self, locals, a){return !a(self, locals);}
+};
+var ESCAPE = {"n":"\n", "f":"\f", "r":"\r", "t":"\t", "v":"\v", "'":"'", '"':'"'};
+
+function lex(text, csp){
+ var tokens = [],
+ token,
+ index = 0,
+ json = [],
+ ch,
+ lastCh = ':'; // can start regexp
+
+ while (index < text.length) {
+ ch = text.charAt(index);
+ if (is('"\'')) {
+ readString(ch);
+ } else if (isNumber(ch) || is('.') && isNumber(peek())) {
+ readNumber();
+ } else if (isIdent(ch)) {
+ readIdent();
+ // identifiers can only be if the preceding char was a { or ,
+ if (was('{,') && json[0]=='{' &&
+ (token=tokens[tokens.length-1])) {
+ token.json = token.text.indexOf('.') == -1;
+ }
+ } else if (is('(){}[].,;:?')) {
+ tokens.push({
+ index:index,
+ text:ch,
+ json:(was(':[,') && is('{[')) || is('}]:,')
+ });
+ if (is('{[')) json.unshift(ch);
+ if (is('}]')) json.shift();
+ index++;
+ } else if (isWhitespace(ch)) {
+ index++;
+ continue;
+ } else {
+ var ch2 = ch + peek(),
+ ch3 = ch2 + peek(2),
+ fn = OPERATORS[ch],
+ fn2 = OPERATORS[ch2],
+ fn3 = OPERATORS[ch3];
+ if (fn3) {
+ tokens.push({index:index, text:ch3, fn:fn3});
+ index += 3;
+ } else if (fn2) {
+ tokens.push({index:index, text:ch2, fn:fn2});
+ index += 2;
+ } else if (fn) {
+ tokens.push({index:index, text:ch, fn:fn, json: was('[,:') && is('+-')});
+ index += 1;
+ } else {
+ throwError("Unexpected next character ", index, index+1);
+ }
+ }
+ lastCh = ch;
+ }
+ return tokens;
+
+ function is(chars) {
+ return chars.indexOf(ch) != -1;
+ }
+
+ function was(chars) {
+ return chars.indexOf(lastCh) != -1;
+ }
+
+ function peek(i) {
+ var num = i || 1;
+ return index + num < text.length ? text.charAt(index + num) : false;
+ }
+ function isNumber(ch) {
+ return '0' <= ch && ch <= '9';
+ }
+ function isWhitespace(ch) {
+ return ch == ' ' || ch == '\r' || ch == '\t' ||
+ ch == '\n' || ch == '\v' || ch == '\u00A0'; // IE treats non-breaking space as \u00A0
+ }
+ function isIdent(ch) {
+ return 'a' <= ch && ch <= 'z' ||
+ 'A' <= ch && ch <= 'Z' ||
+ '_' == ch || ch == '$';
+ }
+ function isExpOperator(ch) {
+ return ch == '-' || ch == '+' || isNumber(ch);
+ }
+
+ function throwError(error, start, end) {
+ end = end || index;
+ throw Error("Lexer Error: " + error + " at column" +
+ (isDefined(start)
+ ? "s " + start + "-" + index + " [" + text.substring(start, end) + "]"
+ : " " + end) +
+ " in expression [" + text + "].");
+ }
+
+ function readNumber() {
+ var number = "";
+ var start = index;
+ while (index < text.length) {
+ var ch = lowercase(text.charAt(index));
+ if (ch == '.' || isNumber(ch)) {
+ number += ch;
+ } else {
+ var peekCh = peek();
+ if (ch == 'e' && isExpOperator(peekCh)) {
+ number += ch;
+ } else if (isExpOperator(ch) &&
+ peekCh && isNumber(peekCh) &&
+ number.charAt(number.length - 1) == 'e') {
+ number += ch;
+ } else if (isExpOperator(ch) &&
+ (!peekCh || !isNumber(peekCh)) &&
+ number.charAt(number.length - 1) == 'e') {
+ throwError('Invalid exponent');
+ } else {
+ break;
+ }
+ }
+ index++;
+ }
+ number = 1 * number;
+ tokens.push({index:start, text:number, json:true,
+ fn:function() {return number;}});
+ }
+ function readIdent() {
+ var ident = "",
+ start = index,
+ lastDot, peekIndex, methodName, ch;
+
+ while (index < text.length) {
+ ch = text.charAt(index);
+ if (ch == '.' || isIdent(ch) || isNumber(ch)) {
+ if (ch == '.') lastDot = index;
+ ident += ch;
+ } else {
+ break;
+ }
+ index++;
+ }
+
+ //check if this is not a method invocation and if it is back out to last dot
+ if (lastDot) {
+ peekIndex = index;
+ while(peekIndex < text.length) {
+ ch = text.charAt(peekIndex);
+ if (ch == '(') {
+ methodName = ident.substr(lastDot - start + 1);
+ ident = ident.substr(0, lastDot - start);
+ index = peekIndex;
+ break;
+ }
+ if(isWhitespace(ch)) {
+ peekIndex++;
+ } else {
+ break;
+ }
+ }
+ }
+
+
+ var token = {
+ index:start,
+ text:ident
+ };
+
+ if (OPERATORS.hasOwnProperty(ident)) {
+ token.fn = token.json = OPERATORS[ident];
+ } else {
+ var getter = getterFn(ident, csp);
+ token.fn = extend(function(self, locals) {
+ return (getter(self, locals));
+ }, {
+ assign: function(self, value) {
+ return setter(self, ident, value);
+ }
+ });
+ }
+
+ tokens.push(token);
+
+ if (methodName) {
+ tokens.push({
+ index:lastDot,
+ text: '.',
+ json: false
+ });
+ tokens.push({
+ index: lastDot + 1,
+ text: methodName,
+ json: false
+ });
+ }
+ }
+
+ function readString(quote) {
+ var start = index;
+ index++;
+ var string = "";
+ var rawString = quote;
+ var escape = false;
+ while (index < text.length) {
+ var ch = text.charAt(index);
+ rawString += ch;
+ if (escape) {
+ if (ch == 'u') {
+ var hex = text.substring(index + 1, index + 5);
+ if (!hex.match(/[\da-f]{4}/i))
+ throwError( "Invalid unicode escape [\\u" + hex + "]");
+ index += 4;
+ string += String.fromCharCode(parseInt(hex, 16));
+ } else {
+ var rep = ESCAPE[ch];
+ if (rep) {
+ string += rep;
+ } else {
+ string += ch;
+ }
+ }
+ escape = false;
+ } else if (ch == '\\') {
+ escape = true;
+ } else if (ch == quote) {
+ index++;
+ tokens.push({
+ index:start,
+ text:rawString,
+ string:string,
+ json:true,
+ fn:function() { return string; }
+ });
+ return;
+ } else {
+ string += ch;
+ }
+ index++;
+ }
+ throwError("Unterminated quote", start);
+ }
+}
+
+/////////////////////////////////////////
+
+function parser(text, json, $filter, csp){
+ var ZERO = valueFn(0),
+ value,
+ tokens = lex(text, csp),
+ assignment = _assignment,
+ functionCall = _functionCall,
+ fieldAccess = _fieldAccess,
+ objectIndex = _objectIndex,
+ filterChain = _filterChain;
+
+ if(json){
+ // The extra level of aliasing is here, just in case the lexer misses something, so that
+ // we prevent any accidental execution in JSON.
+ assignment = logicalOR;
+ functionCall =
+ fieldAccess =
+ objectIndex =
+ filterChain =
+ function() { throwError("is not valid json", {text:text, index:0}); };
+ value = primary();
+ } else {
+ value = statements();
+ }
+ if (tokens.length !== 0) {
+ throwError("is an unexpected token", tokens[0]);
+ }
+ value.literal = !!value.literal;
+ value.constant = !!value.constant;
+ return value;
+
+ ///////////////////////////////////
+ function throwError(msg, token) {
+ throw Error("Syntax Error: Token '" + token.text +
+ "' " + msg + " at column " +
+ (token.index + 1) + " of the expression [" +
+ text + "] starting at [" + text.substring(token.index) + "].");
+ }
+
+ function peekToken() {
+ if (tokens.length === 0)
+ throw Error("Unexpected end of expression: " + text);
+ return tokens[0];
+ }
+
+ function peek(e1, e2, e3, e4) {
+ if (tokens.length > 0) {
+ var token = tokens[0];
+ var t = token.text;
+ if (t==e1 || t==e2 || t==e3 || t==e4 ||
+ (!e1 && !e2 && !e3 && !e4)) {
+ return token;
+ }
+ }
+ return false;
+ }
+
+ function expect(e1, e2, e3, e4){
+ var token = peek(e1, e2, e3, e4);
+ if (token) {
+ if (json && !token.json) {
+ throwError("is not valid json", token);
+ }
+ tokens.shift();
+ return token;
+ }
+ return false;
+ }
+
+ function consume(e1){
+ if (!expect(e1)) {
+ throwError("is unexpected, expecting [" + e1 + "]", peek());
+ }
+ }
+
+ function unaryFn(fn, right) {
+ return extend(function(self, locals) {
+ return fn(self, locals, right);
+ }, {
+ constant:right.constant
+ });
+ }
+
+ function ternaryFn(left, middle, right){
+ return extend(function(self, locals){
+ return left(self, locals) ? middle(self, locals) : right(self, locals);
+ }, {
+ constant: left.constant && middle.constant && right.constant
+ });
+ }
+
+ function binaryFn(left, fn, right) {
+ return extend(function(self, locals) {
+ return fn(self, locals, left, right);
+ }, {
+ constant:left.constant && right.constant
+ });
+ }
+
+ function statements() {
+ var statements = [];
+ while(true) {
+ if (tokens.length > 0 && !peek('}', ')', ';', ']'))
+ statements.push(filterChain());
+ if (!expect(';')) {
+ // optimize for the common case where there is only one statement.
+ // TODO(size): maybe we should not support multiple statements?
+ return statements.length == 1
+ ? statements[0]
+ : function(self, locals){
+ var value;
+ for ( var i = 0; i < statements.length; i++) {
+ var statement = statements[i];
+ if (statement)
+ value = statement(self, locals);
+ }
+ return value;
+ };
+ }
+ }
+ }
+
+ function _filterChain() {
+ var left = expression();
+ var token;
+ while(true) {
+ if ((token = expect('|'))) {
+ left = binaryFn(left, token.fn, filter());
+ } else {
+ return left;
+ }
+ }
+ }
+
+ function filter() {
+ var token = expect();
+ var fn = $filter(token.text);
+ var argsFn = [];
+ while(true) {
+ if ((token = expect(':'))) {
+ argsFn.push(expression());
+ } else {
+ var fnInvoke = function(self, locals, input){
+ var args = [input];
+ for ( var i = 0; i < argsFn.length; i++) {
+ args.push(argsFn[i](self, locals));
+ }
+ return fn.apply(self, args);
+ };
+ return function() {
+ return fnInvoke;
+ };
+ }
+ }
+ }
+
+ function expression() {
+ return assignment();
+ }
+
+ function _assignment() {
+ var left = ternary();
+ var right;
+ var token;
+ if ((token = expect('='))) {
+ if (!left.assign) {
+ throwError("implies assignment but [" +
+ text.substring(0, token.index) + "] can not be assigned to", token);
+ }
+ right = ternary();
+ return function(scope, locals){
+ return left.assign(scope, right(scope, locals), locals);
+ };
+ } else {
+ return left;
+ }
+ }
+
+ function ternary() {
+ var left = logicalOR();
+ var middle;
+ var token;
+ if((token = expect('?'))){
+ middle = ternary();
+ if((token = expect(':'))){
+ return ternaryFn(left, middle, ternary());
+ }
+ else {
+ throwError('expected :', token);
+ }
+ }
+ else {
+ return left;
+ }
+ }
+
+ function logicalOR() {
+ var left = logicalAND();
+ var token;
+ while(true) {
+ if ((token = expect('||'))) {
+ left = binaryFn(left, token.fn, logicalAND());
+ } else {
+ return left;
+ }
+ }
+ }
+
+ function logicalAND() {
+ var left = equality();
+ var token;
+ if ((token = expect('&&'))) {
+ left = binaryFn(left, token.fn, logicalAND());
+ }
+ return left;
+ }
+
+ function equality() {
+ var left = relational();
+ var token;
+ if ((token = expect('==','!=','===','!=='))) {
+ left = binaryFn(left, token.fn, equality());
+ }
+ return left;
+ }
+
+ function relational() {
+ var left = additive();
+ var token;
+ if ((token = expect('<', '>', '<=', '>='))) {
+ left = binaryFn(left, token.fn, relational());
+ }
+ return left;
+ }
+
+ function additive() {
+ var left = multiplicative();
+ var token;
+ while ((token = expect('+','-'))) {
+ left = binaryFn(left, token.fn, multiplicative());
+ }
+ return left;
+ }
+
+ function multiplicative() {
+ var left = unary();
+ var token;
+ while ((token = expect('*','/','%'))) {
+ left = binaryFn(left, token.fn, unary());
+ }
+ return left;
+ }
+
+ function unary() {
+ var token;
+ if (expect('+')) {
+ return primary();
+ } else if ((token = expect('-'))) {
+ return binaryFn(ZERO, token.fn, unary());
+ } else if ((token = expect('!'))) {
+ return unaryFn(token.fn, unary());
+ } else {
+ return primary();
+ }
+ }
+
+
+ function primary() {
+ var primary;
+ if (expect('(')) {
+ primary = filterChain();
+ consume(')');
+ } else if (expect('[')) {
+ primary = arrayDeclaration();
+ } else if (expect('{')) {
+ primary = object();
+ } else {
+ var token = expect();
+ primary = token.fn;
+ if (!primary) {
+ throwError("not a primary expression", token);
+ }
+ if (token.json) {
+ primary.constant = primary.literal = true;
+ }
+ }
+
+ var next, context;
+ while ((next = expect('(', '[', '.'))) {
+ if (next.text === '(') {
+ primary = functionCall(primary, context);
+ context = null;
+ } else if (next.text === '[') {
+ context = primary;
+ primary = objectIndex(primary);
+ } else if (next.text === '.') {
+ context = primary;
+ primary = fieldAccess(primary);
+ } else {
+ throwError("IMPOSSIBLE");
+ }
+ }
+ return primary;
+ }
+
+ function _fieldAccess(object) {
+ var field = expect().text;
+ var getter = getterFn(field, csp);
+ return extend(
+ function(scope, locals, self) {
+ return getter(self || object(scope, locals), locals);
+ },
+ {
+ assign:function(scope, value, locals) {
+ return setter(object(scope, locals), field, value);
+ }
+ }
+ );
+ }
+
+ function _objectIndex(obj) {
+ var indexFn = expression();
+ consume(']');
+ return extend(
+ function(self, locals){
+ var o = obj(self, locals),
+ i = indexFn(self, locals),
+ v, p;
+
+ if (!o) return undefined;
+ v = o[i];
+ if (v && v.then) {
+ p = v;
+ if (!('$$v' in v)) {
+ p.$$v = undefined;
+ p.then(function(val) { p.$$v = val; });
+ }
+ v = v.$$v;
+ }
+ return v;
+ }, {
+ assign:function(self, value, locals){
+ return obj(self, locals)[indexFn(self, locals)] = value;
+ }
+ });
+ }
+
+ function _functionCall(fn, contextGetter) {
+ var argsFn = [];
+ if (peekToken().text != ')') {
+ do {
+ argsFn.push(expression());
+ } while (expect(','));
+ }
+ consume(')');
+ return function(scope, locals){
+ var args = [],
+ context = contextGetter ? contextGetter(scope, locals) : scope;
+
+ for ( var i = 0; i < argsFn.length; i++) {
+ args.push(argsFn[i](scope, locals));
+ }
+ var fnPtr = fn(scope, locals, context) || noop;
+ // IE stupidity!
+ return fnPtr.apply
+ ? fnPtr.apply(context, args)
+ : fnPtr(args[0], args[1], args[2], args[3], args[4]);
+ };
+ }
+
+ // This is used with json array declaration
+ function arrayDeclaration () {
+ var elementFns = [];
+ var allConstant = true;
+ if (peekToken().text != ']') {
+ do {
+ var elementFn = expression();
+ elementFns.push(elementFn);
+ if (!elementFn.constant) {
+ allConstant = false;
+ }
+ } while (expect(','));
+ }
+ consume(']');
+ return extend(function(self, locals){
+ var array = [];
+ for ( var i = 0; i < elementFns.length; i++) {
+ array.push(elementFns[i](self, locals));
+ }
+ return array;
+ }, {
+ literal:true,
+ constant:allConstant
+ });
+ }
+
+ function object () {
+ var keyValues = [];
+ var allConstant = true;
+ if (peekToken().text != '}') {
+ do {
+ var token = expect(),
+ key = token.string || token.text;
+ consume(":");
+ var value = expression();
+ keyValues.push({key:key, value:value});
+ if (!value.constant) {
+ allConstant = false;
+ }
+ } while (expect(','));
+ }
+ consume('}');
+ return extend(function(self, locals){
+ var object = {};
+ for ( var i = 0; i < keyValues.length; i++) {
+ var keyValue = keyValues[i];
+ object[keyValue.key] = keyValue.value(self, locals);
+ }
+ return object;
+ }, {
+ literal:true,
+ constant:allConstant
+ });
+ }
+}
+
+//////////////////////////////////////////////////
+// Parser helper functions
+//////////////////////////////////////////////////
+
+function setter(obj, path, setValue) {
+ var element = path.split('.');
+ for (var i = 0; element.length > 1; i++) {
+ var key = element.shift();
+ var propertyObj = obj[key];
+ if (!propertyObj) {
+ propertyObj = {};
+ obj[key] = propertyObj;
+ }
+ obj = propertyObj;
+ }
+ obj[element.shift()] = setValue;
+ return setValue;
+}
+
+/**
+ * Return the value accessible from the object by path. Any undefined traversals are ignored
+ * @param {Object} obj starting object
+ * @param {string} path path to traverse
+ * @param {boolean=true} bindFnToScope
+ * @returns value as accessible by path
+ */
+//TODO(misko): this function needs to be removed
+function getter(obj, path, bindFnToScope) {
+ if (!path) return obj;
+ var keys = path.split('.');
+ var key;
+ var lastInstance = obj;
+ var len = keys.length;
+
+ for (var i = 0; i < len; i++) {
+ key = keys[i];
+ if (obj) {
+ obj = (lastInstance = obj)[key];
+ }
+ }
+ if (!bindFnToScope && isFunction(obj)) {
+ return bind(lastInstance, obj);
+ }
+ return obj;
+}
+
+var getterFnCache = {};
+
+/**
+ * Implementation of the "Black Hole" variant from:
+ * - http://jsperf.com/angularjs-parse-getter/4
+ * - http://jsperf.com/path-evaluation-simplified/7
+ */
+function cspSafeGetterFn(key0, key1, key2, key3, key4) {
+ return function(scope, locals) {
+ var pathVal = (locals && locals.hasOwnProperty(key0)) ? locals : scope,
+ promise;
+
+ if (pathVal === null || pathVal === undefined) return pathVal;
+
+ pathVal = pathVal[key0];
+ if (pathVal && pathVal.then) {
+ if (!("$$v" in pathVal)) {
+ promise = pathVal;
+ promise.$$v = undefined;
+ promise.then(function(val) { promise.$$v = val; });
+ }
+ pathVal = pathVal.$$v;
+ }
+ if (!key1 || pathVal === null || pathVal === undefined) return pathVal;
+
+ pathVal = pathVal[key1];
+ if (pathVal && pathVal.then) {
+ if (!("$$v" in pathVal)) {
+ promise = pathVal;
+ promise.$$v = undefined;
+ promise.then(function(val) { promise.$$v = val; });
+ }
+ pathVal = pathVal.$$v;
+ }
+ if (!key2 || pathVal === null || pathVal === undefined) return pathVal;
+
+ pathVal = pathVal[key2];
+ if (pathVal && pathVal.then) {
+ if (!("$$v" in pathVal)) {
+ promise = pathVal;
+ promise.$$v = undefined;
+ promise.then(function(val) { promise.$$v = val; });
+ }
+ pathVal = pathVal.$$v;
+ }
+ if (!key3 || pathVal === null || pathVal === undefined) return pathVal;
+
+ pathVal = pathVal[key3];
+ if (pathVal && pathVal.then) {
+ if (!("$$v" in pathVal)) {
+ promise = pathVal;
+ promise.$$v = undefined;
+ promise.then(function(val) { promise.$$v = val; });
+ }
+ pathVal = pathVal.$$v;
+ }
+ if (!key4 || pathVal === null || pathVal === undefined) return pathVal;
+
+ pathVal = pathVal[key4];
+ if (pathVal && pathVal.then) {
+ if (!("$$v" in pathVal)) {
+ promise = pathVal;
+ promise.$$v = undefined;
+ promise.then(function(val) { promise.$$v = val; });
+ }
+ pathVal = pathVal.$$v;
+ }
+ return pathVal;
+ };
+}
+
+function getterFn(path, csp) {
+ if (getterFnCache.hasOwnProperty(path)) {
+ return getterFnCache[path];
+ }
+
+ var pathKeys = path.split('.'),
+ pathKeysLength = pathKeys.length,
+ fn;
+
+ if (csp) {
+ fn = (pathKeysLength < 6)
+ ? cspSafeGetterFn(pathKeys[0], pathKeys[1], pathKeys[2], pathKeys[3], pathKeys[4])
+ : function(scope, locals) {
+ var i = 0, val;
+ do {
+ val = cspSafeGetterFn(
+ pathKeys[i++], pathKeys[i++], pathKeys[i++], pathKeys[i++], pathKeys[i++]
+ )(scope, locals);
+
+ locals = undefined; // clear after first iteration
+ scope = val;
+ } while (i < pathKeysLength);
+ return val;
+ }
+ } else {
+ var code = 'var l, fn, p;\n';
+ forEach(pathKeys, function(key, index) {
+ code += 'if(s === null || s === undefined) return s;\n' +
+ 'l=s;\n' +
+ 's='+ (index
+ // we simply dereference 's' on any .dot notation
+ ? 's'
+ // but if we are first then we check locals first, and if so read it first
+ : '((k&&k.hasOwnProperty("' + key + '"))?k:s)') + '["' + key + '"]' + ';\n' +
+ 'if (s && s.then) {\n' +
+ ' if (!("$$v" in s)) {\n' +
+ ' p=s;\n' +
+ ' p.$$v = undefined;\n' +
+ ' p.then(function(v) {p.$$v=v;});\n' +
+ '}\n' +
+ ' s=s.$$v\n' +
+ '}\n';
+ });
+ code += 'return s;';
+ fn = Function('s', 'k', code); // s=scope, k=locals
+ fn.toString = function() { return code; };
+ }
+
+ return getterFnCache[path] = fn;
+}
+
+///////////////////////////////////
+
+/**
+ * @ngdoc function
+ * @name ng.$parse
+ * @function
+ *
+ * @description
+ *
+ * Converts Angular {@link guide/expression expression} into a function.
+ *
+ *
+ *
+ *
+ * @param {string} expression String expression to compile.
+ * @returns {function(context, locals)} a function which represents the compiled expression:
+ *
+ * * `context` – `{object}` – an object against which any expressions embedded in the strings
+ * are evaluated against (typically a scope object).
+ * * `locals` – `{object=}` – local variables context object, useful for overriding values in
+ * `context`.
+ *
+ * The returned function also has the following properties:
+ * * `literal` – `{boolean}` – whether the expression's top-level node is a JavaScript
+ * literal.
+ * * `constant` – `{boolean}` – whether the expression is made entirely of JavaScript
+ * constant literals.
+ * * `assign` – `{?function(context, value)}` – if the expression is assignable, this will be
+ * set to a function to change its value on the given context.
+ *
+ */
+function $ParseProvider() {
+ var cache = {};
+ this.$get = ['$filter', '$sniffer', function($filter, $sniffer) {
+ return function(exp) {
+ switch(typeof exp) {
+ case 'string':
+ return cache.hasOwnProperty(exp)
+ ? cache[exp]
+ : cache[exp] = parser(exp, false, $filter, $sniffer.csp);
+ case 'function':
+ return exp;
+ default:
+ return noop;
+ }
+ };
+ }];
+}
+
+/**
+ * @ngdoc service
+ * @name ng.$q
+ * @requires $rootScope
+ *
+ * @description
+ * A promise/deferred implementation inspired by [Kris Kowal's Q](https://github.com/kriskowal/q).
+ *
+ * [The CommonJS Promise proposal](http://wiki.commonjs.org/wiki/Promises) describes a promise as an
+ * interface for interacting with an object that represents the result of an action that is
+ * performed asynchronously, and may or may not be finished at any given point in time.
+ *
+ * From the perspective of dealing with error handling, deferred and promise APIs are to
+ * asynchronous programming what `try`, `catch` and `throw` keywords are to synchronous programming.
+ *
+ *
+ * // for the purpose of this example let's assume that variables `$q` and `scope` are
+ * // available in the current lexical scope (they could have been injected or passed in).
+ *
+ * function asyncGreet(name) {
+ * var deferred = $q.defer();
+ *
+ * setTimeout(function() {
+ * // since this fn executes async in a future turn of the event loop, we need to wrap
+ * // our code into an $apply call so that the model changes are properly observed.
+ * scope.$apply(function() {
+ * if (okToGreet(name)) {
+ * deferred.resolve('Hello, ' + name + '!');
+ * } else {
+ * deferred.reject('Greeting ' + name + ' is not allowed.');
+ * }
+ * });
+ * }, 1000);
+ *
+ * return deferred.promise;
+ * }
+ *
+ * var promise = asyncGreet('Robin Hood');
+ * promise.then(function(greeting) {
+ * alert('Success: ' + greeting);
+ * }, function(reason) {
+ * alert('Failed: ' + reason);
+ * });
+ *
+ *
+ * At first it might not be obvious why this extra complexity is worth the trouble. The payoff
+ * comes in the way of
+ * [guarantees that promise and deferred APIs make](https://github.com/kriskowal/uncommonjs/blob/master/promises/specification.md).
+ *
+ * Additionally the promise api allows for composition that is very hard to do with the
+ * traditional callback ([CPS](http://en.wikipedia.org/wiki/Continuation-passing_style)) approach.
+ * For more on this please see the [Q documentation](https://github.com/kriskowal/q) especially the
+ * section on serial or parallel joining of promises.
+ *
+ *
+ * # The Deferred API
+ *
+ * A new instance of deferred is constructed by calling `$q.defer()`.
+ *
+ * The purpose of the deferred object is to expose the associated Promise instance as well as APIs
+ * that can be used for signaling the successful or unsuccessful completion of the task.
+ *
+ * **Methods**
+ *
+ * - `resolve(value)` – resolves the derived promise with the `value`. If the value is a rejection
+ * constructed via `$q.reject`, the promise will be rejected instead.
+ * - `reject(reason)` – rejects the derived promise with the `reason`. This is equivalent to
+ * resolving it with a rejection constructed via `$q.reject`.
+ *
+ * **Properties**
+ *
+ * - promise – `{Promise}` – promise object associated with this deferred.
+ *
+ *
+ * # The Promise API
+ *
+ * A new promise instance is created when a deferred instance is created and can be retrieved by
+ * calling `deferred.promise`.
+ *
+ * The purpose of the promise object is to allow for interested parties to get access to the result
+ * of the deferred task when it completes.
+ *
+ * **Methods**
+ *
+ * - `then(successCallback, errorCallback)` – regardless of when the promise was or will be resolved
+ * or rejected calls one of the success or error callbacks asynchronously as soon as the result
+ * is available. The callbacks are called with a single argument the result or rejection reason.
+ *
+ * This method *returns a new promise* which is resolved or rejected via the return value of the
+ * `successCallback` or `errorCallback`.
+ *
+ * - `always(callback)` – allows you to observe either the fulfillment or rejection of a promise,
+ * but to do so without modifying the final value. This is useful to release resources or do some
+ * clean-up that needs to be done whether the promise was rejected or resolved. See the [full
+ * specification](https://github.com/kriskowal/q/wiki/API-Reference#promisefinallycallback) for
+ * more information.
+ *
+ * # Chaining promises
+ *
+ * Because calling `then` api of a promise returns a new derived promise, it is easily possible
+ * to create a chain of promises:
+ *
+ *
+ * promiseB = promiseA.then(function(result) {
+ * return result + 1;
+ * });
+ *
+ * // promiseB will be resolved immediately after promiseA is resolved and its value will be
+ * // the result of promiseA incremented by 1
+ *
+ *
+ * It is possible to create chains of any length and since a promise can be resolved with another
+ * promise (which will defer its resolution further), it is possible to pause/defer resolution of
+ * the promises at any point in the chain. This makes it possible to implement powerful apis like
+ * $http's response interceptors.
+ *
+ *
+ * # Differences between Kris Kowal's Q and $q
+ *
+ * There are three main differences:
+ *
+ * - $q is integrated with the {@link ng.$rootScope.Scope} Scope model observation
+ * mechanism in angular, which means faster propagation of resolution or rejection into your
+ * models and avoiding unnecessary browser repaints, which would result in flickering UI.
+ * - $q promises are recognized by the templating engine in angular, which means that in templates
+ * you can treat promises attached to a scope as if they were the resulting values.
+ * - Q has many more features than $q, but that comes at a cost of bytes. $q is tiny, but contains
+ * all the important functionality needed for common async tasks.
+ *
+ * # Testing
+ *
+ *
+ * it('should simulate promise', inject(function($q, $rootScope) {
+ * var deferred = $q.defer();
+ * var promise = deferred.promise;
+ * var resolvedValue;
+ *
+ * promise.then(function(value) { resolvedValue = value; });
+ * expect(resolvedValue).toBeUndefined();
+ *
+ * // Simulate resolving of promise
+ * deferred.resolve(123);
+ * // Note that the 'then' function does not get called synchronously.
+ * // This is because we want the promise API to always be async, whether or not
+ * // it got called synchronously or asynchronously.
+ * expect(resolvedValue).toBeUndefined();
+ *
+ * // Propagate promise resolution to 'then' functions using $apply().
+ * $rootScope.$apply();
+ * expect(resolvedValue).toEqual(123);
+ * });
+ *
+ */
+function $QProvider() {
+
+ this.$get = ['$rootScope', '$exceptionHandler', function($rootScope, $exceptionHandler) {
+ return qFactory(function(callback) {
+ $rootScope.$evalAsync(callback);
+ }, $exceptionHandler);
+ }];
+}
+
+
+/**
+ * Constructs a promise manager.
+ *
+ * @param {function(function)} nextTick Function for executing functions in the next turn.
+ * @param {function(...*)} exceptionHandler Function into which unexpected exceptions are passed for
+ * debugging purposes.
+ * @returns {object} Promise manager.
+ */
+function qFactory(nextTick, exceptionHandler) {
+
+ /**
+ * @ngdoc
+ * @name ng.$q#defer
+ * @methodOf ng.$q
+ * @description
+ * Creates a `Deferred` object which represents a task which will finish in the future.
+ *
+ * @returns {Deferred} Returns a new instance of deferred.
+ */
+ var defer = function() {
+ var pending = [],
+ value, deferred;
+
+ deferred = {
+
+ resolve: function(val) {
+ if (pending) {
+ var callbacks = pending;
+ pending = undefined;
+ value = ref(val);
+
+ if (callbacks.length) {
+ nextTick(function() {
+ var callback;
+ for (var i = 0, ii = callbacks.length; i < ii; i++) {
+ callback = callbacks[i];
+ value.then(callback[0], callback[1]);
+ }
+ });
+ }
+ }
+ },
+
+
+ reject: function(reason) {
+ deferred.resolve(reject(reason));
+ },
+
+
+ promise: {
+ then: function(callback, errback) {
+ var result = defer();
+
+ var wrappedCallback = function(value) {
+ try {
+ result.resolve((callback || defaultCallback)(value));
+ } catch(e) {
+ exceptionHandler(e);
+ result.reject(e);
+ }
+ };
+
+ var wrappedErrback = function(reason) {
+ try {
+ result.resolve((errback || defaultErrback)(reason));
+ } catch(e) {
+ exceptionHandler(e);
+ result.reject(e);
+ }
+ };
+
+ if (pending) {
+ pending.push([wrappedCallback, wrappedErrback]);
+ } else {
+ value.then(wrappedCallback, wrappedErrback);
+ }
+
+ return result.promise;
+ },
+ always: function(callback) {
+
+ function makePromise(value, resolved) {
+ var result = defer();
+ if (resolved) {
+ result.resolve(value);
+ } else {
+ result.reject(value);
+ }
+ return result.promise;
+ }
+
+ function handleCallback(value, isResolved) {
+ var callbackOutput = null;
+ try {
+ callbackOutput = (callback ||defaultCallback)();
+ } catch(e) {
+ return makePromise(e, false);
+ }
+ if (callbackOutput && callbackOutput.then) {
+ return callbackOutput.then(function() {
+ return makePromise(value, isResolved);
+ }, function(error) {
+ return makePromise(error, false);
+ });
+ } else {
+ return makePromise(value, isResolved);
+ }
+ }
+
+ return this.then(function(value) {
+ return handleCallback(value, true);
+ }, function(error) {
+ return handleCallback(error, false);
+ });
+ }
+ }
+ };
+
+ return deferred;
+ };
+
+
+ var ref = function(value) {
+ if (value && value.then) return value;
+ return {
+ then: function(callback) {
+ var result = defer();
+ nextTick(function() {
+ result.resolve(callback(value));
+ });
+ return result.promise;
+ }
+ };
+ };
+
+
+ /**
+ * @ngdoc
+ * @name ng.$q#reject
+ * @methodOf ng.$q
+ * @description
+ * Creates a promise that is resolved as rejected with the specified `reason`. This api should be
+ * used to forward rejection in a chain of promises. If you are dealing with the last promise in
+ * a promise chain, you don't need to worry about it.
+ *
+ * When comparing deferreds/promises to the familiar behavior of try/catch/throw, think of
+ * `reject` as the `throw` keyword in JavaScript. This also means that if you "catch" an error via
+ * a promise error callback and you want to forward the error to the promise derived from the
+ * current promise, you have to "rethrow" the error by returning a rejection constructed via
+ * `reject`.
+ *
+ *
+ * promiseB = promiseA.then(function(result) {
+ * // success: do something and resolve promiseB
+ * // with the old or a new result
+ * return result;
+ * }, function(reason) {
+ * // error: handle the error if possible and
+ * // resolve promiseB with newPromiseOrValue,
+ * // otherwise forward the rejection to promiseB
+ * if (canHandle(reason)) {
+ * // handle the error and recover
+ * return newPromiseOrValue;
+ * }
+ * return $q.reject(reason);
+ * });
+ *
+ *
+ * @param {*} reason Constant, message, exception or an object representing the rejection reason.
+ * @returns {Promise} Returns a promise that was already resolved as rejected with the `reason`.
+ */
+ var reject = function(reason) {
+ return {
+ then: function(callback, errback) {
+ var result = defer();
+ nextTick(function() {
+ result.resolve((errback || defaultErrback)(reason));
+ });
+ return result.promise;
+ }
+ };
+ };
+
+
+ /**
+ * @ngdoc
+ * @name ng.$q#when
+ * @methodOf ng.$q
+ * @description
+ * Wraps an object that might be a value or a (3rd party) then-able promise into a $q promise.
+ * This is useful when you are dealing with an object that might or might not be a promise, or if
+ * the promise comes from a source that can't be trusted.
+ *
+ * @param {*} value Value or a promise
+ * @returns {Promise} Returns a promise of the passed value or promise
+ */
+ var when = function(value, callback, errback) {
+ var result = defer(),
+ done;
+
+ var wrappedCallback = function(value) {
+ try {
+ return (callback || defaultCallback)(value);
+ } catch (e) {
+ exceptionHandler(e);
+ return reject(e);
+ }
+ };
+
+ var wrappedErrback = function(reason) {
+ try {
+ return (errback || defaultErrback)(reason);
+ } catch (e) {
+ exceptionHandler(e);
+ return reject(e);
+ }
+ };
+
+ nextTick(function() {
+ ref(value).then(function(value) {
+ if (done) return;
+ done = true;
+ result.resolve(ref(value).then(wrappedCallback, wrappedErrback));
+ }, function(reason) {
+ if (done) return;
+ done = true;
+ result.resolve(wrappedErrback(reason));
+ });
+ });
+
+ return result.promise;
+ };
+
+
+ function defaultCallback(value) {
+ return value;
+ }
+
+
+ function defaultErrback(reason) {
+ return reject(reason);
+ }
+
+
+ /**
+ * @ngdoc
+ * @name ng.$q#all
+ * @methodOf ng.$q
+ * @description
+ * Combines multiple promises into a single promise that is resolved when all of the input
+ * promises are resolved.
+ *
+ * @param {Array.|Object.} promises An array or hash of promises.
+ * @returns {Promise} Returns a single promise that will be resolved with an array/hash of values,
+ * each value corresponding to the promise at the same index/key in the `promises` array/hash. If any of
+ * the promises is resolved with a rejection, this resulting promise will be resolved with the
+ * same rejection.
+ */
+ function all(promises) {
+ var deferred = defer(),
+ counter = 0,
+ results = isArray(promises) ? [] : {};
+
+ forEach(promises, function(promise, key) {
+ counter++;
+ ref(promise).then(function(value) {
+ if (results.hasOwnProperty(key)) return;
+ results[key] = value;
+ if (!(--counter)) deferred.resolve(results);
+ }, function(reason) {
+ if (results.hasOwnProperty(key)) return;
+ deferred.reject(reason);
+ });
+ });
+
+ if (counter === 0) {
+ deferred.resolve(results);
+ }
+
+ return deferred.promise;
+ }
+
+ return {
+ defer: defer,
+ reject: reject,
+ when: when,
+ all: all
+ };
+}
+
+/**
+ * @ngdoc object
+ * @name ng.$routeProvider
+ * @function
+ *
+ * @description
+ *
+ * Used for configuring routes. See {@link ng.$route $route} for an example.
+ */
+function $RouteProvider(){
+ var routes = {};
+
+ /**
+ * @ngdoc method
+ * @name ng.$routeProvider#when
+ * @methodOf ng.$routeProvider
+ *
+ * @param {string} path Route path (matched against `$location.path`). If `$location.path`
+ * contains redundant trailing slash or is missing one, the route will still match and the
+ * `$location.path` will be updated to add or drop the trailing slash to exactly match the
+ * route definition.
+ *
+ * * `path` can contain named groups starting with a colon (`:name`). All characters up
+ * to the next slash are matched and stored in `$routeParams` under the given `name`
+ * when the route matches.
+ * * `path` can contain named groups starting with a star (`*name`). All characters are
+ * eagerly stored in `$routeParams` under the given `name` when the route matches.
+ *
+ * For example, routes like `/color/:color/largecode/*largecode/edit` will match
+ * `/color/brown/largecode/code/with/slashs/edit` and extract:
+ *
+ * * `color: brown`
+ * * `largecode: code/with/slashs`.
+ *
+ *
+ * @param {Object} route Mapping information to be assigned to `$route.current` on route
+ * match.
+ *
+ * Object properties:
+ *
+ * - `controller` – `{(string|function()=}` – Controller fn that should be associated with newly
+ * created scope or the name of a {@link angular.Module#controller registered controller}
+ * if passed as a string.
+ * - `controllerAs` – `{string=}` – A controller alias name. If present the controller will be
+ * published to scope under the `controllerAs` name.
+ * - `template` – `{string=|function()=}` – html template as a string or function that returns
+ * an html template as a string which should be used by {@link ng.directive:ngView ngView} or
+ * {@link ng.directive:ngInclude ngInclude} directives.
+ * This property takes precedence over `templateUrl`.
+ *
+ * If `template` is a function, it will be called with the following parameters:
+ *
+ * - `{Array.