From ee54807bb6d3c86870cde2fcc4a69fa74da57dea Mon Sep 17 00:00:00 2001 From: Pratik Borsadiya Date: Thu, 30 Aug 2018 14:50:26 +0530 Subject: [PATCH 01/16] Initialize NPM & Add prettier --- .gitignore | 1 + .prettierrc | 3 +++ package-lock.json | 14 ++++++++++++++ package.json | 21 +++++++++++++++++++++ 4 files changed, 39 insertions(+) create mode 100644 .prettierrc create mode 100644 package-lock.json create mode 100644 package.json diff --git a/.gitignore b/.gitignore index f5f2df92..cf0bb9c0 100644 --- a/.gitignore +++ b/.gitignore @@ -2,3 +2,4 @@ .idea .git debug.log +node_modules \ No newline at end of file diff --git a/.prettierrc b/.prettierrc new file mode 100644 index 00000000..c61c0ccb --- /dev/null +++ b/.prettierrc @@ -0,0 +1,3 @@ +{ + "printWidth": 100 +} \ No newline at end of file diff --git a/package-lock.json b/package-lock.json new file mode 100644 index 00000000..2cb55e95 --- /dev/null +++ b/package-lock.json @@ -0,0 +1,14 @@ +{ + "name": "webui-aria2", + "version": "1.0.0", + "lockfileVersion": 1, + "requires": true, + "dependencies": { + "prettier": { + "version": "1.14.2", + "resolved": "https://registry.npmjs.org/prettier/-/prettier-1.14.2.tgz", + "integrity": "sha512-McHPg0n1pIke+A/4VcaS2en+pTNjy4xF+Uuq86u/5dyDO59/TtFZtQ708QIRkEZ3qwKz3GVkVa6mpxK/CpB8Rg==", + "dev": true + } + } +} diff --git a/package.json b/package.json new file mode 100644 index 00000000..9bdd973d --- /dev/null +++ b/package.json @@ -0,0 +1,21 @@ +{ + "name": "webui-aria2", + "version": "1.0.0", + "description": "The aim for this project is to create the worlds best and hottest interface to interact with aria2.", + "dependencies": {}, + "devDependencies": { + "prettier": "^1.14.2" + }, + "scripts": { + "format": "prettier -l --config .prettierrc --write \"**/*{js,css}\" \"!**/*.min.{js,css}\" " + }, + "repository": { + "type": "git", + "url": "git+https://github.com/ziahamza/webui-aria2.git" + }, + "license": "MIT", + "bugs": { + "url": "https://github.com/ziahamza/webui-aria2/issues" + }, + "homepage": "https://github.com/ziahamza/webui-aria2#readme" +} From 499f272ac7bb18a31819b02979c588bfaede0a19 Mon Sep 17 00:00:00 2001 From: Pratik Borsadiya Date: Thu, 30 Aug 2018 15:06:03 +0530 Subject: [PATCH 02/16] Add Git hook to auto format staged files before commit --- .prettierignore | 2 + package-lock.json | 565 ++++++++++++++++++++++++++++++++++++++++++++++ package.json | 21 +- 3 files changed, 581 insertions(+), 7 deletions(-) create mode 100644 .prettierignore diff --git a/.prettierignore b/.prettierignore new file mode 100644 index 00000000..74419728 --- /dev/null +++ b/.prettierignore @@ -0,0 +1,2 @@ +**/*.min.js +**/*.min.css \ No newline at end of file diff --git a/package-lock.json b/package-lock.json index 2cb55e95..40679be4 100644 --- a/package-lock.json +++ b/package-lock.json @@ -4,11 +4,576 @@ "lockfileVersion": 1, "requires": true, "dependencies": { + "ansi-styles": { + "version": "3.2.1", + "resolved": "https://registry.npmjs.org/ansi-styles/-/ansi-styles-3.2.1.tgz", + "integrity": "sha512-VT0ZI6kZRdTh8YyJw3SMbYm/u+NqfsAxEpWO0Pf9sq8/e94WxxOpPKx9FR1FlyCtOVDNOQ+8ntlqFxiRc+r5qA==", + "dev": true, + "requires": { + "color-convert": "^1.9.0" + } + }, + "argparse": { + "version": "1.0.10", + "resolved": "https://registry.npmjs.org/argparse/-/argparse-1.0.10.tgz", + "integrity": "sha512-o5Roy6tNG4SL/FOkCAN6RzjiakZS25RLYFrcMttJqbdd8BWrnA+fGz57iN5Pb06pvBGvl5gQ0B48dJlslXvoTg==", + "dev": true, + "requires": { + "sprintf-js": "~1.0.2" + } + }, + "builtin-modules": { + "version": "1.1.1", + "resolved": "https://registry.npmjs.org/builtin-modules/-/builtin-modules-1.1.1.tgz", + "integrity": "sha1-Jw8HbFpywC9bZaR9+Uxf46J4iS8=", + "dev": true + }, + "chalk": { + "version": "2.4.1", + "resolved": "https://registry.npmjs.org/chalk/-/chalk-2.4.1.tgz", + "integrity": "sha512-ObN6h1v2fTJSmUXoS3nMQ92LbDK9be4TV+6G+omQlGJFdcUX5heKi1LZ1YnRMIgwTLEj3E24bT6tYni50rlCfQ==", + "dev": true, + "requires": { + "ansi-styles": "^3.2.1", + "escape-string-regexp": "^1.0.5", + "supports-color": "^5.3.0" + } + }, + "ci-info": { + "version": "1.4.0", + "resolved": "https://registry.npmjs.org/ci-info/-/ci-info-1.4.0.tgz", + "integrity": "sha512-Oqmw2pVfCl8sCL+1QgMywPfdxPJPkC51y4usw0iiE2S9qnEOAqXy8bwl1CpMpnoU39g4iKJTz6QZj+28FvOnjQ==", + "dev": true + }, + "color-convert": { + "version": "1.9.3", + "resolved": "https://registry.npmjs.org/color-convert/-/color-convert-1.9.3.tgz", + "integrity": "sha512-QfAUtd+vFdAtFQcC8CCyYt1fYWxSqAiK2cSD6zDB8N3cpsEBAvRxp9zOGg6G/SHHJYAT88/az/IuDGALsNVbGg==", + "dev": true, + "requires": { + "color-name": "1.1.3" + } + }, + "color-name": { + "version": "1.1.3", + "resolved": "https://registry.npmjs.org/color-name/-/color-name-1.1.3.tgz", + "integrity": "sha1-p9BVi9icQveV3UIyj3QIMcpTvCU=", + "dev": true + }, + "cosmiconfig": { + "version": "5.0.6", + "resolved": "https://registry.npmjs.org/cosmiconfig/-/cosmiconfig-5.0.6.tgz", + "integrity": "sha512-6DWfizHriCrFWURP1/qyhsiFvYdlJzbCzmtFWh744+KyWsJo5+kPzUZZaMRSSItoYc0pxFX7gEO7ZC1/gN/7AQ==", + "dev": true, + "requires": { + "is-directory": "^0.3.1", + "js-yaml": "^3.9.0", + "parse-json": "^4.0.0" + } + }, + "cross-spawn": { + "version": "5.1.0", + "resolved": "https://registry.npmjs.org/cross-spawn/-/cross-spawn-5.1.0.tgz", + "integrity": "sha1-6L0O/uWPz/b4+UUQoKVUu/ojVEk=", + "dev": true, + "requires": { + "lru-cache": "^4.0.1", + "shebang-command": "^1.2.0", + "which": "^1.2.9" + } + }, + "error-ex": { + "version": "1.3.2", + "resolved": "https://registry.npmjs.org/error-ex/-/error-ex-1.3.2.tgz", + "integrity": "sha512-7dFHNmqeFSEt2ZBsCriorKnn3Z2pj+fd9kmI6QoWw4//DL+icEBfc0U7qJCisqrTsKTjw4fNFy2pW9OqStD84g==", + "dev": true, + "requires": { + "is-arrayish": "^0.2.1" + } + }, + "escape-string-regexp": { + "version": "1.0.5", + "resolved": "https://registry.npmjs.org/escape-string-regexp/-/escape-string-regexp-1.0.5.tgz", + "integrity": "sha1-G2HAViGQqN/2rjuyzwIAyhMLhtQ=", + "dev": true + }, + "esprima": { + "version": "4.0.1", + "resolved": "https://registry.npmjs.org/esprima/-/esprima-4.0.1.tgz", + "integrity": "sha512-eGuFFw7Upda+g4p+QHvnW0RyTX/SVeJBDM/gCtMARO0cLuT2HcEKnTPvhjV6aGeqrCB/sbNop0Kszm0jsaWU4A==", + "dev": true + }, + "execa": { + "version": "0.9.0", + "resolved": "https://registry.npmjs.org/execa/-/execa-0.9.0.tgz", + "integrity": "sha512-BbUMBiX4hqiHZUA5+JujIjNb6TyAlp2D5KLheMjMluwOuzcnylDL4AxZYLLn1n2AGB49eSWwyKvvEQoRpnAtmA==", + "dev": true, + "requires": { + "cross-spawn": "^5.0.1", + "get-stream": "^3.0.0", + "is-stream": "^1.1.0", + "npm-run-path": "^2.0.0", + "p-finally": "^1.0.0", + "signal-exit": "^3.0.0", + "strip-eof": "^1.0.0" + } + }, + "find-up": { + "version": "3.0.0", + "resolved": "https://registry.npmjs.org/find-up/-/find-up-3.0.0.tgz", + "integrity": "sha512-1yD6RmLI1XBfxugvORwlck6f75tYL+iR0jqwsOrOxMZyGYqUuDhJ0l4AXdO1iX/FTs9cBAMEk1gWSEx1kSbylg==", + "dev": true, + "requires": { + "locate-path": "^3.0.0" + } + }, + "get-stdin": { + "version": "6.0.0", + "resolved": "https://registry.npmjs.org/get-stdin/-/get-stdin-6.0.0.tgz", + "integrity": "sha512-jp4tHawyV7+fkkSKyvjuLZswblUtz+SQKzSWnBbii16BuZksJlU1wuBYXY75r+duh/llF1ur6oNwi+2ZzjKZ7g==", + "dev": true + }, + "get-stream": { + "version": "3.0.0", + "resolved": "https://registry.npmjs.org/get-stream/-/get-stream-3.0.0.tgz", + "integrity": "sha1-jpQ9E1jcN1VQVOy+LtsFqhdO3hQ=", + "dev": true + }, + "has-flag": { + "version": "3.0.0", + "resolved": "https://registry.npmjs.org/has-flag/-/has-flag-3.0.0.tgz", + "integrity": "sha1-tdRU3CGZriJWmfNGfloH87lVuv0=", + "dev": true + }, + "hosted-git-info": { + "version": "2.7.1", + "resolved": "https://registry.npmjs.org/hosted-git-info/-/hosted-git-info-2.7.1.tgz", + "integrity": "sha512-7T/BxH19zbcCTa8XkMlbK5lTo1WtgkFi3GvdWEyNuc4Vex7/9Dqbnpsf4JMydcfj9HCg4zUWFTL3Za6lapg5/w==", + "dev": true + }, + "husky": { + "version": "1.0.0-rc.13", + "resolved": "https://registry.npmjs.org/husky/-/husky-1.0.0-rc.13.tgz", + "integrity": "sha512-ZNNoaBgfOHRA05UHS/etBoWFDu65mjPoohPYQwOqb5155KOovBp8LMkMoNK0kn3VYdsm+HWdtuHbD4XjfzlfpQ==", + "dev": true, + "requires": { + "cosmiconfig": "^5.0.2", + "execa": "^0.9.0", + "find-up": "^3.0.0", + "get-stdin": "^6.0.0", + "is-ci": "^1.1.0", + "pkg-dir": "^3.0.0", + "please-upgrade-node": "^3.1.1", + "read-pkg": "^4.0.1", + "run-node": "^1.0.0", + "slash": "^2.0.0" + } + }, + "ignore": { + "version": "3.3.10", + "resolved": "https://registry.npmjs.org/ignore/-/ignore-3.3.10.tgz", + "integrity": "sha512-Pgs951kaMm5GXP7MOvxERINe3gsaVjUWFm+UZPSq9xYriQAksyhg0csnS0KXSNRD5NmNdapXEpjxG49+AKh/ug==", + "dev": true + }, + "is-arrayish": { + "version": "0.2.1", + "resolved": "https://registry.npmjs.org/is-arrayish/-/is-arrayish-0.2.1.tgz", + "integrity": "sha1-d8mYQFJ6qOyxqLppe4BkWnqSap0=", + "dev": true + }, + "is-builtin-module": { + "version": "1.0.0", + "resolved": "https://registry.npmjs.org/is-builtin-module/-/is-builtin-module-1.0.0.tgz", + "integrity": "sha1-VAVy0096wxGfj3bDDLwbHgN6/74=", + "dev": true, + "requires": { + "builtin-modules": "^1.0.0" + } + }, + "is-ci": { + "version": "1.2.0", + "resolved": "https://registry.npmjs.org/is-ci/-/is-ci-1.2.0.tgz", + "integrity": "sha512-plgvKjQtalH2P3Gytb7L61Lmz95g2DlpzFiQyRSFew8WoJKxtKRzrZMeyRN2supblm3Psc8OQGy7Xjb6XG11jw==", + "dev": true, + "requires": { + "ci-info": "^1.3.0" + } + }, + "is-directory": { + "version": "0.3.1", + "resolved": "https://registry.npmjs.org/is-directory/-/is-directory-0.3.1.tgz", + "integrity": "sha1-YTObbyR1/Hcv2cnYP1yFddwVSuE=", + "dev": true + }, + "is-stream": { + "version": "1.1.0", + "resolved": "https://registry.npmjs.org/is-stream/-/is-stream-1.1.0.tgz", + "integrity": "sha1-EtSj3U5o4Lec6428hBc66A2RykQ=", + "dev": true + }, + "isexe": { + "version": "2.0.0", + "resolved": "https://registry.npmjs.org/isexe/-/isexe-2.0.0.tgz", + "integrity": "sha1-6PvzdNxVb/iUehDcsFctYz8s+hA=", + "dev": true + }, + "js-yaml": { + "version": "3.12.0", + "resolved": "https://registry.npmjs.org/js-yaml/-/js-yaml-3.12.0.tgz", + "integrity": "sha512-PIt2cnwmPfL4hKNwqeiuz4bKfnzHTBv6HyVgjahA6mPLwPDzjDWrplJBMjHUFxku/N3FlmrbyPclad+I+4mJ3A==", + "dev": true, + "requires": { + "argparse": "^1.0.7", + "esprima": "^4.0.0" + } + }, + "json-parse-better-errors": { + "version": "1.0.2", + "resolved": "https://registry.npmjs.org/json-parse-better-errors/-/json-parse-better-errors-1.0.2.tgz", + "integrity": "sha512-mrqyZKfX5EhL7hvqcV6WG1yYjnjeuYDzDhhcAAUrq8Po85NBQBJP+ZDUT75qZQ98IkUoBqdkExkukOU7Ts2wrw==", + "dev": true + }, + "locate-path": { + "version": "3.0.0", + "resolved": "https://registry.npmjs.org/locate-path/-/locate-path-3.0.0.tgz", + "integrity": "sha512-7AO748wWnIhNqAuaty2ZWHkQHRSNfPVIsPIfwEOWO22AmaoVrWavlOcMR5nzTLNYvp36X220/maaRsrec1G65A==", + "dev": true, + "requires": { + "p-locate": "^3.0.0", + "path-exists": "^3.0.0" + } + }, + "lru-cache": { + "version": "4.1.3", + "resolved": "https://registry.npmjs.org/lru-cache/-/lru-cache-4.1.3.tgz", + "integrity": "sha512-fFEhvcgzuIoJVUF8fYr5KR0YqxD238zgObTps31YdADwPPAp82a4M8TrckkWyx7ekNlf9aBcVn81cFwwXngrJA==", + "dev": true, + "requires": { + "pseudomap": "^1.0.2", + "yallist": "^2.1.2" + } + }, + "mri": { + "version": "1.1.1", + "resolved": "https://registry.npmjs.org/mri/-/mri-1.1.1.tgz", + "integrity": "sha1-haom09ru7t+A3FmEr5XMXKXK2fE=", + "dev": true + }, + "normalize-package-data": { + "version": "2.4.0", + "resolved": "https://registry.npmjs.org/normalize-package-data/-/normalize-package-data-2.4.0.tgz", + "integrity": "sha512-9jjUFbTPfEy3R/ad/2oNbKtW9Hgovl5O1FvFWKkKblNXoN/Oou6+9+KKohPK13Yc3/TyunyWhJp6gvRNR/PPAw==", + "dev": true, + "requires": { + "hosted-git-info": "^2.1.4", + "is-builtin-module": "^1.0.0", + "semver": "2 || 3 || 4 || 5", + "validate-npm-package-license": "^3.0.1" + } + }, + "npm-run-path": { + "version": "2.0.2", + "resolved": "https://registry.npmjs.org/npm-run-path/-/npm-run-path-2.0.2.tgz", + "integrity": "sha1-NakjLfo11wZ7TLLd8jV7GHFTbF8=", + "dev": true, + "requires": { + "path-key": "^2.0.0" + } + }, + "p-finally": { + "version": "1.0.0", + "resolved": "https://registry.npmjs.org/p-finally/-/p-finally-1.0.0.tgz", + "integrity": "sha1-P7z7FbiZpEEjs0ttzBi3JDNqLK4=", + "dev": true + }, + "p-limit": { + "version": "2.0.0", + "resolved": "https://registry.npmjs.org/p-limit/-/p-limit-2.0.0.tgz", + "integrity": "sha512-fl5s52lI5ahKCernzzIyAP0QAZbGIovtVHGwpcu1Jr/EpzLVDI2myISHwGqK7m8uQFugVWSrbxH7XnhGtvEc+A==", + "dev": true, + "requires": { + "p-try": "^2.0.0" + } + }, + "p-locate": { + "version": "3.0.0", + "resolved": "https://registry.npmjs.org/p-locate/-/p-locate-3.0.0.tgz", + "integrity": "sha512-x+12w/To+4GFfgJhBEpiDcLozRJGegY+Ei7/z0tSLkMmxGZNybVMSfWj9aJn8Z5Fc7dBUNJOOVgPv2H7IwulSQ==", + "dev": true, + "requires": { + "p-limit": "^2.0.0" + } + }, + "p-try": { + "version": "2.0.0", + "resolved": "https://registry.npmjs.org/p-try/-/p-try-2.0.0.tgz", + "integrity": "sha512-hMp0onDKIajHfIkdRk3P4CdCmErkYAxxDtP3Wx/4nZ3aGlau2VKh3mZpcuFkH27WQkL/3WBCPOktzA9ZOAnMQQ==", + "dev": true + }, + "parse-json": { + "version": "4.0.0", + "resolved": "https://registry.npmjs.org/parse-json/-/parse-json-4.0.0.tgz", + "integrity": "sha1-vjX1Qlvh9/bHRxhPmKeIy5lHfuA=", + "dev": true, + "requires": { + "error-ex": "^1.3.1", + "json-parse-better-errors": "^1.0.1" + } + }, + "path-exists": { + "version": "3.0.0", + "resolved": "https://registry.npmjs.org/path-exists/-/path-exists-3.0.0.tgz", + "integrity": "sha1-zg6+ql94yxiSXqfYENe1mwEP1RU=", + "dev": true + }, + "path-key": { + "version": "2.0.1", + "resolved": "https://registry.npmjs.org/path-key/-/path-key-2.0.1.tgz", + "integrity": "sha1-QRyttXTFoUDTpLGRDUDYDMn0C0A=", + "dev": true + }, + "pify": { + "version": "3.0.0", + "resolved": "https://registry.npmjs.org/pify/-/pify-3.0.0.tgz", + "integrity": "sha1-5aSs0sEB/fPZpNB/DbxNtJ3SgXY=", + "dev": true + }, + "pkg-dir": { + "version": "3.0.0", + "resolved": "https://registry.npmjs.org/pkg-dir/-/pkg-dir-3.0.0.tgz", + "integrity": "sha512-/E57AYkoeQ25qkxMj5PBOVgF8Kiu/h7cYS30Z5+R7WaiCCBfLq58ZI/dSeaEKb9WVJV5n/03QwrN3IeWIFllvw==", + "dev": true, + "requires": { + "find-up": "^3.0.0" + } + }, + "please-upgrade-node": { + "version": "3.1.1", + "resolved": "https://registry.npmjs.org/please-upgrade-node/-/please-upgrade-node-3.1.1.tgz", + "integrity": "sha512-KY1uHnQ2NlQHqIJQpnh/i54rKkuxCEBx+voJIS/Mvb+L2iYd2NMotwduhKTMjfC1uKoX3VXOxLjIYG66dfJTVQ==", + "dev": true, + "requires": { + "semver-compare": "^1.0.0" + } + }, "prettier": { "version": "1.14.2", "resolved": "https://registry.npmjs.org/prettier/-/prettier-1.14.2.tgz", "integrity": "sha512-McHPg0n1pIke+A/4VcaS2en+pTNjy4xF+Uuq86u/5dyDO59/TtFZtQ708QIRkEZ3qwKz3GVkVa6mpxK/CpB8Rg==", "dev": true + }, + "pretty-quick": { + "version": "1.6.0", + "resolved": "https://registry.npmjs.org/pretty-quick/-/pretty-quick-1.6.0.tgz", + "integrity": "sha512-bnCmsPy98ERD7VWBO+0y1OGWLfx/DPUjNFN2ZRVyxuGBiic1BXAGgjHsTKgBIbPISdqpP6KBEmRV0Lir4xu/BA==", + "dev": true, + "requires": { + "chalk": "^2.3.0", + "execa": "^0.8.0", + "find-up": "^2.1.0", + "ignore": "^3.3.7", + "mri": "^1.1.0" + }, + "dependencies": { + "execa": { + "version": "0.8.0", + "resolved": "https://registry.npmjs.org/execa/-/execa-0.8.0.tgz", + "integrity": "sha1-2NdrvBtVIX7RkP1t1J08d07PyNo=", + "dev": true, + "requires": { + "cross-spawn": "^5.0.1", + "get-stream": "^3.0.0", + "is-stream": "^1.1.0", + "npm-run-path": "^2.0.0", + "p-finally": "^1.0.0", + "signal-exit": "^3.0.0", + "strip-eof": "^1.0.0" + } + }, + "find-up": { + "version": "2.1.0", + "resolved": "https://registry.npmjs.org/find-up/-/find-up-2.1.0.tgz", + "integrity": "sha1-RdG35QbHF93UgndaK3eSCjwMV6c=", + "dev": true, + "requires": { + "locate-path": "^2.0.0" + } + }, + "locate-path": { + "version": "2.0.0", + "resolved": "https://registry.npmjs.org/locate-path/-/locate-path-2.0.0.tgz", + "integrity": "sha1-K1aLJl7slExtnA3pw9u7ygNUzY4=", + "dev": true, + "requires": { + "p-locate": "^2.0.0", + "path-exists": "^3.0.0" + } + }, + "p-limit": { + "version": "1.3.0", + "resolved": "https://registry.npmjs.org/p-limit/-/p-limit-1.3.0.tgz", + "integrity": "sha512-vvcXsLAJ9Dr5rQOPk7toZQZJApBl2K4J6dANSsEuh6QI41JYcsS/qhTGa9ErIUUgK3WNQoJYvylxvjqmiqEA9Q==", + "dev": true, + "requires": { + "p-try": "^1.0.0" + } + }, + "p-locate": { + "version": "2.0.0", + "resolved": "https://registry.npmjs.org/p-locate/-/p-locate-2.0.0.tgz", + "integrity": "sha1-IKAQOyIqcMj9OcwuWAaA893l7EM=", + "dev": true, + "requires": { + "p-limit": "^1.1.0" + } + }, + "p-try": { + "version": "1.0.0", + "resolved": "https://registry.npmjs.org/p-try/-/p-try-1.0.0.tgz", + "integrity": "sha1-y8ec26+P1CKOE/Yh8rGiN8GyB7M=", + "dev": true + } + } + }, + "pseudomap": { + "version": "1.0.2", + "resolved": "https://registry.npmjs.org/pseudomap/-/pseudomap-1.0.2.tgz", + "integrity": "sha1-8FKijacOYYkX7wqKw0wa5aaChrM=", + "dev": true + }, + "read-pkg": { + "version": "4.0.1", + "resolved": "https://registry.npmjs.org/read-pkg/-/read-pkg-4.0.1.tgz", + "integrity": "sha1-ljYlN48+HE1IyFhytabsfV0JMjc=", + "dev": true, + "requires": { + "normalize-package-data": "^2.3.2", + "parse-json": "^4.0.0", + "pify": "^3.0.0" + } + }, + "run-node": { + "version": "1.0.0", + "resolved": "https://registry.npmjs.org/run-node/-/run-node-1.0.0.tgz", + "integrity": "sha512-kc120TBlQ3mih1LSzdAJXo4xn/GWS2ec0l3S+syHDXP9uRr0JAT8Qd3mdMuyjqCzeZktgP3try92cEgf9Nks8A==", + "dev": true + }, + "semver": { + "version": "5.5.1", + "resolved": "https://registry.npmjs.org/semver/-/semver-5.5.1.tgz", + "integrity": "sha512-PqpAxfrEhlSUWge8dwIp4tZnQ25DIOthpiaHNIthsjEFQD6EvqUKUDM7L8O2rShkFccYo1VjJR0coWfNkCubRw==", + "dev": true + }, + "semver-compare": { + "version": "1.0.0", + "resolved": "https://registry.npmjs.org/semver-compare/-/semver-compare-1.0.0.tgz", + "integrity": "sha1-De4hahyUGrN+nvsXiPavxf9VN/w=", + "dev": true + }, + "shebang-command": { + "version": "1.2.0", + "resolved": "https://registry.npmjs.org/shebang-command/-/shebang-command-1.2.0.tgz", + "integrity": "sha1-RKrGW2lbAzmJaMOfNj/uXer98eo=", + "dev": true, + "requires": { + "shebang-regex": "^1.0.0" + } + }, + "shebang-regex": { + "version": "1.0.0", + "resolved": "https://registry.npmjs.org/shebang-regex/-/shebang-regex-1.0.0.tgz", + "integrity": "sha1-2kL0l0DAtC2yypcoVxyxkMmO/qM=", + "dev": true + }, + "signal-exit": { + "version": "3.0.2", + "resolved": "https://registry.npmjs.org/signal-exit/-/signal-exit-3.0.2.tgz", + "integrity": "sha1-tf3AjxKH6hF4Yo5BXiUTK3NkbG0=", + "dev": true + }, + "slash": { + "version": "2.0.0", + "resolved": "https://registry.npmjs.org/slash/-/slash-2.0.0.tgz", + "integrity": "sha512-ZYKh3Wh2z1PpEXWr0MpSBZ0V6mZHAQfYevttO11c51CaWjGTaadiKZ+wVt1PbMlDV5qhMFslpZCemhwOK7C89A==", + "dev": true + }, + "spdx-correct": { + "version": "3.0.0", + "resolved": "https://registry.npmjs.org/spdx-correct/-/spdx-correct-3.0.0.tgz", + "integrity": "sha512-N19o9z5cEyc8yQQPukRCZ9EUmb4HUpnrmaL/fxS2pBo2jbfcFRVuFZ/oFC+vZz0MNNk0h80iMn5/S6qGZOL5+g==", + "dev": true, + "requires": { + "spdx-expression-parse": "^3.0.0", + "spdx-license-ids": "^3.0.0" + } + }, + "spdx-exceptions": { + "version": "2.1.0", + "resolved": "https://registry.npmjs.org/spdx-exceptions/-/spdx-exceptions-2.1.0.tgz", + "integrity": "sha512-4K1NsmrlCU1JJgUrtgEeTVyfx8VaYea9J9LvARxhbHtVtohPs/gFGG5yy49beySjlIMhhXZ4QqujIZEfS4l6Cg==", + "dev": true + }, + "spdx-expression-parse": { + "version": "3.0.0", + "resolved": "https://registry.npmjs.org/spdx-expression-parse/-/spdx-expression-parse-3.0.0.tgz", + "integrity": "sha512-Yg6D3XpRD4kkOmTpdgbUiEJFKghJH03fiC1OPll5h/0sO6neh2jqRDVHOQ4o/LMea0tgCkbMgea5ip/e+MkWyg==", + "dev": true, + "requires": { + "spdx-exceptions": "^2.1.0", + "spdx-license-ids": "^3.0.0" + } + }, + "spdx-license-ids": { + "version": "3.0.0", + "resolved": "https://registry.npmjs.org/spdx-license-ids/-/spdx-license-ids-3.0.0.tgz", + "integrity": "sha512-2+EPwgbnmOIl8HjGBXXMd9NAu02vLjOO1nWw4kmeRDFyHn+M/ETfHxQUK0oXg8ctgVnl9t3rosNVsZ1jG61nDA==", + "dev": true + }, + "sprintf-js": { + "version": "1.0.3", + "resolved": "https://registry.npmjs.org/sprintf-js/-/sprintf-js-1.0.3.tgz", + "integrity": "sha1-BOaSb2YolTVPPdAVIDYzuFcpfiw=", + "dev": true + }, + "strip-eof": { + "version": "1.0.0", + "resolved": "https://registry.npmjs.org/strip-eof/-/strip-eof-1.0.0.tgz", + "integrity": "sha1-u0P/VZim6wXYm1n80SnJgzE2Br8=", + "dev": true + }, + "supports-color": { + "version": "5.5.0", + "resolved": "https://registry.npmjs.org/supports-color/-/supports-color-5.5.0.tgz", + "integrity": "sha512-QjVjwdXIt408MIiAqCX4oUKsgU2EqAGzs2Ppkm4aQYbjm+ZEWEcW4SfFNTr4uMNZma0ey4f5lgLrkB0aX0QMow==", + "dev": true, + "requires": { + "has-flag": "^3.0.0" + } + }, + "validate-npm-package-license": { + "version": "3.0.4", + "resolved": "https://registry.npmjs.org/validate-npm-package-license/-/validate-npm-package-license-3.0.4.tgz", + "integrity": "sha512-DpKm2Ui/xN7/HQKCtpZxoRWBhZ9Z0kqtygG8XCgNQ8ZlDnxuQmWhj566j8fN4Cu3/JmbhsDo7fcAJq4s9h27Ew==", + "dev": true, + "requires": { + "spdx-correct": "^3.0.0", + "spdx-expression-parse": "^3.0.0" + } + }, + "which": { + "version": "1.3.1", + "resolved": "https://registry.npmjs.org/which/-/which-1.3.1.tgz", + "integrity": "sha512-HxJdYWq1MTIQbJ3nw0cqssHoTNU267KlrDuGZ1WYlxDStUtKUhOaJmh112/TZmHxxUfuJqPXSOm7tDyas0OSIQ==", + "dev": true, + "requires": { + "isexe": "^2.0.0" + } + }, + "yallist": { + "version": "2.1.2", + "resolved": "https://registry.npmjs.org/yallist/-/yallist-2.1.2.tgz", + "integrity": "sha1-HBH5IY8HYImkfdUS+TxmmaaoHVI=", + "dev": true } } } diff --git a/package.json b/package.json index 9bdd973d..74cdae7c 100644 --- a/package.json +++ b/package.json @@ -2,20 +2,27 @@ "name": "webui-aria2", "version": "1.0.0", "description": "The aim for this project is to create the worlds best and hottest interface to interact with aria2.", - "dependencies": {}, - "devDependencies": { - "prettier": "^1.14.2" - }, + "homepage": "https://github.com/ziahamza/webui-aria2#readme", + "license": "MIT", "scripts": { - "format": "prettier -l --config .prettierrc --write \"**/*{js,css}\" \"!**/*.min.{js,css}\" " + "format": "prettier -l --write \"**/*{js,css}\" " }, "repository": { "type": "git", "url": "git+https://github.com/ziahamza/webui-aria2.git" }, - "license": "MIT", "bugs": { "url": "https://github.com/ziahamza/webui-aria2/issues" }, - "homepage": "https://github.com/ziahamza/webui-aria2#readme" + "husky": { + "hooks": { + "pre-commit": "pretty-quick --staged" + } + }, + "dependencies": {}, + "devDependencies": { + "husky": "^1.0.0-rc.13", + "prettier": "^1.14.2", + "pretty-quick": "^1.6.0" + } } From 4c3d2fddc9e2aec0137fbd7f26ed710678a39c7c Mon Sep 17 00:00:00 2001 From: Pratik Borsadiya Date: Thu, 30 Aug 2018 15:07:55 +0530 Subject: [PATCH 03/16] Run Prettier to format the files for consistency --- configuration.js | 99 +- css/download.css | 15 +- css/modals.css | 2 +- css/style.css | 24 +- js/ctrls/alert.js | 56 +- js/ctrls/main.js | 1370 +++++++++++++------------- js/ctrls/modal.js | 477 ++++----- js/ctrls/nav.js | 291 +++--- js/ctrls/props.js | 160 +-- js/directives/chunkbar.js | 63 +- js/directives/dgraph.js | 282 +++--- js/directives/fileselect.js | 251 ++--- js/directives/fselect.js | 29 +- js/directives/textarea.js | 19 +- js/filters/bytes.js | 57 +- js/filters/url.js | 3 +- js/init.js | 114 ++- js/libs/bootstrap-filestyle.js | 740 +++++++------- js/services/alerts.js | 44 +- js/services/base64.js | 105 +- js/services/deps.js | 8 +- js/services/errors.js | 132 ++- js/services/modals.js | 3 +- js/services/rpc/helpers.js | 111 ++- js/services/rpc/jsoncall.js | 147 +-- js/services/rpc/rpc.js | 530 +++++----- js/services/rpc/sockcall.js | 292 +++--- js/services/rpc/syscall.js | 100 +- js/services/settings/filters.js | 31 +- js/services/settings/settings.js | 1569 ++++++++++++++++-------------- js/services/utils.js | 315 +++--- js/translate/cs_CZ.js | 307 +++--- js/translate/de_DE.js | 268 ++--- js/translate/en_US.js | 298 +++--- js/translate/es_ES.js | 308 +++--- js/translate/fa_IR.js | 307 +++--- js/translate/fr_FR.js | 300 +++--- js/translate/id_ID.js | 312 +++--- js/translate/it_IT.js | 286 +++--- js/translate/nl_NL.js | 241 ++--- js/translate/pl_PL.js | 277 +++--- js/translate/pt_BR.js | 312 +++--- js/translate/ru_RU.js | 289 +++--- js/translate/template.js | 293 +++--- js/translate/th_TH.js | 228 +++-- js/translate/tr_TR.js | 286 +++--- js/translate/zh_CN.js | 303 +++--- js/translate/zh_TW.js | 303 +++--- node-server.js | 86 +- 49 files changed, 6511 insertions(+), 5932 deletions(-) diff --git a/configuration.js b/configuration.js index 4119b317..90b49203 100644 --- a/configuration.js +++ b/configuration.js @@ -1,46 +1,55 @@ angular -.module('webui.services.configuration', []) -.constant('$name', 'Aria2 WebUI') // name used across the entire UI -.constant('$titlePattern', 'active: {active} - waiting: {waiting} - stopped: {stopped} — {name}') -.constant('$pageSize', 11) // number of downloads shown before pagination kicks in -.constant('$authconf', { // default authentication configuration, never fill it in case the webui is hosted in public IP as it can be compromised - host: location.protocol.startsWith('http') ? location.hostname : 'localhost', - path: '/jsonrpc', - port: 6800, - encrypt: false, - auth: { // either add the token field or the user and pass field, not both. - // token: '$YOUR_SECRET_TOKEN$' - /*-----------------------------*/ - // user: '*YOUR_USERNAME*', - // pass: '*YOUR_SECRET_PASS*' - }, - directURL: '' // If supplied, links will be created to enable direct download from the aria2 server, requires appropriate webserver to be configured -}) -.constant('$enable', { - - torrent: true, // bittorrent support only enabled if supported by aria2 build, set to false otherwise to permanently disable it - - metalink: true, // metalink support only enabled if supported by aria2 build, set to false to permanently disable it - - sidebar: { // configuration related to the sidebar next to the list of downloads - show: true, // set to false to completely hide the sidebar. Other elements inside will be automatically hidden - - stats: true, // set to false to hide the global statistic section (contains the speed graph for now) - - filters: true, // set to false to hide the Download Filters - - starredProps: true // only shown when at least one property is added to the starred list, set to false to permanently hide the Quick Access Settings inside the sidebar - } -}) -.constant('$starredProps', [ // default list of Quick Access Properties. Can be overridden by making modification through the Global Settings dialog - // go to Global Settings dialog to see their description - 'dir', 'conf-path', 'auto-file-renaming', 'max-connection-per-server' -]) -.constant('$downloadProps', [ // Similar to starred Quick Access properties but for adding new downloads. - // go to Advance Download Options when adding a new download to view the list of possible options - 'header', 'http-user', 'http-passwd', 'pause', 'dir', 'max-connection-per-server' -]) -.constant('$globalTimeout', 1000) // interval to update the individual downloads -; - - + .module("webui.services.configuration", []) + .constant("$name", "Aria2 WebUI") // name used across the entire UI + .constant("$titlePattern", "active: {active} - waiting: {waiting} - stopped: {stopped} — {name}") + .constant("$pageSize", 11) // number of downloads shown before pagination kicks in + .constant("$authconf", { + // default authentication configuration, never fill it in case the webui is hosted in public IP as it can be compromised + host: location.protocol.startsWith("http") ? location.hostname : "localhost", + path: "/jsonrpc", + port: 6800, + encrypt: false, + auth: { + // either add the token field or the user and pass field, not both. + // token: '$YOUR_SECRET_TOKEN$' + /*-----------------------------*/ + // user: '*YOUR_USERNAME*', + // pass: '*YOUR_SECRET_PASS*' + }, + directURL: "" // If supplied, links will be created to enable direct download from the aria2 server, requires appropriate webserver to be configured + }) + .constant("$enable", { + torrent: true, // bittorrent support only enabled if supported by aria2 build, set to false otherwise to permanently disable it + + metalink: true, // metalink support only enabled if supported by aria2 build, set to false to permanently disable it + + sidebar: { + // configuration related to the sidebar next to the list of downloads + show: true, // set to false to completely hide the sidebar. Other elements inside will be automatically hidden + + stats: true, // set to false to hide the global statistic section (contains the speed graph for now) + + filters: true, // set to false to hide the Download Filters + + starredProps: true // only shown when at least one property is added to the starred list, set to false to permanently hide the Quick Access Settings inside the sidebar + } + }) + .constant("$starredProps", [ + // default list of Quick Access Properties. Can be overridden by making modification through the Global Settings dialog + // go to Global Settings dialog to see their description + "dir", + "conf-path", + "auto-file-renaming", + "max-connection-per-server" + ]) + .constant("$downloadProps", [ + // Similar to starred Quick Access properties but for adding new downloads. + // go to Advance Download Options when adding a new download to view the list of possible options + "header", + "http-user", + "http-passwd", + "pause", + "dir", + "max-connection-per-server" + ]) + .constant("$globalTimeout", 1000); // interval to update the individual downloads diff --git a/css/download.css b/css/download.css index 6a354b18..399f3e81 100644 --- a/css/download.css +++ b/css/download.css @@ -27,24 +27,31 @@ word-wrap: break-word; } -.active-download, .waiting-download, .stopped-download, .download { +.active-download, +.waiting-download, +.stopped-download, +.download { cursor: pointer; width: 100%; padding: 4px 5px; background-color: #fff; margin-bottom: 20px; - box-shadow: 0 1px 3px 0 rgba(0, 0, 0, 0.2), 0 1px 1px 0 rgba(0, 0, 0, 0.14), 0 2px 1px -1px rgba(0, 0, 0, 0.12); + box-shadow: 0 1px 3px 0 rgba(0, 0, 0, 0.2), 0 1px 1px 0 rgba(0, 0, 0, 0.14), + 0 2px 1px -1px rgba(0, 0, 0, 0.12); } /* fix table layout to break words */ @media (max-width: 767px) { - .active-download, .waiting-download, .stopped-download, .download { + .active-download, + .waiting-download, + .stopped-download, + .download { table-layout: fixed; } } .download-graph { - margin: .5em 30px .5em 0; + margin: 0.5em 30px 0.5em 0; } @media (min-width: 1200px) { diff --git a/css/modals.css b/css/modals.css index 35488319..4483f15a 100644 --- a/css/modals.css +++ b/css/modals.css @@ -45,4 +45,4 @@ .selectFiles div.recursivedir { width: 100%; -} \ No newline at end of file +} diff --git a/css/style.css b/css/style.css index 3ca4b08f..d940429b 100644 --- a/css/style.css +++ b/css/style.css @@ -1,13 +1,14 @@ -@import 'https://fonts.googleapis.com/css?family=Lato:400,700'; +@import "https://fonts.googleapis.com/css?family=Lato:400,700"; body { - font-family: 'Lato', sans-serif; + font-family: "Lato", sans-serif; overflow-y: scroll; background-color: #f5f5f5; padding-bottom: 5em; } -input[type=checkbox], input[type=radio] { +input[type="checkbox"], +input[type="radio"] { vertical-align: middle; position: relative; } @@ -21,8 +22,10 @@ input[type=checkbox], input[type=radio] { background-color: #428bca; } -.label-active, .badge-active, .progress-active .bar { - background-color: #62C462; +.label-active, +.badge-active, +.progress-active .bar { + background-color: #62c462; } .progress-success .bar { @@ -81,8 +84,8 @@ input[type=checkbox], input[type=radio] { .main-navbar { box-shadow: 0 2px 2px 0 rgba(0, 0, 0, 0.1); - background-color: #00897B; - border-color: #00897B; + background-color: #00897b; + border-color: #00897b; } .main-navbar .navbar-brand { @@ -110,7 +113,8 @@ input[type=checkbox], input[type=radio] { margin-bottom: 30px; background-color: #fff; padding: 10px 20px 20px; - box-shadow: 0 1px 3px 0 rgba(0, 0, 0, 0.2), 0 1px 1px 0 rgba(0, 0, 0, 0.14), 0 2px 1px -1px rgba(0, 0, 0, 0.12); + box-shadow: 0 1px 3px 0 rgba(0, 0, 0, 0.2), 0 1px 1px 0 rgba(0, 0, 0, 0.14), + 0 2px 1px -1px rgba(0, 0, 0, 0.12); } .filter-input-group { @@ -121,6 +125,6 @@ input[type=checkbox], input[type=radio] { .filter-input-group > .clear-button { position: absolute; right: 25px; - top: 6px; + top: 6px; cursor: pointer; -} \ No newline at end of file +} diff --git a/js/ctrls/alert.js b/js/ctrls/alert.js index 4fec3d9b..1c9ed3a3 100644 --- a/js/ctrls/alert.js +++ b/js/ctrls/alert.js @@ -1,33 +1,33 @@ -angular.module('webui.ctrls.alert', [ - 'webui.services.alerts' -]) -.controller('AlertCtrl', ['$scope', '$alerts', '$sce', - function(scope, alerts, sce) { - scope.pendingAlerts = []; +angular.module("webui.ctrls.alert", ["webui.services.alerts"]).controller("AlertCtrl", [ + "$scope", + "$alerts", + "$sce", + function(scope, alerts, sce) { + scope.pendingAlerts = []; - scope.removeAlert = function(ind) { - this.pendingAlerts.splice(ind, 1); - }; + scope.removeAlert = function(ind) { + this.pendingAlerts.splice(ind, 1); + }; - alerts.addAlerter(function(msg, type) { - type = type || 'warning'; - var obj = { msg: sce.trustAsHtml(msg), type: type }; - scope.pendingAlerts = _.filter(scope.pendingAlerts, function(al) { - return !al.expired; - }); - scope.pendingAlerts.push(obj); + alerts.addAlerter(function(msg, type) { + type = type || "warning"; + var obj = { msg: sce.trustAsHtml(msg), type: type }; + scope.pendingAlerts = _.filter(scope.pendingAlerts, function(al) { + return !al.expired; + }); + scope.pendingAlerts.push(obj); - setTimeout(function() { - var ind = scope.pendingAlerts.indexOf(obj); - if (ind != -1) { - scope.pendingAlerts[ind].expired = true; + setTimeout(function() { + var ind = scope.pendingAlerts.indexOf(obj); + if (ind != -1) { + scope.pendingAlerts[ind].expired = true; - // only remove if more notifications are pending in the pipeline - if (scope.pendingAlerts.length > 0) - scope.removeAlert(ind); - } - }, type == "error" ? 15000 : 5000); + // only remove if more notifications are pending in the pipeline + if (scope.pendingAlerts.length > 0) scope.removeAlert(ind); + } + }, type == "error" ? 15000 : 5000); - scope.$digest(); - }); -}]); + scope.$digest(); + }); + } +]); diff --git a/js/ctrls/main.js b/js/ctrls/main.js index 04c08dd1..f7d10924 100644 --- a/js/ctrls/main.js +++ b/js/ctrls/main.js @@ -1,669 +1,703 @@ angular -.module('webui.ctrls.download', [ - "ui.bootstrap", - 'webui.services.utils', 'webui.services.rpc', 'webui.services.rpc.helpers', 'webui.services.alerts', - 'webui.services.settings', 'webui.services.modals', 'webui.services.configuration', - 'webui.services.errors', -]) -.controller('MainCtrl', [ - '$scope', '$name', '$enable', '$rpc', '$rpchelpers', '$utils', '$alerts', '$modals', - '$fileSettings', '$activeInclude', '$waitingExclude', '$pageSize', '$getErrorStatus', - // for document title - '$rootScope', '$filter', -function( - scope, name, enable, rpc, rhelpers, utils, alerts, modals, - fsettings, activeInclude, waitingExclude, pageSize, getErrorStatus, - rootScope, filter -) { - - scope.name = name; // default UI name - scope.enable = enable; // UI enable options - - var re_slashes = /\\/g; - var slash = "/"; - var allStopped = []; - - scope.active = [], scope.waiting = [], scope.stopped = []; - scope.gstats = {}; - scope.hideLinkedMetadata = true; - scope.propFilter = ""; - - // pause the download - // d: the download ctx - scope.pause = function(d) { - rpc.once('forcePause', [d.gid]); - } - - // resume the download - // d: the download ctx - scope.resume = function(d) { - rpc.once('unpause', [d.gid]); - } - - scope.restart = function(d) { - // assumes downloads which are started by URIs, not torrents. - // the preferences are also not transferred, just simple restart - - rpc.once('getOption', [d.gid], function(data) { - var prefs = data[0]; - rpc.once('getFiles', [d.gid], function(data) { - var files = data[0]; - var uris = - _.chain(files).map(function(f) { return f.uris }) - .filter(function(uris) { return uris && uris.length }) - .map(function(uris) { - var u = _.chain(uris) - .map(function(u) { return u.uri }) - .uniq().value(); - return u; - }).value(); - - if (uris.length > 0) { - console.log('adding uris:', uris, prefs); - scope.remove(d, function() { - rhelpers.addUris(uris, prefs); - }, true); - } - }); - }); - } - - - - scope.canRestart = function(d) { - return (['active', 'paused'].indexOf(d.status) == -1 - && !d.bittorrent); - } - - // remove the download, - // put it in stopped list if active, - // otherwise permanantly remove it - // d: the download ctx - scope.remove = function(d, cb, noConfirm) { - // HACK to make sure an angular digest is not running, as only one can happen at a time, and confirm is a blocking - // call so an rpc response can also trigger a digest call - setTimeout(function() { - if (!noConfirm && !confirm( - filter('translate')('Remove {{name}} and associated meta-data?', - { name: d.name }))) { - return; - } - - var method = 'remove'; - - if (scope.getType(d) == 'stopped') - method = 'removeDownloadResult'; - - if (d.followedFrom) { - scope.remove(d.followedFrom, function() {}, true); - d.followedFrom = null; - } - rpc.once(method, [d.gid], cb); - - var lists = [scope.active, scope.waiting, scope.stopped], ind = -1, i; - for (var i = 0; i < lists.length; ++i) { - var list = lists[i]; - var idx = list.indexOf(d); - if (idx < 0) { - continue; - } - list.splice(idx, 1); - return; - } - }, 0); - } - - // start filling in the model of active, - // waiting and stopped download - rpc.subscribe('tellActive', [], function(data) { - scope.$apply(function() { - utils.mergeMap(data[0], scope.active, scope.getCtx); - }); - }); - - rpc.subscribe('tellWaiting', [0, 1000], function(data) { - scope.$apply(function() { - utils.mergeMap(data[0], scope.waiting, scope.getCtx); - }); - }); - - - rpc.subscribe('tellStopped', [0, 1000], function(data) { - scope.$apply(function() { - if (!scope.hideLinkedMetadata) { - utils.mergeMap(data[0], scope.stopped, scope.getCtx); - return; - } - utils.mergeMap(data[0], allStopped, scope.getCtx); - var gids = {}; - _.forEach(allStopped, function(e) { - gids[e.gid] = e; - }); - _.forEach(scope.active, function(e) { - gids[e.gid] = e; - }); - _.forEach(scope.waiting, function(e) { - gids[e.gid] = e; - }); - scope.stopped = _.filter(allStopped, function(e) { - if (!e.metadata || !e.followedBy || !(e.followedBy in gids)) { - return true; - } - var linked = gids[e.followedBy]; - linked.followedFrom = e; - return false; - }); - }); - }); - - rootScope.pageTitle = utils.getTitle(); - rpc.subscribe('getGlobalStat', [], function(data) { - scope.$apply(function() { - scope.gstats = data[0]; - rootScope.pageTitle = utils.getTitle(scope.gstats); - }); - }); - - rpc.once('getVersion', [], function(data) { - scope.$apply(function() { - scope.miscellaneous = data[0]; - }); - }); - - // total number of downloads, updates dynamically as downloads are - // stored in scope - scope.totalDownloads = 0; - - // download search filter - scope.downloadFilter = ""; - scope.downloadFilterCommitted = ""; - - scope.onDownloadFilter = function() { - if (scope.downloadFilterTimer) { - clearTimeout(scope.downloadFilterTimer); - } - scope.downloadFilterTimer = setTimeout(function() { - delete scope.downloadFilterTimer; - if (scope.downloadFilterCommitted !== scope.downloadFilter) { - scope.downloadFilterCommitted = scope.downloadFilter; - scope.$digest(); - } - }, 500); - }; - - scope.filterDownloads = function(downloads) { - if (!scope.downloadFilterCommitted) { - return downloads; - } - var filter = scope.downloadFilterCommitted. - replace(/[{}()\[\]\\^$.?]/g, "\\$&"). - replace(/\*/g, ".*"). - replace(/\./g, "."); - filter = new RegExp(filter, "i"); - return _.filter(downloads, function(d) { - if (filter.test(d.name)) return true; - return _.filter(d.files, function(f) { - return filter.test(f.relpath); - }).length; - }); - }; - - scope.clearFilter = function() { - scope.downloadFilter = scope.downloadFilterCommitted = ""; - }; - - scope.toggleStateFilters = function() { - scope.filterSpeed = !scope.filterSpeed; - scope.filterActive = !scope.filterActive; - scope.filterWaiting = !scope.filterWaiting; - scope.filterComplete = !scope.filterComplete; - scope.filterError = !scope.filterError; - scope.filterPaused = !scope.filterPaused; - scope.filterRemoved = !scope.filterRemoved; - scope.persistFilters(); - }; - - scope.resetFilters = function() { - scope.filterSpeed = - scope.filterActive = - scope.filterWaiting = - scope.filterComplete = - scope.filterError = - scope.filterPaused = - scope.filterRemoved = - true; - scope.clearFilter(); - scope.persistFilters(); - }; - - scope.persistFilters = function() { - var o = JSON.stringify({ - s: scope.filterSpeed, - a: scope.filterActive, - w: scope.filterWaiting, - c: scope.filterComplete, - e: scope.filterError, - p: scope.filterPaused, - r: scope.filterRemoved - }); - utils.setCookie("aria2filters", o); - }; - - scope.loadFilters = function() { - var o = JSON.parse(utils.getCookie("aria2filters")); - if (!o) { - scope.resetFilters(); - return; - } - scope.filterSpeed = !!o.s; - scope.filterActive = !!o.a; - scope.filterWaiting = !!o.w; - scope.filterComplete = !!o.c; - scope.filterError = !!o.e; - scope.filterPaused = !!o.p; - scope.filterRemoved = !!o.r; - }; - - scope.loadFilters(); - - scope.toggleCollapsed = function(download) { - if (!download.collapsed) { - download.animCollapsed = true; - // ng-unswitch after half a second. - // XXX hacky way, because I'm to lazy right now to wire up proper - // transitionend events. - setTimeout(function() { - scope.$apply(function() { - download.collapsed = true; - }); - }, 500); - return; - } - - download.collapsed = false; - setTimeout(function() { - scope.$apply(function() { - download.animCollapsed = false; - }); - }, 0); - }; - - - // max downloads shown in one page - scope.pageSize = pageSize; - - // current displayed page - scope.currentPage = 1; - - // total amount of downloads returned by aria2 - scope.totalAria2Downloads = function() { - return scope.active.length - + scope.waiting.length - + scope.stopped.length; - } - - scope.getErrorStatus = function(errorCode) { - return getErrorStatus(+errorCode); - } - - // actual downloads used by the view - scope.getDownloads = function() { - var categories = []; - - if (scope.filterActive) { - if (!scope.filterSpeed) { - categories.push(_.filter(scope.active, function (e) { - return !+e.uploadSpeed && !+e.downloadSpeed; - })); - } - else { - categories.push(scope.active); - } - } - else if (scope.filterSpeed) { - categories.push(_.filter(scope.active, function (e) { - return +e.uploadSpeed || +e.downloadSpeed; - })); - } - - if (scope.filterWaiting) { - categories.push(_.filter(scope.waiting, function (e) { - return e.status == "waiting"; - })); - } - - if (scope.filterPaused) { - categories.push(_.filter(scope.waiting, function (e) { - return e.status == "paused"; - })); - } - - if (scope.filterError) { - categories.push(_.filter(scope.stopped, function (e) { - return e.status == "error"; - })); - } - - if (scope.filterComplete) { - categories.push(_.filter(scope.stopped, function (e) { - return e.status == "complete"; - })); - } - - if (scope.filterRemoved) { - categories.push(_.filter(scope.stopped, function (e) { - return e.status == "removed"; - })); - } - - var downloads = categories.map(function (category) { - // sort downloads within category by completness, most completed first - return _.sortBy(category, function (e) { - return -(e.completedLength / e.totalLength); - }); - }).reduce(function (downloads, category) { - return downloads.concat(category); - }, []); - - downloads = scope.filterDownloads(downloads); - - scope.totalDownloads = downloads.length; - - downloads = downloads.slice( (scope.currentPage - 1) * scope.pageSize ); - downloads.splice( scope.pageSize ); - - return downloads; - } - - scope.hasDirectURL = function() { - return rpc.getDirectURL() != ''; - } - - scope.getDirectURL = function() { - return rpc.getDirectURL(); - } - - // convert the donwload form aria2 to once used by the view, - // minor additions of some fields and checks - scope.getCtx = function(d, ctx) { - if (!ctx) { - ctx = { - dir: d.dir, - status: d.status, - gid: d.gid, - followedBy: (d.followedBy && d.followedBy.length == 1 - ? d.followedBy[0] : null), - followedFrom: null, - numPieces: d.numPieces, - connections: d.connections, - connectionsTitle: "Connections", - numSeeders: d.numSeeders, - bitfield: d.bitfield, - errorCode: d.errorCode, - totalLength: d.totalLength, - fmtTotalLength: utils.fmtsize(d.totalLength), - completedLength: d.completedLength, - fmtCompletedLength: utils.fmtsize(d.completedLength), - uploadLength: d.uploadLength, - fmtUploadLength: utils.fmtsize(d.uploadLength), - pieceLength: d.pieceLength, - fmtPieceLength: utils.fmtsize(d.pieceLength), - downloadSpeed: d.downloadSpeed, - fmtDownloadSpeed: utils.fmtspeed(d.downloadSpeed), - uploadSpeed: d.uploadSpeed, - fmtUploadSpeed: utils.fmtspeed(d.uploadSpeed), - collapsed: true, - animCollapsed: true, - files: [], - }; - if (d.verifiedLength) { - ctx.verifiedLength = d.verifiedLength; - ctx.status = "verifing"; - } - if (d.verifyIntegrityPending) { - ctx.verifyIntegrityPending = d.verifyIntegrityPending; - ctx.status = "verifyPending"; - } - } - else { - if (ctx.gid !== d.gid) - ctx.files = []; - ctx.dir = d.dir; - ctx.status = d.status; - if(d.verifiedLength) - ctx.status = "verifing"; - if(d.verifyIntegrityPending) - ctx.status = "verifyPending" - ctx.errorCode = d.errorCode; - ctx.gid = d.gid; - ctx.followedBy = (d.followedBy && d.followedBy.length == 1 - ? d.followedBy[0] : null); - ctx.followedFrom = null; - ctx.numPieces = d.numPieces; - ctx.connections = d.connections; - if ( typeof d.numSeeders === 'undefined' ) { - ctx.numSeeders = ""; - } - else { - ctx.connectionsTitle = "Connections (Seeders)"; - ctx.numSeeders = " (" + d.numSeeders + ")"; - } - ctx.bitfield = d.bitfield; - if (ctx.totalLength !== d.totalLength) { - ctx.totalLength = d.totalLength; - ctx.fmtTotalLength = utils.fmtsize(d.totalLength); - } - if (ctx.completedLength !== d.completedLength) { - ctx.completedLength = d.completedLength; - ctx.fmtCompletedLength = utils.fmtsize(d.completedLength); - } - if (!d.verifiedLength) { - delete ctx.verifiedLength - } else if (ctx.verifiedLength !== d.verifiedLength) { - ctx.verifiedLength = d.verifiedLength; - } - if (!d.verifyIntegrityPending) { - delete ctx.verifyIntegrityPending - } else if (ctx.verifyIntegrityPending !== d.verifyIntegrityPending) { - ctx.verifyIntegrityPending = d.verifyIntegrityPending; - } - if (ctx.uploadLength !== d.uploadLength) { - ctx.uploadLength = d.uploadLength; - ctx.fmtUploadLength = utils.fmtsize(d.uploadLength); - } - if (ctx.pieceLength !== d.pieceLength) { - ctx.pieceLength = d.pieceLength; - ctx.fmtPieceLength = utils.fmtsize(d.pieceLength); - } - if (ctx.downloadSpeed !== d.downloadSpeed) { - ctx.downloadSpeed = d.downloadSpeed; - ctx.fmtDownloadSpeed = utils.fmtspeed(d.downloadSpeed); - } - if (ctx.uploadSpeed !== d.uploadSpeed) { - ctx.uploadSpeed = d.uploadSpeed; - ctx.fmtUploadSpeed = utils.fmtspeed(d.uploadSpeed); - } - } - - var dlName; - var files = d.files; - if (files) { - var cfiles = ctx.files; - for (var i = 0; i < files.length; ++i) { - var cfile = cfiles[i] || (cfiles[i] = {}); - var file = files[i]; - if (file.path !== cfile.path) { - cfile.index = +file.index; - cfile.path = file.path; - cfile.length = file.length; - cfile.fmtLength = utils.fmtsize(file.length); - cfile.relpath = file.path.replace(re_slashes, slash); - if (!cfile.relpath) { - cfile.relpath = (file.uris && file.uris[0] && file.uris[0].uri) || "Unknown"; - } - else if (!cfile.relpath.startsWith("[")) { // METADATA - cfile.relpath = cfile.relpath.substr(ctx.dir.length + 1); - } - } - cfile.selected = (file.selected === "true"); - } - cfiles.length = files.length; - if (cfiles.length) { - dlName = cfiles[0].relpath; - } - } - else { - delete ctx.files; - } - - var btName; - if (d.bittorrent) { - btName = d.bittorrent.info && d.bittorrent.info.name; - ctx.bittorrent = true; - } - else { - delete ctx.bittorrent; - } - - ctx.name = btName || dlName || "Unknown"; - ctx.metadata = ctx.name.startsWith("[METADATA]"); - if (ctx.metadata) { - ctx.name = ctx.name.substr(10); - } - - return ctx; - }; - - scope.hasStatus = function hasStatus(d, status) { - if (_.isArray(status)) { - if (status.length == 0) return false; - return hasStatus(d, status[0]) || hasStatus(d, status.slice(1)); - } - else { - return d.status == status; - } - }; - - // get time left for the download with - // current download speed, - // could be smarter by different heuristics - scope.getEta = function(d) { - return (d.totalLength-d.completedLength) / d.downloadSpeed; - } - - scope.getProgressClass = function(d) { - switch (d.status) { - case "paused": - return "progress-bar-info"; - case "error": - return "progress-bar-danger"; - case "removed": - return "progress-bar-warning"; - case "active": - return "active"; - case "verifing": - return "progress-bar-warning"; - case "complete": - return "progress-bar-success"; - default: - return ""; - } - }; - - // gets the progress in percentages - scope.getProgress = function(d) { - var percentage = 0 - if (d.verifiedLength) - percentage = (d.verifiedLength / d.totalLength) * 100 || 0; - else - percentage = (d.completedLength / d.totalLength) * 100 || 0; - percentage = percentage.toFixed(2); - if(!percentage) percentage = 0; - - return percentage; - }; - - // gets the upload ratio - scope.getRatio = function(d) { - var ratio = 0 - ratio = (d.uploadLength / d.completedLength) || 0; - ratio = ratio.toFixed(2); - if(!ratio) ratio = 0; - - return ratio; - }; - - // gets the type for the download as classified by the aria2 rpc calls - scope.getType = function(d) { - var type = d.status; - if (type == "paused") type = "waiting"; - if (["error", "removed", "complete"].indexOf(type) != -1) - type = "stopped"; - return type; - }; - - scope.selectFiles = function(d) { - console.log('got back files for the torrent ...'); - modals.invoke('selectFiles', d.files, function(files) { - var indexes = ""; - _.forEach(files, function(f) { - if (f.selected) { - indexes += "," + f.index; - } - }); - - indexes = indexes.slice(1); - rpc.once('changeOption', [d.gid, {'select-file': indexes}], function(res) { - console.log('changed indexes to:', indexes, res); - }) - }); - } - - scope.showSettings = function(d) { - var type = scope.getType(d) - , settings = {}; - - rpc.once('getOption', [d.gid], function(data) { - var vals = data[0]; - - var sets = _.cloneDeep(fsettings); - for (var i in sets) { - if (type == 'active' && activeInclude.indexOf(i) == -1) continue; - - if (type == 'waiting' && waitingExclude.indexOf(i) != -1) continue; - - settings[i] = sets[i]; - settings[i].val = vals[i] || settings[i].val; - } - - modals.invoke('settings', settings, d.name + ' settings', 'Change', function(settings) { - var sets = {}; - for (var i in settings) { sets[i] = settings[i].val }; - - rpc.once('changeOption', [d.gid, sets]); - }); - }); - - return false; - } - scope.moveDown = function (d) { - rpc.once('changePosition', [d.gid, 1, 'POS_CUR']); - }; - scope.moveUp = function (d) { - rpc.once('changePosition', [d.gid, -1, 'POS_CUR']); - }; -}]) -.filter('objFilter', function(){ - return function(input, filter) { - input = input || {}; - var out = {}; - - for(key in input) { - if (key.startsWith(filter)){ - out[key] = input[key]; - } - } - - return out; - }; -}); + .module("webui.ctrls.download", [ + "ui.bootstrap", + "webui.services.utils", + "webui.services.rpc", + "webui.services.rpc.helpers", + "webui.services.alerts", + "webui.services.settings", + "webui.services.modals", + "webui.services.configuration", + "webui.services.errors" + ]) + .controller("MainCtrl", [ + "$scope", + "$name", + "$enable", + "$rpc", + "$rpchelpers", + "$utils", + "$alerts", + "$modals", + "$fileSettings", + "$activeInclude", + "$waitingExclude", + "$pageSize", + "$getErrorStatus", + // for document title + "$rootScope", + "$filter", + function( + scope, + name, + enable, + rpc, + rhelpers, + utils, + alerts, + modals, + fsettings, + activeInclude, + waitingExclude, + pageSize, + getErrorStatus, + rootScope, + filter + ) { + scope.name = name; // default UI name + scope.enable = enable; // UI enable options + + var re_slashes = /\\/g; + var slash = "/"; + var allStopped = []; + + (scope.active = []), (scope.waiting = []), (scope.stopped = []); + scope.gstats = {}; + scope.hideLinkedMetadata = true; + scope.propFilter = ""; + + // pause the download + // d: the download ctx + scope.pause = function(d) { + rpc.once("forcePause", [d.gid]); + }; + + // resume the download + // d: the download ctx + scope.resume = function(d) { + rpc.once("unpause", [d.gid]); + }; + + scope.restart = function(d) { + // assumes downloads which are started by URIs, not torrents. + // the preferences are also not transferred, just simple restart + + rpc.once("getOption", [d.gid], function(data) { + var prefs = data[0]; + rpc.once("getFiles", [d.gid], function(data) { + var files = data[0]; + var uris = _.chain(files) + .map(function(f) { + return f.uris; + }) + .filter(function(uris) { + return uris && uris.length; + }) + .map(function(uris) { + var u = _.chain(uris) + .map(function(u) { + return u.uri; + }) + .uniq() + .value(); + return u; + }) + .value(); + + if (uris.length > 0) { + console.log("adding uris:", uris, prefs); + scope.remove( + d, + function() { + rhelpers.addUris(uris, prefs); + }, + true + ); + } + }); + }); + }; + + scope.canRestart = function(d) { + return ["active", "paused"].indexOf(d.status) == -1 && !d.bittorrent; + }; + + // remove the download, + // put it in stopped list if active, + // otherwise permanantly remove it + // d: the download ctx + scope.remove = function(d, cb, noConfirm) { + // HACK to make sure an angular digest is not running, as only one can happen at a time, and confirm is a blocking + // call so an rpc response can also trigger a digest call + setTimeout(function() { + if ( + !noConfirm && + !confirm( + filter("translate")("Remove {{name}} and associated meta-data?", { name: d.name }) + ) + ) { + return; + } + + var method = "remove"; + + if (scope.getType(d) == "stopped") method = "removeDownloadResult"; + + if (d.followedFrom) { + scope.remove(d.followedFrom, function() {}, true); + d.followedFrom = null; + } + rpc.once(method, [d.gid], cb); + + var lists = [scope.active, scope.waiting, scope.stopped], + ind = -1, + i; + for (var i = 0; i < lists.length; ++i) { + var list = lists[i]; + var idx = list.indexOf(d); + if (idx < 0) { + continue; + } + list.splice(idx, 1); + return; + } + }, 0); + }; + + // start filling in the model of active, + // waiting and stopped download + rpc.subscribe("tellActive", [], function(data) { + scope.$apply(function() { + utils.mergeMap(data[0], scope.active, scope.getCtx); + }); + }); + + rpc.subscribe("tellWaiting", [0, 1000], function(data) { + scope.$apply(function() { + utils.mergeMap(data[0], scope.waiting, scope.getCtx); + }); + }); + + rpc.subscribe("tellStopped", [0, 1000], function(data) { + scope.$apply(function() { + if (!scope.hideLinkedMetadata) { + utils.mergeMap(data[0], scope.stopped, scope.getCtx); + return; + } + utils.mergeMap(data[0], allStopped, scope.getCtx); + var gids = {}; + _.forEach(allStopped, function(e) { + gids[e.gid] = e; + }); + _.forEach(scope.active, function(e) { + gids[e.gid] = e; + }); + _.forEach(scope.waiting, function(e) { + gids[e.gid] = e; + }); + scope.stopped = _.filter(allStopped, function(e) { + if (!e.metadata || !e.followedBy || !(e.followedBy in gids)) { + return true; + } + var linked = gids[e.followedBy]; + linked.followedFrom = e; + return false; + }); + }); + }); + + rootScope.pageTitle = utils.getTitle(); + rpc.subscribe("getGlobalStat", [], function(data) { + scope.$apply(function() { + scope.gstats = data[0]; + rootScope.pageTitle = utils.getTitle(scope.gstats); + }); + }); + + rpc.once("getVersion", [], function(data) { + scope.$apply(function() { + scope.miscellaneous = data[0]; + }); + }); + + // total number of downloads, updates dynamically as downloads are + // stored in scope + scope.totalDownloads = 0; + + // download search filter + scope.downloadFilter = ""; + scope.downloadFilterCommitted = ""; + + scope.onDownloadFilter = function() { + if (scope.downloadFilterTimer) { + clearTimeout(scope.downloadFilterTimer); + } + scope.downloadFilterTimer = setTimeout(function() { + delete scope.downloadFilterTimer; + if (scope.downloadFilterCommitted !== scope.downloadFilter) { + scope.downloadFilterCommitted = scope.downloadFilter; + scope.$digest(); + } + }, 500); + }; + + scope.filterDownloads = function(downloads) { + if (!scope.downloadFilterCommitted) { + return downloads; + } + var filter = scope.downloadFilterCommitted + .replace(/[{}()\[\]\\^$.?]/g, "\\$&") + .replace(/\*/g, ".*") + .replace(/\./g, "."); + filter = new RegExp(filter, "i"); + return _.filter(downloads, function(d) { + if (filter.test(d.name)) return true; + return _.filter(d.files, function(f) { + return filter.test(f.relpath); + }).length; + }); + }; + + scope.clearFilter = function() { + scope.downloadFilter = scope.downloadFilterCommitted = ""; + }; + + scope.toggleStateFilters = function() { + scope.filterSpeed = !scope.filterSpeed; + scope.filterActive = !scope.filterActive; + scope.filterWaiting = !scope.filterWaiting; + scope.filterComplete = !scope.filterComplete; + scope.filterError = !scope.filterError; + scope.filterPaused = !scope.filterPaused; + scope.filterRemoved = !scope.filterRemoved; + scope.persistFilters(); + }; + + scope.resetFilters = function() { + scope.filterSpeed = scope.filterActive = scope.filterWaiting = scope.filterComplete = scope.filterError = scope.filterPaused = scope.filterRemoved = true; + scope.clearFilter(); + scope.persistFilters(); + }; + + scope.persistFilters = function() { + var o = JSON.stringify({ + s: scope.filterSpeed, + a: scope.filterActive, + w: scope.filterWaiting, + c: scope.filterComplete, + e: scope.filterError, + p: scope.filterPaused, + r: scope.filterRemoved + }); + utils.setCookie("aria2filters", o); + }; + + scope.loadFilters = function() { + var o = JSON.parse(utils.getCookie("aria2filters")); + if (!o) { + scope.resetFilters(); + return; + } + scope.filterSpeed = !!o.s; + scope.filterActive = !!o.a; + scope.filterWaiting = !!o.w; + scope.filterComplete = !!o.c; + scope.filterError = !!o.e; + scope.filterPaused = !!o.p; + scope.filterRemoved = !!o.r; + }; + + scope.loadFilters(); + + scope.toggleCollapsed = function(download) { + if (!download.collapsed) { + download.animCollapsed = true; + // ng-unswitch after half a second. + // XXX hacky way, because I'm to lazy right now to wire up proper + // transitionend events. + setTimeout(function() { + scope.$apply(function() { + download.collapsed = true; + }); + }, 500); + return; + } + + download.collapsed = false; + setTimeout(function() { + scope.$apply(function() { + download.animCollapsed = false; + }); + }, 0); + }; + + // max downloads shown in one page + scope.pageSize = pageSize; + + // current displayed page + scope.currentPage = 1; + + // total amount of downloads returned by aria2 + scope.totalAria2Downloads = function() { + return scope.active.length + scope.waiting.length + scope.stopped.length; + }; + + scope.getErrorStatus = function(errorCode) { + return getErrorStatus(+errorCode); + }; + + // actual downloads used by the view + scope.getDownloads = function() { + var categories = []; + + if (scope.filterActive) { + if (!scope.filterSpeed) { + categories.push( + _.filter(scope.active, function(e) { + return !+e.uploadSpeed && !+e.downloadSpeed; + }) + ); + } else { + categories.push(scope.active); + } + } else if (scope.filterSpeed) { + categories.push( + _.filter(scope.active, function(e) { + return +e.uploadSpeed || +e.downloadSpeed; + }) + ); + } + + if (scope.filterWaiting) { + categories.push( + _.filter(scope.waiting, function(e) { + return e.status == "waiting"; + }) + ); + } + + if (scope.filterPaused) { + categories.push( + _.filter(scope.waiting, function(e) { + return e.status == "paused"; + }) + ); + } + + if (scope.filterError) { + categories.push( + _.filter(scope.stopped, function(e) { + return e.status == "error"; + }) + ); + } + + if (scope.filterComplete) { + categories.push( + _.filter(scope.stopped, function(e) { + return e.status == "complete"; + }) + ); + } + + if (scope.filterRemoved) { + categories.push( + _.filter(scope.stopped, function(e) { + return e.status == "removed"; + }) + ); + } + + var downloads = categories + .map(function(category) { + // sort downloads within category by completness, most completed first + return _.sortBy(category, function(e) { + return -(e.completedLength / e.totalLength); + }); + }) + .reduce(function(downloads, category) { + return downloads.concat(category); + }, []); + + downloads = scope.filterDownloads(downloads); + + scope.totalDownloads = downloads.length; + + downloads = downloads.slice((scope.currentPage - 1) * scope.pageSize); + downloads.splice(scope.pageSize); + + return downloads; + }; + + scope.hasDirectURL = function() { + return rpc.getDirectURL() != ""; + }; + + scope.getDirectURL = function() { + return rpc.getDirectURL(); + }; + + // convert the donwload form aria2 to once used by the view, + // minor additions of some fields and checks + scope.getCtx = function(d, ctx) { + if (!ctx) { + ctx = { + dir: d.dir, + status: d.status, + gid: d.gid, + followedBy: d.followedBy && d.followedBy.length == 1 ? d.followedBy[0] : null, + followedFrom: null, + numPieces: d.numPieces, + connections: d.connections, + connectionsTitle: "Connections", + numSeeders: d.numSeeders, + bitfield: d.bitfield, + errorCode: d.errorCode, + totalLength: d.totalLength, + fmtTotalLength: utils.fmtsize(d.totalLength), + completedLength: d.completedLength, + fmtCompletedLength: utils.fmtsize(d.completedLength), + uploadLength: d.uploadLength, + fmtUploadLength: utils.fmtsize(d.uploadLength), + pieceLength: d.pieceLength, + fmtPieceLength: utils.fmtsize(d.pieceLength), + downloadSpeed: d.downloadSpeed, + fmtDownloadSpeed: utils.fmtspeed(d.downloadSpeed), + uploadSpeed: d.uploadSpeed, + fmtUploadSpeed: utils.fmtspeed(d.uploadSpeed), + collapsed: true, + animCollapsed: true, + files: [] + }; + if (d.verifiedLength) { + ctx.verifiedLength = d.verifiedLength; + ctx.status = "verifing"; + } + if (d.verifyIntegrityPending) { + ctx.verifyIntegrityPending = d.verifyIntegrityPending; + ctx.status = "verifyPending"; + } + } else { + if (ctx.gid !== d.gid) ctx.files = []; + ctx.dir = d.dir; + ctx.status = d.status; + if (d.verifiedLength) ctx.status = "verifing"; + if (d.verifyIntegrityPending) ctx.status = "verifyPending"; + ctx.errorCode = d.errorCode; + ctx.gid = d.gid; + ctx.followedBy = d.followedBy && d.followedBy.length == 1 ? d.followedBy[0] : null; + ctx.followedFrom = null; + ctx.numPieces = d.numPieces; + ctx.connections = d.connections; + if (typeof d.numSeeders === "undefined") { + ctx.numSeeders = ""; + } else { + ctx.connectionsTitle = "Connections (Seeders)"; + ctx.numSeeders = " (" + d.numSeeders + ")"; + } + ctx.bitfield = d.bitfield; + if (ctx.totalLength !== d.totalLength) { + ctx.totalLength = d.totalLength; + ctx.fmtTotalLength = utils.fmtsize(d.totalLength); + } + if (ctx.completedLength !== d.completedLength) { + ctx.completedLength = d.completedLength; + ctx.fmtCompletedLength = utils.fmtsize(d.completedLength); + } + if (!d.verifiedLength) { + delete ctx.verifiedLength; + } else if (ctx.verifiedLength !== d.verifiedLength) { + ctx.verifiedLength = d.verifiedLength; + } + if (!d.verifyIntegrityPending) { + delete ctx.verifyIntegrityPending; + } else if (ctx.verifyIntegrityPending !== d.verifyIntegrityPending) { + ctx.verifyIntegrityPending = d.verifyIntegrityPending; + } + if (ctx.uploadLength !== d.uploadLength) { + ctx.uploadLength = d.uploadLength; + ctx.fmtUploadLength = utils.fmtsize(d.uploadLength); + } + if (ctx.pieceLength !== d.pieceLength) { + ctx.pieceLength = d.pieceLength; + ctx.fmtPieceLength = utils.fmtsize(d.pieceLength); + } + if (ctx.downloadSpeed !== d.downloadSpeed) { + ctx.downloadSpeed = d.downloadSpeed; + ctx.fmtDownloadSpeed = utils.fmtspeed(d.downloadSpeed); + } + if (ctx.uploadSpeed !== d.uploadSpeed) { + ctx.uploadSpeed = d.uploadSpeed; + ctx.fmtUploadSpeed = utils.fmtspeed(d.uploadSpeed); + } + } + + var dlName; + var files = d.files; + if (files) { + var cfiles = ctx.files; + for (var i = 0; i < files.length; ++i) { + var cfile = cfiles[i] || (cfiles[i] = {}); + var file = files[i]; + if (file.path !== cfile.path) { + cfile.index = +file.index; + cfile.path = file.path; + cfile.length = file.length; + cfile.fmtLength = utils.fmtsize(file.length); + cfile.relpath = file.path.replace(re_slashes, slash); + if (!cfile.relpath) { + cfile.relpath = (file.uris && file.uris[0] && file.uris[0].uri) || "Unknown"; + } else if (!cfile.relpath.startsWith("[")) { + // METADATA + cfile.relpath = cfile.relpath.substr(ctx.dir.length + 1); + } + } + cfile.selected = file.selected === "true"; + } + cfiles.length = files.length; + if (cfiles.length) { + dlName = cfiles[0].relpath; + } + } else { + delete ctx.files; + } + + var btName; + if (d.bittorrent) { + btName = d.bittorrent.info && d.bittorrent.info.name; + ctx.bittorrent = true; + } else { + delete ctx.bittorrent; + } + + ctx.name = btName || dlName || "Unknown"; + ctx.metadata = ctx.name.startsWith("[METADATA]"); + if (ctx.metadata) { + ctx.name = ctx.name.substr(10); + } + + return ctx; + }; + + scope.hasStatus = function hasStatus(d, status) { + if (_.isArray(status)) { + if (status.length == 0) return false; + return hasStatus(d, status[0]) || hasStatus(d, status.slice(1)); + } else { + return d.status == status; + } + }; + + // get time left for the download with + // current download speed, + // could be smarter by different heuristics + scope.getEta = function(d) { + return (d.totalLength - d.completedLength) / d.downloadSpeed; + }; + + scope.getProgressClass = function(d) { + switch (d.status) { + case "paused": + return "progress-bar-info"; + case "error": + return "progress-bar-danger"; + case "removed": + return "progress-bar-warning"; + case "active": + return "active"; + case "verifing": + return "progress-bar-warning"; + case "complete": + return "progress-bar-success"; + default: + return ""; + } + }; + + // gets the progress in percentages + scope.getProgress = function(d) { + var percentage = 0; + if (d.verifiedLength) percentage = (d.verifiedLength / d.totalLength) * 100 || 0; + else percentage = (d.completedLength / d.totalLength) * 100 || 0; + percentage = percentage.toFixed(2); + if (!percentage) percentage = 0; + + return percentage; + }; + + // gets the upload ratio + scope.getRatio = function(d) { + var ratio = 0; + ratio = d.uploadLength / d.completedLength || 0; + ratio = ratio.toFixed(2); + if (!ratio) ratio = 0; + + return ratio; + }; + + // gets the type for the download as classified by the aria2 rpc calls + scope.getType = function(d) { + var type = d.status; + if (type == "paused") type = "waiting"; + if (["error", "removed", "complete"].indexOf(type) != -1) type = "stopped"; + return type; + }; + + scope.selectFiles = function(d) { + console.log("got back files for the torrent ..."); + modals.invoke("selectFiles", d.files, function(files) { + var indexes = ""; + _.forEach(files, function(f) { + if (f.selected) { + indexes += "," + f.index; + } + }); + + indexes = indexes.slice(1); + rpc.once("changeOption", [d.gid, { "select-file": indexes }], function(res) { + console.log("changed indexes to:", indexes, res); + }); + }); + }; + + scope.showSettings = function(d) { + var type = scope.getType(d), + settings = {}; + + rpc.once("getOption", [d.gid], function(data) { + var vals = data[0]; + + var sets = _.cloneDeep(fsettings); + for (var i in sets) { + if (type == "active" && activeInclude.indexOf(i) == -1) continue; + + if (type == "waiting" && waitingExclude.indexOf(i) != -1) continue; + + settings[i] = sets[i]; + settings[i].val = vals[i] || settings[i].val; + } + + modals.invoke("settings", settings, d.name + " settings", "Change", function(settings) { + var sets = {}; + for (var i in settings) { + sets[i] = settings[i].val; + } + + rpc.once("changeOption", [d.gid, sets]); + }); + }); + + return false; + }; + scope.moveDown = function(d) { + rpc.once("changePosition", [d.gid, 1, "POS_CUR"]); + }; + scope.moveUp = function(d) { + rpc.once("changePosition", [d.gid, -1, "POS_CUR"]); + }; + } + ]) + .filter("objFilter", function() { + return function(input, filter) { + input = input || {}; + var out = {}; + + for (key in input) { + if (key.startsWith(filter)) { + out[key] = input[key]; + } + } + + return out; + }; + }); diff --git a/js/ctrls/modal.js b/js/ctrls/modal.js index 55d9c6d5..44956dda 100644 --- a/js/ctrls/modal.js +++ b/js/ctrls/modal.js @@ -3,7 +3,7 @@ var parseFiles = function(files, cb) { var txts = []; var onload = function(res) { var txt = res.target.result; - txts.push(txt.split(',')[1]); + txts.push(txt.split(",")[1]); cnt--; if (!cnt) { cb(txts); @@ -11,13 +11,13 @@ var parseFiles = function(files, cb) { }; _.each(files, function(file) { cnt++; - console.log('starting file reader'); + console.log("starting file reader"); var reader = new FileReader(); reader.onload = onload; reader.onerror = function(err) { // return error // TODO: find a better way to propogate error upstream - console.log('got back error', err); + console.log("got back error", err); cb([]); }; reader.readAsDataURL(file); @@ -25,261 +25,294 @@ var parseFiles = function(files, cb) { }; angular -.module('webui.ctrls.modal', [ - "ui.bootstrap", 'webui.services.deps', 'webui.services.modals', 'webui.services.rpc', - 'webui.services.configuration' -]) -.controller('ModalCtrl', [ - '$_', '$scope', '$modal', "$modals", '$rpc','$fileSettings', '$downloadProps', - function(_, scope, $modal, modals, rpc, fsettings, dprops) { + .module("webui.ctrls.modal", [ + "ui.bootstrap", + "webui.services.deps", + "webui.services.modals", + "webui.services.rpc", + "webui.services.configuration" + ]) + .controller("ModalCtrl", [ + "$_", + "$scope", + "$modal", + "$modals", + "$rpc", + "$fileSettings", + "$downloadProps", + function(_, scope, $modal, modals, rpc, fsettings, dprops) { + scope.getUris = { + open: function(cb) { + var self = this; + this.uris = ""; + this.downloadSettingsCollapsed = true; + this.advancedSettingsCollapsed = true; + this.settings = {}; + this.fsettings = _.cloneDeep(fsettings); + this.cb = cb; - scope.getUris = { - open: function(cb) { - var self = this; - this.uris = ""; - this.downloadSettingsCollapsed = true; - this.advancedSettingsCollapsed = true; - this.settings = {}; - this.fsettings = _.cloneDeep(fsettings); - this.cb = cb; - - // fill in default download properties - _.forEach(dprops, function(p) { - self.settings[p] = self.fsettings[p]; - delete self.fsettings[p]; - }); + // fill in default download properties + _.forEach(dprops, function(p) { + self.settings[p] = self.fsettings[p]; + delete self.fsettings[p]; + }); - this.inst = $modal.open({ - templateUrl: "getUris.html", - scope: scope, - windowClass: "modal-large" - }); - this.inst.result.then(function() { - delete self.inst; - if (self.cb) { - var settings = {}; - // no need to send in default values, just the changed ones - for (var i in self.settings) { - if (fsettings[i].val != self.settings[i].val) - settings[i] = self.settings[i].val; - } - for (var i in self.fsettings) { - if (fsettings[i].val != self.fsettings[i].val) - settings[i] = self.fsettings[i].val; - } + this.inst = $modal.open({ + templateUrl: "getUris.html", + scope: scope, + windowClass: "modal-large" + }); + this.inst.result.then( + function() { + delete self.inst; + if (self.cb) { + var settings = {}; + // no need to send in default values, just the changed ones + for (var i in self.settings) { + if (fsettings[i].val != self.settings[i].val) settings[i] = self.settings[i].val; + } + for (var i in self.fsettings) { + if (fsettings[i].val != self.fsettings[i].val) + settings[i] = self.fsettings[i].val; + } - console.log('sending settings:', settings); - self.cb(self.parse(), settings); - } - }, - function() { - delete self.inst; - }); - }, - parse: function() { - return _ - .chain(this.uris.trim().split(/\r?\n/g)) - .map(function(d) { - return _(d) - .replace(/["'][^"']*["']/g, function(c) { - return c.replace(/%/g,'%25').replace(/ /g,'%20'); + console.log("sending settings:", settings); + self.cb(self.parse(), settings); + } + }, + function() { + delete self.inst; + } + ); + }, + parse: function() { + return _.chain(this.uris.trim().split(/\r?\n/g)) + .map(function(d) { + return _(d) + .replace(/["'][^"']*["']/g, function(c) { + return c.replace(/%/g, "%25").replace(/ /g, "%20"); + }) + .trim() + .split(/\s+/g) + .map(function(c) { + return c + .replace(/%20/g, " ") + .replace(/%25/g, "%") + .replace(/["']/g, ""); + }); }) - .trim() - .split(/\s+/g) - .map(function(c) { - return c.replace(/%20/g,' ').replace(/%25/g,'%').replace(/["']/g,''); - }); - }) - .filter(function(d) { return d.length }) - .value(); - } - }; + .filter(function(d) { + return d.length; + }) + .value(); + } + }; - scope.settings = { - open: function(settings, title, actionText, cb) { - var self = this; - this.settings = settings; - this.title = title; - this.actionText = actionText; - this.inst = $modal.open({ - templateUrl: "settings.html", - scope: scope, - windowClass: "modal-large" - }); - this.inst.result.then(function() { - delete self.inst; - if (cb) { - cb(self.settings); + scope.settings = { + open: function(settings, title, actionText, cb) { + var self = this; + this.settings = settings; + this.title = title; + this.actionText = actionText; + this.inst = $modal.open({ + templateUrl: "settings.html", + scope: scope, + windowClass: "modal-large" + }); + this.inst.result.then( + function() { + delete self.inst; + if (cb) { + cb(self.settings); + } + }, + function() { + delete self.inst; + } + ); } - }, - function() { - delete self.inst; - }); - } - }; + }; - scope.selectFiles = { - open: function(files, cb) { - var self = this; + scope.selectFiles = { + open: function(files, cb) { + var self = this; - this.files = _.cloneDeep(files); - var groupFiles = function (files) { - // sort files alphabetically - files.sort(function (a, b) { + this.files = _.cloneDeep(files); + var groupFiles = function(files) { + // sort files alphabetically + files.sort(function(a, b) { if (a.relpath < b.relpath) { - return -1; + return -1; } else { - return 1; + return 1; } - }); - function OrganizedFolder () { + }); + function OrganizedFolder() { this.dirs = {}; this.files = []; this.show = false; this.selected = true; - } - var folder = new OrganizedFolder(), tmp; - for (var i = 0; i < files.length; i++) { + } + var folder = new OrganizedFolder(), + tmp; + for (var i = 0; i < files.length; i++) { tmp = folder; var str = files[i].relpath; var arr = str.split("/"); for (var j = 0; j < arr.length - 1; j++) { - if (!tmp.dirs[arr[j]]) { - tmp.dirs[arr[j]] = new OrganizedFolder(); - } - tmp = tmp.dirs[arr[j]]; + if (!tmp.dirs[arr[j]]) { + tmp.dirs[arr[j]] = new OrganizedFolder(); + } + tmp = tmp.dirs[arr[j]]; } tmp.files.push(files[i]); - } - return folder; - }; - this.groupedFiles = groupFiles(this.files); - this.inst = $modal.open({ - templateUrl: "selectFiles.html", - scope: scope, - windowClass: "modal-large" - }); + } + return folder; + }; + this.groupedFiles = groupFiles(this.files); + this.inst = $modal.open({ + templateUrl: "selectFiles.html", + scope: scope, + windowClass: "modal-large" + }); - this.inst.result.then(function() { - delete self.inst; + this.inst.result.then( + function() { + delete self.inst; - if (cb) { - cb(self.files); + if (cb) { + cb(self.files); + } + }, + function() { + delete self.inst; + } + ); } - }, - function() { - delete self.inst; - }); - } - }; + }; - scope.connection = { - open: function(defaults, cb) { - var self = this; + scope.connection = { + open: function(defaults, cb) { + var self = this; - // XXX We need to actually clone this! - this.conf = rpc.getConfiguration(); - this.inst = $modal.open({ - templateUrl: "connection.html", - scope: scope, - windowClass: "modal-large", - }); + // XXX We need to actually clone this! + this.conf = rpc.getConfiguration(); + this.inst = $modal.open({ + templateUrl: "connection.html", + scope: scope, + windowClass: "modal-large" + }); - this.inst.result.then(function() { - delete self.inst; - if (cb) { - cb(self.conf); + this.inst.result.then( + function() { + delete self.inst; + if (cb) { + cb(self.conf); + } + }, + function() { + delete self.inst; + } + ); } - }, - function() { - delete self.inst; - }); - } - }; + }; - _.each(['getTorrents', 'getMetalinks'], function(name) { - scope[name] = { - open: function(cb) { - var self = this; - this.files = []; - this.collapsed = true; - this.settings = {}; - this.fsettings = _.cloneDeep(fsettings); + _.each(["getTorrents", "getMetalinks"], function(name) { + scope[name] = { + open: function(cb) { + var self = this; + this.files = []; + this.collapsed = true; + this.settings = {}; + this.fsettings = _.cloneDeep(fsettings); - // fill in default download properties - _.forEach(dprops, function(p) { - self.settings[p] = self.fsettings[p]; - delete self.fsettings[p]; - }); + // fill in default download properties + _.forEach(dprops, function(p) { + self.settings[p] = self.fsettings[p]; + delete self.fsettings[p]; + }); - this.inst = $modal.open({ - templateUrl: name + ".html", - scope: scope, - windowClass: "modal-large", - }); + this.inst = $modal.open({ + templateUrl: name + ".html", + scope: scope, + windowClass: "modal-large" + }); - this.inst.result.then(function() { - delete self.inst; - if (cb) { - parseFiles(self.files, function(txts) { - var settings = {}; + this.inst.result.then( + function() { + delete self.inst; + if (cb) { + parseFiles(self.files, function(txts) { + var settings = {}; - // no need to send in default values, just the changed ones - for (var i in self.settings) { - if (fsettings[i].val != self.settings[i].val) - settings[i] = self.settings[i].val; - } - for (var i in self.fsettings) { - if (fsettings[i].val != self.fsettings[i].val) - settings[i] = self.fsettings[i].val; + // no need to send in default values, just the changed ones + for (var i in self.settings) { + if (fsettings[i].val != self.settings[i].val) + settings[i] = self.settings[i].val; + } + for (var i in self.fsettings) { + if (fsettings[i].val != self.fsettings[i].val) + settings[i] = self.fsettings[i].val; + } + + console.log("sending settings:", settings); + cb(txts, settings); + }); + } + }, + function() { + delete self.inst; } + ); + } + }; + }); - console.log('sending settings:', settings); - cb(txts, settings); + _.each(["about", "server_info"], function(name) { + scope[name] = { + open: function() { + var self = this; + this.inst = $modal.open({ + templateUrl: name + ".html", + scope: scope }); + this.inst.result.then( + function() { + delete self.inst; + }, + function() { + delete self.inst; + } + ); } - }, - function() { - delete self.inst; - }); - } - }; - }); - - _.each(["about", "server_info"], function(name) { - scope[name] = { - open: function() { - var self = this; - this.inst = $modal.open({ - templateUrl: name + ".html", - scope: scope - }); - this.inst.result.then(function() { - delete self.inst; - }, - function() { - delete self.inst; - }); - } - }; - }); - - rpc.once('getVersion', [], function(data) { - scope.miscellaneous = data[0]; - }); + }; + }); - _.each([ - 'getUris', 'getTorrents', 'getMetalinks', 'selectFiles', - 'settings', 'connection', 'server_info', 'about' - ], function(name) { - modals.register(name, function() { - if (scope[name].inst) { - // Already open. - return; - } - var args = Array.prototype.slice.call(arguments, 0); - scope[name].open.apply(scope[name], args); - }); - }); + rpc.once("getVersion", [], function(data) { + scope.miscellaneous = data[0]; + }); -}]); + _.each( + [ + "getUris", + "getTorrents", + "getMetalinks", + "selectFiles", + "settings", + "connection", + "server_info", + "about" + ], + function(name) { + modals.register(name, function() { + if (scope[name].inst) { + // Already open. + return; + } + var args = Array.prototype.slice.call(arguments, 0); + scope[name].open.apply(scope[name], args); + }); + } + ); + } + ]); diff --git a/js/ctrls/nav.js b/js/ctrls/nav.js index affe3f61..782bab29 100644 --- a/js/ctrls/nav.js +++ b/js/ctrls/nav.js @@ -1,145 +1,148 @@ angular -.module('webui.ctrls.nav', [ - 'webui.services.configuration', 'webui.services.modals', - 'webui.services.rpc', 'webui.services.rpc.helpers', - 'webui.services.settings', 'webui.services.utils' -]) -.controller('NavCtrl', [ - '$scope', '$modals', - '$rpc', '$rpchelpers', '$fileSettings', - '$globalSettings', '$globalExclude', - '$utils', '$translate', '$filter', - function( - scope, modals, - rpc, rhelpers, fsettings, - gsettings, gexclude, - utils, translate, filter - ) { - - scope.isFeatureEnabled = function(f) { return rhelpers.isFeatureEnabled(f) }; - - // initially collapsed in mobile resolution - scope.collapsed = true; - - scope.onDownloadFilter = function() { - // Forward to MainCtrl. - scope.$parent.downloadFilter = scope.downloadFilter; - scope.$parent.onDownloadFilter(); - }; - - // manage download functions - scope.forcePauseAll = function() { - rpc.once('forcePauseAll', []); - } - - scope.purgeDownloadResult = function() { - rpc.once('purgeDownloadResult', []); - } - - scope.unpauseAll = function() { - rpc.once('unpauseAll', []); - } - - scope.addUris = function() { - modals.invoke( - 'getUris', _.bind(rhelpers.addUris, rhelpers) - ); - }; - - scope.addMetalinks = function() { - modals.invoke( - 'getMetalinks', _.bind(rhelpers.addMetalinks, rhelpers) - ); - }; - - scope.addTorrents = function() { - modals.invoke( - 'getTorrents', _.bind(rhelpers.addTorrents, rhelpers) - ); - }; - - scope.changeCSettings = function() { - modals.invoke( - 'connection', rpc.getConfiguration(), _.bind(rpc.configure, rpc) - ); - } - - scope.changeGSettings = function() { - rpc.once('getGlobalOption', [], function(data) { - var starred = utils.getCookie('aria2props'); - if (!starred || !starred.indexOf) starred = []; - var vals = data[0]; - var settings = {}; - - // global settings divided into - // file settings + some global specific - // settings - - _.forEach([fsettings, gsettings], function(sets) { - for (var i in sets) { - if (gexclude.indexOf(i) != -1) continue; - - settings[i] = _.cloneDeep(sets[i]); - settings[i].starred = starred.indexOf(i) != -1; - } - }); - - for (var i in vals) { - if (i in gexclude) continue; - - if (!(i in settings)) { - settings[i] = { name: i, val: vals[i], desc: '', starred: starred.indexOf(i) != -1 }; - } - - else { - settings[i].val = vals[i]; - } - } - - modals.invoke( - 'settings', _.cloneDeep(settings), - filter('translate')('Global Settings'), - filter('translate')('Save'), - function(chsettings) { - - var sets = {}; - var starred = []; - for (var i in chsettings) { - // no need to change default values - if (settings[i].val != chsettings[i].val) - sets[i] = chsettings[i].val - - if (chsettings[i].starred) { - starred.push(i); - } - }; - - console.log('saving aria2 settings:', sets); - console.log('saving aria2 starred:', starred); - - rpc.once('changeGlobalOption', [sets]); - utils.setCookie('aria2props', starred); - }); - }); - }; - - scope.showServerInfo = function() { - modals.invoke( - 'server_info' - ); - }; - - scope.showAbout = function() { - modals.invoke( - 'about' - ); - }; - - scope.changeLanguage = function (langkey) { - translate.use(langkey); - }; - - scope.shutDownServer = function () { - rpc.once('shutdown', []); - }; -}]); + .module("webui.ctrls.nav", [ + "webui.services.configuration", + "webui.services.modals", + "webui.services.rpc", + "webui.services.rpc.helpers", + "webui.services.settings", + "webui.services.utils" + ]) + .controller("NavCtrl", [ + "$scope", + "$modals", + "$rpc", + "$rpchelpers", + "$fileSettings", + "$globalSettings", + "$globalExclude", + "$utils", + "$translate", + "$filter", + function( + scope, + modals, + rpc, + rhelpers, + fsettings, + gsettings, + gexclude, + utils, + translate, + filter + ) { + scope.isFeatureEnabled = function(f) { + return rhelpers.isFeatureEnabled(f); + }; + + // initially collapsed in mobile resolution + scope.collapsed = true; + + scope.onDownloadFilter = function() { + // Forward to MainCtrl. + scope.$parent.downloadFilter = scope.downloadFilter; + scope.$parent.onDownloadFilter(); + }; + + // manage download functions + scope.forcePauseAll = function() { + rpc.once("forcePauseAll", []); + }; + + scope.purgeDownloadResult = function() { + rpc.once("purgeDownloadResult", []); + }; + + scope.unpauseAll = function() { + rpc.once("unpauseAll", []); + }; + + scope.addUris = function() { + modals.invoke("getUris", _.bind(rhelpers.addUris, rhelpers)); + }; + + scope.addMetalinks = function() { + modals.invoke("getMetalinks", _.bind(rhelpers.addMetalinks, rhelpers)); + }; + + scope.addTorrents = function() { + modals.invoke("getTorrents", _.bind(rhelpers.addTorrents, rhelpers)); + }; + + scope.changeCSettings = function() { + modals.invoke("connection", rpc.getConfiguration(), _.bind(rpc.configure, rpc)); + }; + + scope.changeGSettings = function() { + rpc.once("getGlobalOption", [], function(data) { + var starred = utils.getCookie("aria2props"); + if (!starred || !starred.indexOf) starred = []; + var vals = data[0]; + var settings = {}; + + // global settings divided into + // file settings + some global specific + // settings + + _.forEach([fsettings, gsettings], function(sets) { + for (var i in sets) { + if (gexclude.indexOf(i) != -1) continue; + + settings[i] = _.cloneDeep(sets[i]); + settings[i].starred = starred.indexOf(i) != -1; + } + }); + + for (var i in vals) { + if (i in gexclude) continue; + + if (!(i in settings)) { + settings[i] = { name: i, val: vals[i], desc: "", starred: starred.indexOf(i) != -1 }; + } else { + settings[i].val = vals[i]; + } + } + + modals.invoke( + "settings", + _.cloneDeep(settings), + filter("translate")("Global Settings"), + filter("translate")("Save"), + function(chsettings) { + var sets = {}; + var starred = []; + for (var i in chsettings) { + // no need to change default values + if (settings[i].val != chsettings[i].val) sets[i] = chsettings[i].val; + + if (chsettings[i].starred) { + starred.push(i); + } + } + + console.log("saving aria2 settings:", sets); + console.log("saving aria2 starred:", starred); + + rpc.once("changeGlobalOption", [sets]); + utils.setCookie("aria2props", starred); + } + ); + }); + }; + + scope.showServerInfo = function() { + modals.invoke("server_info"); + }; + + scope.showAbout = function() { + modals.invoke("about"); + }; + + scope.changeLanguage = function(langkey) { + translate.use(langkey); + }; + + scope.shutDownServer = function() { + rpc.once("shutdown", []); + }; + } + ]); diff --git a/js/ctrls/props.js b/js/ctrls/props.js index 9a33bfd5..eeb4b366 100644 --- a/js/ctrls/props.js +++ b/js/ctrls/props.js @@ -1,85 +1,93 @@ -angular.module('webui.ctrls.props', [ - 'webui.services.utils', 'webui.services.settings', 'webui.services.deps', - 'webui.services.rpc', 'webui.services.configuration', -]) -.controller('StarredPropsCtrl', ['$scope', '$_', '$utils', '$rpc', '$globalSettings', '$fileSettings', '$starredProps', - function(scope, _, utils, rpc, gsettings, fsettings, starredProps) { - scope._props = []; - scope.dirty = true; - scope.properties = []; - scope.getProps = function() { - var props = utils.getCookie('aria2props'); - if (!props || !props.indexOf) props = starredProps; // default properties starred in the global configuration file +angular + .module("webui.ctrls.props", [ + "webui.services.utils", + "webui.services.settings", + "webui.services.deps", + "webui.services.rpc", + "webui.services.configuration" + ]) + .controller("StarredPropsCtrl", [ + "$scope", + "$_", + "$utils", + "$rpc", + "$globalSettings", + "$fileSettings", + "$starredProps", + function(scope, _, utils, rpc, gsettings, fsettings, starredProps) { + scope._props = []; + scope.dirty = true; + scope.properties = []; + scope.getProps = function() { + var props = utils.getCookie("aria2props"); + if (!props || !props.indexOf) props = starredProps; // default properties starred in the global configuration file - return props; - }; + return props; + }; - scope.enabled = function() { - for (var i = 0; i < scope.properties.length; i++) { - if (scope.properties[i]._val != scope.properties[i].val) return true; - } + scope.enabled = function() { + for (var i = 0; i < scope.properties.length; i++) { + if (scope.properties[i]._val != scope.properties[i].val) return true; + } - return false; - } + return false; + }; - scope.save = function() { - var sets = {}; - var found = false; - for (var i = 0; i < scope.properties.length; i++) { - if (scope.properties[i]._val != scope.properties[i].val) { - sets[scope.properties[i].name] = scope.properties[i].val; - found = true; - } - } + scope.save = function() { + var sets = {}; + var found = false; + for (var i = 0; i < scope.properties.length; i++) { + if (scope.properties[i]._val != scope.properties[i].val) { + sets[scope.properties[i].name] = scope.properties[i].val; + found = true; + } + } - if (found) { - rpc.once('changeGlobalOption', [sets]); - } - } + if (found) { + rpc.once("changeGlobalOption", [sets]); + } + }; - rpc.subscribe('getGlobalOption', [], function(data) { - var vals = data[0]; - var props = scope.getProps(); - var arr = []; + rpc.subscribe("getGlobalOption", [], function(data) { + var vals = data[0]; + var props = scope.getProps(); + var arr = []; - for (var i = 0; i < props.length; i++) { - var set = {}; - if (props[i] in gsettings) { - set = gsettings[props[i]]; - if (props[i] in vals) { - set.val = vals[props[i]]; - } - set.name = props[i]; - arr.push(set); - } - else if (props[i] in fsettings) { - set = fsettings[props[i]]; - if (props[i] in vals) { - set.val = vals[props[i]]; + for (var i = 0; i < props.length; i++) { + var set = {}; + if (props[i] in gsettings) { + set = gsettings[props[i]]; + if (props[i] in vals) { + set.val = vals[props[i]]; + } + set.name = props[i]; + arr.push(set); + } else if (props[i] in fsettings) { + set = fsettings[props[i]]; + if (props[i] in vals) { + set.val = vals[props[i]]; + } + set.name = props[i]; + arr.push(set); + } else if (props[i] in vals) { + arr.push({ name: props[i], val: vals[props[i]] }); + } } - set.name = props[i]; - arr.push(set); - } - else if (props[i] in vals) { - arr.push({name: props[i], val: vals[props[i]]}); - } - } - - utils.mergeMap(arr, scope.properties, function(prop, nprop) { - nprop = nprop || {}; - nprop.name = prop.name; - nprop.options = prop.options; - nprop.multiline = prop.multiline; - if (nprop._val == nprop.val || nprop.val == prop.val) { - nprop._val = prop.val; - nprop.val = prop.val; - } - else { - nprop._val = prop.val; - } - nprop.desc = prop.desc; - return nprop; - }); - }); -}]); + utils.mergeMap(arr, scope.properties, function(prop, nprop) { + nprop = nprop || {}; + nprop.name = prop.name; + nprop.options = prop.options; + nprop.multiline = prop.multiline; + if (nprop._val == nprop.val || nprop.val == prop.val) { + nprop._val = prop.val; + nprop.val = prop.val; + } else { + nprop._val = prop.val; + } + nprop.desc = prop.desc; + return nprop; + }); + }); + } + ]); diff --git a/js/directives/chunkbar.js b/js/directives/chunkbar.js index 9391377c..8aa833ce 100644 --- a/js/directives/chunkbar.js +++ b/js/directives/chunkbar.js @@ -1,49 +1,50 @@ var draw = function(canvas, chunks, fillStyle) { chunks = chunks || []; if (!canvas.getContext) { - console.log('use chunk bar on an canvas implementation!'); + console.log("use chunk bar on an canvas implementation!"); return; } - var ctx = canvas.getContext('2d'); + var ctx = canvas.getContext("2d"); ctx.fillStyle = fillStyle || "#149BDF"; ctx.clearRect(0, 0, canvas.width, canvas.height); var x = 0, - width = canvas.width, - height = canvas.height; + width = canvas.width, + height = canvas.height; chunks.forEach(function(c) { var dx = c.ratio * width; - if (c.show) - ctx.fillRect(x, 0, dx, height); + if (c.show) ctx.fillRect(x, 0, dx, height); x += dx; }); }; // put chunkbar and bitfield attributes in a canvas element // to use the directive, draw is optional and canvas is // only drawn when it is true if given -angular -.module('webui.directives.chunkbar', ['webui.services.utils']) -.directive('chunkbar', ['$utils', function(utils) { - return function(scope, elem, attrs) { - var bitfield = "", pieces = 0, canDraw = true; - var update = function() { - if (canDraw) - draw(elem[0], utils.getChunksFromHex(bitfield, pieces), attrs.fillStyle); - }; - scope.$watch(attrs.bitfield, function(bf) { - bitfield = bf; - update(); - }); - scope.$watch(attrs.pieces, function(p) { - pieces = p; - update(); - }); - - if (attrs.draw) { - scope.$watch(attrs.draw, function(val) { - canDraw = val; +angular.module("webui.directives.chunkbar", ["webui.services.utils"]).directive("chunkbar", [ + "$utils", + function(utils) { + return function(scope, elem, attrs) { + var bitfield = "", + pieces = 0, + canDraw = true; + var update = function() { + if (canDraw) draw(elem[0], utils.getChunksFromHex(bitfield, pieces), attrs.fillStyle); + }; + scope.$watch(attrs.bitfield, function(bf) { + bitfield = bf; + update(); + }); + scope.$watch(attrs.pieces, function(p) { + pieces = p; + update(); }); - } - update(); - }; -}]); + if (attrs.draw) { + scope.$watch(attrs.draw, function(val) { + canDraw = val; + }); + } + + update(); + }; + } +]); diff --git a/js/directives/dgraph.js b/js/directives/dgraph.js index 32b0787a..ad2d4c94 100644 --- a/js/directives/dgraph.js +++ b/js/directives/dgraph.js @@ -2,154 +2,158 @@ // the last 180 secs, it also takes draw as an optional attribute and only // draws the graph when it is true, if not given then graph is always drawn angular -.module('webui.directives.dgraph', ['webui.filters.bytes', 'webui.services.deps']) -.directive('dgraph', ['$', '$filter', '$parse', function($, filter, parse) { - var ratio = 0.6; - var xfmt = "%H:%M:%S"; - var yTicks = 7; // Number of y-axis ticks (sans 0) - var xticks = 10; // Number of x-axis ticks (sans 0) - var yTickBase = 10240; // y-axis ticks must be a multiple of this (bytes). - try { - // Try to detect AM/PM locales. - if (!/16/.test(new Date(2000,0,1,16,7,9).toLocaleTimeString())) { - xfmt = "%I:%M:%S %P"; - } - } - catch (ex) { - // Ignore. Browser does not support toLocaleTimeString. - } - - return function(scope, elem, attrs) { - var canDraw = false; - - var graphSize = 180 - , dspeed = 0, uspeed = 0, hasSpeeds = false - , dconf = { - label: "DOWN", - data: [], - color: "#00ff00", - lines: { show: true } - } - , uconf = { - label: "UP", - data: [], - color: "#0000ff", - lines: { show: true } - } - ; - - // hack for the null height for flot elem - elem.height(elem.width() * ratio); - var graph = $.plot(elem, [dconf, uconf], { - legend: { - show: (attrs.nolabel == undefined), - backgroundOpacity: 0, - margin: [10, 20], - labelFormatter: function(label, series) { - if (!series.data.length) { - return label; - } - return label + " (" + filter("bspeed")(series.data[series.data.length-1][1]) + ")"; - }, - position: "sw" - }, - xaxis: { - show: true, - mode: "time", - timeformat: xfmt, - ticks: +attrs.xticks || xticks, // allow users of the directive to overwride xticks - minTickSize: [30, "second"] // 180 / 30 == 6 - }, - yaxis: { - position: "right", - ticks: function(axis) { - var res = [0]; - yt = +attrs.yticks || yticks; // allow users of directive to overwride yticks - - var step = yTickBase * Math.max(1, Math.ceil(axis.max / (yt * yTickBase))) - - for (var s = 0; s < yt; s++) { - var c = step * s; - if (c > axis.max) - break; - - res.push(step * s); - } - - return res; - }, - tickFormatter: function(val, axis) { - return filter('bspeed')(val); - }, - min: 0 + .module("webui.directives.dgraph", ["webui.filters.bytes", "webui.services.deps"]) + .directive("dgraph", [ + "$", + "$filter", + "$parse", + function($, filter, parse) { + var ratio = 0.6; + var xfmt = "%H:%M:%S"; + var yTicks = 7; // Number of y-axis ticks (sans 0) + var xticks = 10; // Number of x-axis ticks (sans 0) + var yTickBase = 10240; // y-axis ticks must be a multiple of this (bytes). + try { + // Try to detect AM/PM locales. + if (!/16/.test(new Date(2000, 0, 1, 16, 7, 9).toLocaleTimeString())) { + xfmt = "%I:%M:%S %P"; + } + } catch (ex) { + // Ignore. Browser does not support toLocaleTimeString. } - }); - var draw = function() { - var width = elem.width(); - if (width == 0) return; + return function(scope, elem, attrs) { + var canDraw = false; + + var graphSize = 180, + dspeed = 0, + uspeed = 0, + hasSpeeds = false, + dconf = { + label: "DOWN", + data: [], + color: "#00ff00", + lines: { show: true } + }, + uconf = { + label: "UP", + data: [], + color: "#0000ff", + lines: { show: true } + }; + + // hack for the null height for flot elem + elem.height(elem.width() * ratio); + var graph = $.plot(elem, [dconf, uconf], { + legend: { + show: attrs.nolabel == undefined, + backgroundOpacity: 0, + margin: [10, 20], + labelFormatter: function(label, series) { + if (!series.data.length) { + return label; + } + return label + " (" + filter("bspeed")(series.data[series.data.length - 1][1]) + ")"; + }, + position: "sw" + }, + xaxis: { + show: true, + mode: "time", + timeformat: xfmt, + ticks: +attrs.xticks || xticks, // allow users of the directive to overwride xticks + minTickSize: [30, "second"] // 180 / 30 == 6 + }, + yaxis: { + position: "right", + ticks: function(axis) { + var res = [0]; + yt = +attrs.yticks || yticks; // allow users of directive to overwride yticks + + var step = yTickBase * Math.max(1, Math.ceil(axis.max / (yt * yTickBase))); + + for (var s = 0; s < yt; s++) { + var c = step * s; + if (c > axis.max) break; + + res.push(step * s); + } + + return res; + }, + tickFormatter: function(val, axis) { + return filter("bspeed")(val); + }, + min: 0 + } + }); - elem.height(width * ratio); + var draw = function() { + var width = elem.width(); + if (width == 0) return; - graph.setData([dconf, uconf]); - graph.resize(); - graph.setupGrid(); - graph.draw(); - }; + elem.height(width * ratio); - function update() { - if (!hasSpeeds) { - return; - } + graph.setData([dconf, uconf]); + graph.resize(); + graph.setupGrid(); + graph.draw(); + }; - // Convoluted way to get the local date timestamp instead of the UTC one. - var cnt = new Date(); - cnt = Date.UTC( - cnt.getFullYear(), - cnt.getMonth(), - cnt.getDate(), - cnt.getHours(), - cnt.getMinutes(), - cnt.getSeconds()); - - if (dconf.data.length === graphSize) dconf.data.shift(); - dconf.data.push([cnt, dspeed]); - - if (uconf.data.length === graphSize) uconf.data.shift(); - uconf.data.push([cnt, uspeed]); - - // if any parents is collapsable, then confirm if it isnt - if (canDraw) { - draw(); - } - }; + function update() { + if (!hasSpeeds) { + return; + } - scope.$watch(attrs.dspeed, function(val) { - if (val === undefined) { - return; - } - hasSpeeds = true; - dspeed = parseFloat(val) || 0; - }); + // Convoluted way to get the local date timestamp instead of the UTC one. + var cnt = new Date(); + cnt = Date.UTC( + cnt.getFullYear(), + cnt.getMonth(), + cnt.getDate(), + cnt.getHours(), + cnt.getMinutes(), + cnt.getSeconds() + ); + + if (dconf.data.length === graphSize) dconf.data.shift(); + dconf.data.push([cnt, dspeed]); + + if (uconf.data.length === graphSize) uconf.data.shift(); + uconf.data.push([cnt, uspeed]); + + // if any parents is collapsable, then confirm if it isnt + if (canDraw) { + draw(); + } + } - scope.$watch(attrs.uspeed, function(val) { - if (val === undefined) { - return; - } - hasSpeeds = true; - uspeed = parseFloat(val) || 0; - }); + scope.$watch(attrs.dspeed, function(val) { + if (val === undefined) { + return; + } + hasSpeeds = true; + dspeed = parseFloat(val) || 0; + }); - scope.$watch(attrs.draw, function(val) { - canDraw = val; - }); + scope.$watch(attrs.uspeed, function(val) { + if (val === undefined) { + return; + } + hasSpeeds = true; + uspeed = parseFloat(val) || 0; + }); - var interval = setInterval(update, 1000); + scope.$watch(attrs.draw, function(val) { + canDraw = val; + }); - angular.element(window).bind('resize', draw); - elem.bind('$destroy', function() { - clearInterval(interval); - }); + var interval = setInterval(update, 1000); - }; -}]); + angular.element(window).bind("resize", draw); + elem.bind("$destroy", function() { + clearInterval(interval); + }); + }; + } + ]); diff --git a/js/directives/fileselect.js b/js/directives/fileselect.js index 08904c36..2f13e653 100644 --- a/js/directives/fileselect.js +++ b/js/directives/fileselect.js @@ -2,125 +2,152 @@ // puts the files selected in an attribute var app = angular.module("webui.directives.fileselect", ["webui.services.deps"]); app.directive("indeterminate", [ - "$parse", function syncInput (parse) { - return { - require : "ngModel", - // Restrict the directive so it can only be used as an attribute - restrict : "A", + "$parse", + function syncInput(parse) { + return { + require: "ngModel", + // Restrict the directive so it can only be used as an attribute + restrict: "A", - link : function link (scope, elem, attr, ngModelCtrl) { - // Whenever the bound value of the attribute changes we update - // use upward emit notification for change to prevent the performance penalty bring by $scope.$watch - var getter = parse(attr["ngModel"]); - // var setter = getter.assign; - var children = []; // cache children input - var cacheSelectedSubInputNumber = 0; - var cacheNoSelectedSubInputNumber = 0; - var get = function () { - return getter(scope); - }; - // the internal 'indeterminate' flag on the attached dom element - var setIndeterminateState = function (newValue) { - elem.prop("indeterminate", newValue); - }; - var setModelValueWithSideEffect = function (newVal) { // will cause to emit corresponding events - ngModelCtrl.$setViewValue(newVal); - ngModelCtrl.$render(); - }; - var passIfIsLeafChild = function (callback) { // ensure to execute callback only when this input has one or more subinputs - return function () { - if (children.length > 0) { - callback.apply(this, arguments); - } - }; - }; - var passIfNotIsLeafChild = function (callback) { // ensure to execute callback only when this input hasn't any subinput - return function () { - if (children.length === 0) { - callback.apply(this, arguments); - } - }; - }; - var passThroughThisScope = function (callback) { // pass through the event from the scope where they sent - return function (event) { - if (event.targetScope !== event.currentScope) { - return callback.apply(this, arguments); - } - }; - }; - var passIfIsIndeterminate = function (callback) { // pass through the event when this input is indeterminate - return function () { - if (!elem.prop("indeterminate")) { - return callback.apply(this, arguments); - } - }; - }; - /* var catchEventOnlyOnce = function (callback) { // only fire once, and stop event's propagation + link: function link(scope, elem, attr, ngModelCtrl) { + // Whenever the bound value of the attribute changes we update + // use upward emit notification for change to prevent the performance penalty bring by $scope.$watch + var getter = parse(attr["ngModel"]); + // var setter = getter.assign; + var children = []; // cache children input + var cacheSelectedSubInputNumber = 0; + var cacheNoSelectedSubInputNumber = 0; + var get = function() { + return getter(scope); + }; + // the internal 'indeterminate' flag on the attached dom element + var setIndeterminateState = function(newValue) { + elem.prop("indeterminate", newValue); + }; + var setModelValueWithSideEffect = function(newVal) { + // will cause to emit corresponding events + ngModelCtrl.$setViewValue(newVal); + ngModelCtrl.$render(); + }; + var passIfIsLeafChild = function(callback) { + // ensure to execute callback only when this input has one or more subinputs + return function() { + if (children.length > 0) { + callback.apply(this, arguments); + } + }; + }; + var passIfNotIsLeafChild = function(callback) { + // ensure to execute callback only when this input hasn't any subinput + return function() { + if (children.length === 0) { + callback.apply(this, arguments); + } + }; + }; + var passThroughThisScope = function(callback) { + // pass through the event from the scope where they sent + return function(event) { + if (event.targetScope !== event.currentScope) { + return callback.apply(this, arguments); + } + }; + }; + var passIfIsIndeterminate = function(callback) { + // pass through the event when this input is indeterminate + return function() { + if (!elem.prop("indeterminate")) { + return callback.apply(this, arguments); + } + }; + }; + /* var catchEventOnlyOnce = function (callback) { // only fire once, and stop event's propagation return function (event) { callback.apply(this, arguments); return event.stopPropagation(); }; }; */ - if (attr["indeterminate"] && parse(attr["indeterminate"]).constant) { - setIndeterminateState(scope.$eval(attr["indeterminate"])); // set to default value (set in template) - } - if (attr["indeterminate"] && parse(attr["indeterminate"]).constant && !scope.$eval(attr["indeterminate"])) { - // when this input wont have subinput, they will only receive parent change and emit child change event - ngModelCtrl.$viewChangeListeners.push(passIfNotIsLeafChild(function () { - scope.$emit("childSelectedChange", get()); // notifies parents to change their state - })); - scope.$on("ParentSelectedChange", passThroughThisScope(passIfNotIsLeafChild( - function (event, newVal) { - setModelValueWithSideEffect(newVal); // set value to parent's value; this will cause listener to emit childChange event; this won't be a infinite loop - }))); - // init first time and only once - scope.$emit("i'm child input", get); // traverses upwards toward the root scope notifying the listeners for keep reference to this input's value - scope.$emit("childSelectedChange", get()); // force emitted, and force the parent change their state base on children at first time + if (attr["indeterminate"] && parse(attr["indeterminate"]).constant) { + setIndeterminateState(scope.$eval(attr["indeterminate"])); // set to default value (set in template) + } + if ( + attr["indeterminate"] && + parse(attr["indeterminate"]).constant && + !scope.$eval(attr["indeterminate"]) + ) { + // when this input wont have subinput, they will only receive parent change and emit child change event + ngModelCtrl.$viewChangeListeners.push( + passIfNotIsLeafChild(function() { + scope.$emit("childSelectedChange", get()); // notifies parents to change their state + }) + ); + scope.$on( + "ParentSelectedChange", + passThroughThisScope( + passIfNotIsLeafChild(function(event, newVal) { + setModelValueWithSideEffect(newVal); // set value to parent's value; this will cause listener to emit childChange event; this won't be a infinite loop + }) + ) + ); + // init first time and only once + scope.$emit("i'm child input", get); // traverses upwards toward the root scope notifying the listeners for keep reference to this input's value + scope.$emit("childSelectedChange", get()); // force emitted, and force the parent change their state base on children at first time + } else { + // establish parent-child's relation + // listen for the child emitted token + scope.$on( + "i'm child input", + passThroughThisScope( + // can't apply pass passIfIsLeafChild, at beginning all has not child input + function(event, child) { + children.push(child); + } + ) + ); + var updateBaseOnChildrenState = function(event, newChildValue) { + if (cacheSelectedSubInputNumber + cacheNoSelectedSubInputNumber !== children.length) { + // cache childern state + cacheSelectedSubInputNumber = 0; + cacheNoSelectedSubInputNumber = 0; + for (var i = 0; i < children.length; i++) { + if (children[i]()) { + cacheSelectedSubInputNumber += 1; } else { - // establish parent-child's relation - // listen for the child emitted token - scope.$on("i'm child input", passThroughThisScope( // can't apply pass passIfIsLeafChild, at beginning all has not child input - function (event, child) { - children.push(child); - }) - ); - var updateBaseOnChildrenState = function (event, newChildValue) { - if ((cacheSelectedSubInputNumber + cacheNoSelectedSubInputNumber) !== children.length) { - // cache childern state - cacheSelectedSubInputNumber = 0; - cacheNoSelectedSubInputNumber = 0; - for (var i = 0; i < children.length; i++) { - if (children[i]()) { - cacheSelectedSubInputNumber += 1; - } else { - cacheNoSelectedSubInputNumber += 1; - } - } - } else { - // no need for recalculated children state - // just make a few change to cache value - if (newChildValue) { - cacheSelectedSubInputNumber++; - cacheNoSelectedSubInputNumber--; - } else { - cacheSelectedSubInputNumber--; - cacheNoSelectedSubInputNumber++; - } - } - var allSelected = (cacheNoSelectedSubInputNumber === 0); // if doesn't has any no selected input - var anySeleted = (cacheSelectedSubInputNumber > 0); - setIndeterminateState(allSelected !== anySeleted); // if at least one is selected, but not all then set input property indeterminate to true - setModelValueWithSideEffect(allSelected); // change binding model value and trigger onchange event - }; - // is not leaf input, Only receive child change and parent change event - ngModelCtrl.$viewChangeListeners.push(passIfIsLeafChild(passIfIsIndeterminate(function () { - // emit when input property indeterminate is false, prevent recursively emitting event from parent to children, children to parent - scope.$broadcast("ParentSelectedChange", get()); - }))); - // reset input state base on children inputs - scope.$on("childSelectedChange", passThroughThisScope(passIfIsLeafChild(updateBaseOnChildrenState))); + cacheNoSelectedSubInputNumber += 1; } + } + } else { + // no need for recalculated children state + // just make a few change to cache value + if (newChildValue) { + cacheSelectedSubInputNumber++; + cacheNoSelectedSubInputNumber--; + } else { + cacheSelectedSubInputNumber--; + cacheNoSelectedSubInputNumber++; + } } - }; - } + var allSelected = cacheNoSelectedSubInputNumber === 0; // if doesn't has any no selected input + var anySeleted = cacheSelectedSubInputNumber > 0; + setIndeterminateState(allSelected !== anySeleted); // if at least one is selected, but not all then set input property indeterminate to true + setModelValueWithSideEffect(allSelected); // change binding model value and trigger onchange event + }; + // is not leaf input, Only receive child change and parent change event + ngModelCtrl.$viewChangeListeners.push( + passIfIsLeafChild( + passIfIsIndeterminate(function() { + // emit when input property indeterminate is false, prevent recursively emitting event from parent to children, children to parent + scope.$broadcast("ParentSelectedChange", get()); + }) + ) + ); + // reset input state base on children inputs + scope.$on( + "childSelectedChange", + passThroughThisScope(passIfIsLeafChild(updateBaseOnChildrenState)) + ); + } + } + }; + } ]); diff --git a/js/directives/fselect.js b/js/directives/fselect.js index 4ede3319..a557ca5e 100644 --- a/js/directives/fselect.js +++ b/js/directives/fselect.js @@ -1,15 +1,18 @@ // watches changes in the file upload control (input[file]) and // puts the files selected in an attribute -angular -.module('webui.directives.fselect', ['webui.services.deps']) -.directive('fselect', ['$parse', function(parse) { - return function(scope, elem, attrs) { - var setfiles = parse(attrs.fselect || attrs.files).assign; - elem.bind('change', function() { - setfiles(scope, elem[0].files); - }).filestyle({ - placeholder : 'No file selected', - iconName : 'fa fa-folder-open', - }); - }; -}]); +angular.module("webui.directives.fselect", ["webui.services.deps"]).directive("fselect", [ + "$parse", + function(parse) { + return function(scope, elem, attrs) { + var setfiles = parse(attrs.fselect || attrs.files).assign; + elem + .bind("change", function() { + setfiles(scope, elem[0].files); + }) + .filestyle({ + placeholder: "No file selected", + iconName: "fa fa-folder-open" + }); + }; + } +]); diff --git a/js/directives/textarea.js b/js/directives/textarea.js index 3688a63a..f57d8407 100644 --- a/js/directives/textarea.js +++ b/js/directives/textarea.js @@ -2,21 +2,20 @@ webui.directive("textarea", function() { return { restrict: "E", link: function(scope, element) { - element.attr( - "placeholder", - function(index, placeholder) { + element + .attr("placeholder", function(index, placeholder) { if (placeholder !== undefined) { return placeholder.replace(/\\n/g, "\n"); } else { return placeholder; } - } - ).bind("keydown keypress", function(event) { - if (event.ctrlKey && event.which === 13) { - event.preventDefault(); - scope.$close(); - } - }); + }) + .bind("keydown keypress", function(event) { + if (event.ctrlKey && event.which === 13) { + event.preventDefault(); + scope.$close(); + } + }); } }; }); diff --git a/js/filters/bytes.js b/js/filters/bytes.js index 7c33501b..aeb2f93d 100644 --- a/js/filters/bytes.js +++ b/js/filters/bytes.js @@ -1,25 +1,34 @@ -angular.module('webui.filters.bytes', ["webui.services.utils"]) -.filter('blength', ['$filter', "$utils", function(filter, utils) { - return utils.fmtsize; -}]) -.filter('bspeed', ['$filter', "$utils", function(filter, utils) { - return utils.fmtspeed; -}]) -.filter('time', function() { - function pad(f) { - return ("0" + f).substr(-2); - } +angular + .module("webui.filters.bytes", ["webui.services.utils"]) + .filter("blength", [ + "$filter", + "$utils", + function(filter, utils) { + return utils.fmtsize; + } + ]) + .filter("bspeed", [ + "$filter", + "$utils", + function(filter, utils) { + return utils.fmtspeed; + } + ]) + .filter("time", function() { + function pad(f) { + return ("0" + f).substr(-2); + } - return function(time) { - time = parseInt(time, 10); - if (!time || !isFinite(time)) return "∞"; - var secs = time % 60; - if (time < 60) return secs + "s"; - var mins = Math.floor((time % 3600) / 60) - if (time < 3600) return pad(mins) + ":" + pad(secs); - var hrs = Math.floor((time % 86400) / 3600); - if (time < 86400) return pad(hrs) + ":" + pad(mins) + ":" + pad(secs); - var days = Math.floor(time / 86400); - return days + "::" + pad(hrs) + ":" + pad(mins) + ":" + pad(secs); - }; -}); + return function(time) { + time = parseInt(time, 10); + if (!time || !isFinite(time)) return "∞"; + var secs = time % 60; + if (time < 60) return secs + "s"; + var mins = Math.floor((time % 3600) / 60); + if (time < 3600) return pad(mins) + ":" + pad(secs); + var hrs = Math.floor((time % 86400) / 3600); + if (time < 86400) return pad(hrs) + ":" + pad(mins) + ":" + pad(secs); + var days = Math.floor(time / 86400); + return days + "::" + pad(hrs) + ":" + pad(mins) + ":" + pad(secs); + }; + }); diff --git a/js/filters/url.js b/js/filters/url.js index 3f6e5ab3..1d52f0ca 100644 --- a/js/filters/url.js +++ b/js/filters/url.js @@ -1,4 +1,3 @@ -angular.module('webui.filters.url', ["webui.services.utils"]) -.filter('encodeURI', function() { +angular.module("webui.filters.url", ["webui.services.utils"]).filter("encodeURI", function() { return window.encodeURI; }); diff --git a/js/init.js b/js/init.js index 8bee3179..67642a62 100644 --- a/js/init.js +++ b/js/init.js @@ -1,68 +1,82 @@ -var webui = angular.module('webui', [ - 'webui.services.utils', 'webui.services.deps', 'webui.services.base64', - 'webui.services.configuration', 'webui.services.rpc', - 'webui.services.modals', 'webui.services.alerts', - 'webui.services.settings', 'webui.services.settings.filters', - 'webui.filters.bytes','webui.filters.url', - 'webui.directives.chunkbar', 'webui.directives.dgraph', 'webui.directives.fselect', "webui.directives.fileselect", - 'webui.ctrls.download', 'webui.ctrls.nav', 'webui.ctrls.modal', 'webui.ctrls.alert', - 'webui.ctrls.props', +var webui = angular.module("webui", [ + "webui.services.utils", + "webui.services.deps", + "webui.services.base64", + "webui.services.configuration", + "webui.services.rpc", + "webui.services.modals", + "webui.services.alerts", + "webui.services.settings", + "webui.services.settings.filters", + "webui.filters.bytes", + "webui.filters.url", + "webui.directives.chunkbar", + "webui.directives.dgraph", + "webui.directives.fselect", + "webui.directives.fileselect", + "webui.ctrls.download", + "webui.ctrls.nav", + "webui.ctrls.modal", + "webui.ctrls.alert", + "webui.ctrls.props", // external deps - 'ui.bootstrap', + "ui.bootstrap", // translate - 'pascalprecht.translate' + "pascalprecht.translate" ]); function mergeTranslation(translation, base) { - for (var i in base) { - if (!base.hasOwnProperty(i)) { - continue; - } + for (var i in base) { + if (!base.hasOwnProperty(i)) { + continue; + } - if (!translation[i] || !translation[i].length) { - translation[i] = base[i]; - } - } + if (!translation[i] || !translation[i].length) { + translation[i] = base[i]; + } + } - return translation; + return translation; } -webui.config(function ($translateProvider, $locationProvider) { +webui.config(function($translateProvider, $locationProvider) { $translateProvider - .translations('en_US', translations.en_US) - .translations('nl_NL', mergeTranslation(translations.nl_NL, translations.en_US)) - .translations('th_TH', mergeTranslation(translations.th_TH, translations.en_US)) - .translations('zh_CN', mergeTranslation(translations.zh_CN, translations.en_US)) - .translations('zh_TW', mergeTranslation(translations.zh_TW, translations.en_US)) - .translations('pl_PL', mergeTranslation(translations.pl_PL, translations.en_US)) - .translations('fr_FR', mergeTranslation(translations.fr_FR, translations.en_US)) - .translations('de_DE', mergeTranslation(translations.de_DE, translations.en_US)) - .translations('es_ES', mergeTranslation(translations.es_ES, translations.en_US)) - .translations('ru_RU', mergeTranslation(translations.ru_RU, translations.en_US)) - .translations('it_IT', mergeTranslation(translations.it_IT, translations.en_US)) - .translations('tr_TR', mergeTranslation(translations.tr_TR, translations.en_US)) - .translations('cs_CZ', mergeTranslation(translations.cs_CZ, translations.en_US)) - .translations('fa_IR', mergeTranslation(translations.fa_IR, translations.en_US)) - .translations('id_ID', mergeTranslation(translations.id_ID, translations.en_US)) - .translations('pt_BR', mergeTranslation(translations.pt_BR, translations.en_US)) - .useSanitizeValueStrategy('escapeParameters') - .determinePreferredLanguage(); + .translations("en_US", translations.en_US) + .translations("nl_NL", mergeTranslation(translations.nl_NL, translations.en_US)) + .translations("th_TH", mergeTranslation(translations.th_TH, translations.en_US)) + .translations("zh_CN", mergeTranslation(translations.zh_CN, translations.en_US)) + .translations("zh_TW", mergeTranslation(translations.zh_TW, translations.en_US)) + .translations("pl_PL", mergeTranslation(translations.pl_PL, translations.en_US)) + .translations("fr_FR", mergeTranslation(translations.fr_FR, translations.en_US)) + .translations("de_DE", mergeTranslation(translations.de_DE, translations.en_US)) + .translations("es_ES", mergeTranslation(translations.es_ES, translations.en_US)) + .translations("ru_RU", mergeTranslation(translations.ru_RU, translations.en_US)) + .translations("it_IT", mergeTranslation(translations.it_IT, translations.en_US)) + .translations("tr_TR", mergeTranslation(translations.tr_TR, translations.en_US)) + .translations("cs_CZ", mergeTranslation(translations.cs_CZ, translations.en_US)) + .translations("fa_IR", mergeTranslation(translations.fa_IR, translations.en_US)) + .translations("id_ID", mergeTranslation(translations.id_ID, translations.en_US)) + .translations("pt_BR", mergeTranslation(translations.pt_BR, translations.en_US)) + .useSanitizeValueStrategy("escapeParameters") + .determinePreferredLanguage(); - $locationProvider.html5Mode({ - enabled: true, - requireBase: false - }); + $locationProvider.html5Mode({ + enabled: true, + requireBase: false + }); }); $(function() { if (!String.prototype.startsWith) { - Object.defineProperty(String.prototype, 'startsWith', { - enumerable: false, configurable: false, writable: false, - value: function (searchString, position) { - position = position || 0; - return this.indexOf(searchString, position) === position; - } + Object.defineProperty(String.prototype, "startsWith", { + enumerable: false, + configurable: false, + writable: false, + value: function(searchString, position) { + position = position || 0; + return this.indexOf(searchString, position) === position; + } }); } - angular.bootstrap(document, ['webui']) + angular.bootstrap(document, ["webui"]); }); diff --git a/js/libs/bootstrap-filestyle.js b/js/libs/bootstrap-filestyle.js index 4a6c1df1..e09b3172 100644 --- a/js/libs/bootstrap-filestyle.js +++ b/js/libs/bootstrap-filestyle.js @@ -7,351 +7,397 @@ * Version 1.2.1 * Licensed under the MIT license. */ -(function($) {"use strict"; - - var nextId = 0; - - var Filestyle = function(element, options) { - this.options = options; - this.$elementFilestyle = []; - this.$element = $(element); - }; - - Filestyle.prototype = { - clear : function() { - this.$element.val(''); - this.$elementFilestyle.find(':text').val(''); - this.$elementFilestyle.find('.badge').remove(); - }, - - destroy : function() { - this.$element.removeAttr('style').removeData('filestyle'); - this.$elementFilestyle.remove(); - }, - - disabled : function(value) { - if (value === true) { - if (!this.options.disabled) { - this.$element.attr('disabled', 'true'); - this.$elementFilestyle.find('label').attr('disabled', 'true'); - this.options.disabled = true; - } - } else if (value === false) { - if (this.options.disabled) { - this.$element.removeAttr('disabled'); - this.$elementFilestyle.find('label').removeAttr('disabled'); - this.options.disabled = false; - } - } else { - return this.options.disabled; - } - }, - - buttonBefore : function(value) { - if (value === true) { - if (!this.options.buttonBefore) { - this.options.buttonBefore = true; - if (this.options.input) { - this.$elementFilestyle.remove(); - this.constructor(); - this.pushNameFiles(); - } - } - } else if (value === false) { - if (this.options.buttonBefore) { - this.options.buttonBefore = false; - if (this.options.input) { - this.$elementFilestyle.remove(); - this.constructor(); - this.pushNameFiles(); - } - } - } else { - return this.options.buttonBefore; - } - }, - - icon : function(value) { - if (value === true) { - if (!this.options.icon) { - this.options.icon = true; - this.$elementFilestyle.find('label').prepend(this.htmlIcon()); - } - } else if (value === false) { - if (this.options.icon) { - this.options.icon = false; - this.$elementFilestyle.find('.icon-span-filestyle').remove(); - } - } else { - return this.options.icon; - } - }, - - input : function(value) { - if (value === true) { - if (!this.options.input) { - this.options.input = true; - - if (this.options.buttonBefore) { - this.$elementFilestyle.append(this.htmlInput()); - } else { - this.$elementFilestyle.prepend(this.htmlInput()); - } - - this.$elementFilestyle.find('.badge').remove(); - - this.pushNameFiles(); - - this.$elementFilestyle.find('.group-span-filestyle').addClass('input-group-btn'); - } - } else if (value === false) { - if (this.options.input) { - this.options.input = false; - this.$elementFilestyle.find(':text').remove(); - var files = this.pushNameFiles(); - if (files.length > 0 && this.options.badge) { - this.$elementFilestyle.find('label').append(' ' + files.length + ''); - } - this.$elementFilestyle.find('.group-span-filestyle').removeClass('input-group-btn'); - } - } else { - return this.options.input; - } - }, - - size : function(value) { - if (value !== undefined) { - var btn = this.$elementFilestyle.find('label'), input = this.$elementFilestyle.find('input'); - - btn.removeClass('btn-lg btn-sm'); - input.removeClass('input-lg input-sm'); - if (value != 'nr') { - btn.addClass('btn-' + value); - input.addClass('input-' + value); - } - } else { - return this.options.size; - } - }, - - placeholder : function(value) { - if (value !== undefined) { - this.options.placeholder = value; - this.$elementFilestyle.find('input').attr('placeholder', value); - } else { - return this.options.placeholder; - } - }, - - buttonText : function(value) { - if (value !== undefined) { - this.options.buttonText = value; - this.$elementFilestyle.find('label .buttonText').html(this.options.buttonText); - } else { - return this.options.buttonText; - } - }, - - buttonName : function(value) { - if (value !== undefined) { - this.options.buttonName = value; - this.$elementFilestyle.find('label').attr({ - 'class' : 'btn ' + this.options.buttonName - }); - } else { - return this.options.buttonName; - } - }, - - iconName : function(value) { - if (value !== undefined) { - this.$elementFilestyle.find('.icon-span-filestyle').attr({ - 'class' : 'icon-span-filestyle ' + this.options.iconName - }); - } else { - return this.options.iconName; - } - }, - - htmlIcon : function() { - if (this.options.icon) { - return ' '; - } else { - return ''; - } - }, - - htmlInput : function() { - if (this.options.input) { - return ' '; - } else { - return ''; - } - }, - - // puts the name of the input files - // return files - pushNameFiles : function() { - var content = '', files = []; - if (this.$element[0].files === undefined) { - files[0] = { - 'name' : this.$element[0] && this.$element[0].value - }; - } else { - files = this.$element[0].files; - } - - for (var i = 0; i < files.length; i++) { - content += files[i].name.split("\\").pop() + ', '; - } - - if (content !== '') { - this.$elementFilestyle.find(':text').val(content.replace(/\, $/g, '')); - } else { - this.$elementFilestyle.find(':text').val(''); - } - - return files; - }, - - constructor : function() { - var _self = this, - html = '', - id = _self.$element.attr('id'), - files = [], - btn = '', - clear = '', - $label; - - if (id === '' || !id) { - id = 'filestyle-' + nextId; - _self.$element.attr({ - 'id' : id - }); - nextId++; - } - - html = '
'; - btn = '' - clear = '' - - html = _self.options.buttonBefore ? html + btn + clear + '
' + _self.htmlInput() : _self.htmlInput() + html + clear + btn + ''; - - _self.$elementFilestyle = $('
' + html + '
'); - _self.$elementFilestyle.find('.group-span-filestyle').attr('tabindex', "0").keypress(function(e) { - if (e.keyCode === 13 || e.charCode === 32) { - _self.$elementFilestyle.find('label').click(); - return false; - } - }); - _self.$elementFilestyle.find('#' + id + '-clear').click(function(e) { - _self.clear(); - }); - - // hidding input file and add filestyle - _self.$element.css({ - 'position' : 'absolute', - 'clip' : 'rect(0px 0px 0px 0px)' // using 0px for work in IE8 - }).attr('tabindex', "-1").after(_self.$elementFilestyle); - - if (_self.options.disabled || _self.$element.attr('disabled')) { - _self.$element.attr('disabled', 'true'); - } - - // Getting input file value - _self.$element.change(function() { - var files = _self.pushNameFiles(); - - if (_self.options.input == false && _self.options.badge) { - if (_self.$elementFilestyle.find('.badge').length == 0) { - _self.$elementFilestyle.find('label').append(' ' + files.length + ''); - } else if (files.length == 0) { - _self.$elementFilestyle.find('.badge').remove(); - } else { - _self.$elementFilestyle.find('.badge').html(files.length); - } - } else { - _self.$elementFilestyle.find('.badge').remove(); - } - }); - - // Check if browser is Firefox - if (window.navigator.userAgent.search(/firefox/i) > -1) { - // Simulating choose file for firefox - _self.$elementFilestyle.find('label').click(function() { - _self.$element.click(); - return false; - }); - } - } - }; - - var old = $.fn.filestyle; - - $.fn.filestyle = function(option, value) { - var get = '', element = this.each(function() { - if ($(this).attr('type') === 'file') { - var $this = $(this), data = $this.data('filestyle'), options = $.extend({}, $.fn.filestyle.defaults, option, typeof option === 'object' && option); - - if (!data) { - $this.data('filestyle', ( data = new Filestyle(this, options))); - data.constructor(); - } - - if ( typeof option === 'string') { - get = data[option](value); - } - } - }); - - if ( typeof get !== undefined) { - return get; - } else { - return element; - } - }; - - $.fn.filestyle.defaults = { - 'buttonText' : 'Choose file', - 'iconName' : 'glyphicon glyphicon-folder-open', - 'buttonName' : 'btn-default', - 'size' : 'nr', - 'input' : true, - 'badge' : true, - 'icon' : true, - 'buttonBefore' : false, - 'disabled' : false, - 'placeholder': '' - }; - - $.fn.filestyle.noConflict = function() { - $.fn.filestyle = old; - return this; - }; - - $(function() { - $('.filestyle').each(function() { - var $this = $(this), options = { - - 'input' : $this.attr('data-input') !== 'false', - 'icon' : $this.attr('data-icon') !== 'false', - 'buttonBefore' : $this.attr('data-buttonBefore') === 'true', - 'disabled' : $this.attr('data-disabled') === 'true', - 'size' : $this.attr('data-size'), - 'buttonText' : $this.attr('data-buttonText'), - 'buttonName' : $this.attr('data-buttonName'), - 'iconName' : $this.attr('data-iconName'), - 'badge' : $this.attr('data-badge') !== 'false', - 'placeholder': $this.attr('data-placeholder') - }; - - $this.filestyle(options); - }); - }); +(function($) { + "use strict"; + + var nextId = 0; + + var Filestyle = function(element, options) { + this.options = options; + this.$elementFilestyle = []; + this.$element = $(element); + }; + + Filestyle.prototype = { + clear: function() { + this.$element.val(""); + this.$elementFilestyle.find(":text").val(""); + this.$elementFilestyle.find(".badge").remove(); + }, + + destroy: function() { + this.$element.removeAttr("style").removeData("filestyle"); + this.$elementFilestyle.remove(); + }, + + disabled: function(value) { + if (value === true) { + if (!this.options.disabled) { + this.$element.attr("disabled", "true"); + this.$elementFilestyle.find("label").attr("disabled", "true"); + this.options.disabled = true; + } + } else if (value === false) { + if (this.options.disabled) { + this.$element.removeAttr("disabled"); + this.$elementFilestyle.find("label").removeAttr("disabled"); + this.options.disabled = false; + } + } else { + return this.options.disabled; + } + }, + + buttonBefore: function(value) { + if (value === true) { + if (!this.options.buttonBefore) { + this.options.buttonBefore = true; + if (this.options.input) { + this.$elementFilestyle.remove(); + this.constructor(); + this.pushNameFiles(); + } + } + } else if (value === false) { + if (this.options.buttonBefore) { + this.options.buttonBefore = false; + if (this.options.input) { + this.$elementFilestyle.remove(); + this.constructor(); + this.pushNameFiles(); + } + } + } else { + return this.options.buttonBefore; + } + }, + + icon: function(value) { + if (value === true) { + if (!this.options.icon) { + this.options.icon = true; + this.$elementFilestyle.find("label").prepend(this.htmlIcon()); + } + } else if (value === false) { + if (this.options.icon) { + this.options.icon = false; + this.$elementFilestyle.find(".icon-span-filestyle").remove(); + } + } else { + return this.options.icon; + } + }, + + input: function(value) { + if (value === true) { + if (!this.options.input) { + this.options.input = true; + + if (this.options.buttonBefore) { + this.$elementFilestyle.append(this.htmlInput()); + } else { + this.$elementFilestyle.prepend(this.htmlInput()); + } + + this.$elementFilestyle.find(".badge").remove(); + + this.pushNameFiles(); + + this.$elementFilestyle.find(".group-span-filestyle").addClass("input-group-btn"); + } + } else if (value === false) { + if (this.options.input) { + this.options.input = false; + this.$elementFilestyle.find(":text").remove(); + var files = this.pushNameFiles(); + if (files.length > 0 && this.options.badge) { + this.$elementFilestyle + .find("label") + .append(' ' + files.length + ""); + } + this.$elementFilestyle.find(".group-span-filestyle").removeClass("input-group-btn"); + } + } else { + return this.options.input; + } + }, + + size: function(value) { + if (value !== undefined) { + var btn = this.$elementFilestyle.find("label"), + input = this.$elementFilestyle.find("input"); + + btn.removeClass("btn-lg btn-sm"); + input.removeClass("input-lg input-sm"); + if (value != "nr") { + btn.addClass("btn-" + value); + input.addClass("input-" + value); + } + } else { + return this.options.size; + } + }, + + placeholder: function(value) { + if (value !== undefined) { + this.options.placeholder = value; + this.$elementFilestyle.find("input").attr("placeholder", value); + } else { + return this.options.placeholder; + } + }, + + buttonText: function(value) { + if (value !== undefined) { + this.options.buttonText = value; + this.$elementFilestyle.find("label .buttonText").html(this.options.buttonText); + } else { + return this.options.buttonText; + } + }, + + buttonName: function(value) { + if (value !== undefined) { + this.options.buttonName = value; + this.$elementFilestyle.find("label").attr({ + class: "btn " + this.options.buttonName + }); + } else { + return this.options.buttonName; + } + }, + + iconName: function(value) { + if (value !== undefined) { + this.$elementFilestyle.find(".icon-span-filestyle").attr({ + class: "icon-span-filestyle " + this.options.iconName + }); + } else { + return this.options.iconName; + } + }, + + htmlIcon: function() { + if (this.options.icon) { + return ' '; + } else { + return ""; + } + }, + + htmlInput: function() { + if (this.options.input) { + return ( + ' ' + ); + } else { + return ""; + } + }, + + // puts the name of the input files + // return files + pushNameFiles: function() { + var content = "", + files = []; + if (this.$element[0].files === undefined) { + files[0] = { + name: this.$element[0] && this.$element[0].value + }; + } else { + files = this.$element[0].files; + } + + for (var i = 0; i < files.length; i++) { + content += files[i].name.split("\\").pop() + ", "; + } + + if (content !== "") { + this.$elementFilestyle.find(":text").val(content.replace(/\, $/g, "")); + } else { + this.$elementFilestyle.find(":text").val(""); + } + + return files; + }, + + constructor: function() { + var _self = this, + html = "", + id = _self.$element.attr("id"), + files = [], + btn = "", + clear = "", + $label; + + if (id === "" || !id) { + id = "filestyle-" + nextId; + _self.$element.attr({ + id: id + }); + nextId++; + } + + html = + '
'; + btn = + '"; + clear = + ''; + + html = _self.options.buttonBefore + ? html + btn + clear + "
" + _self.htmlInput() + : _self.htmlInput() + html + clear + btn + ""; + + _self.$elementFilestyle = $( + '
' + html + "
" + ); + _self.$elementFilestyle + .find(".group-span-filestyle") + .attr("tabindex", "0") + .keypress(function(e) { + if (e.keyCode === 13 || e.charCode === 32) { + _self.$elementFilestyle.find("label").click(); + return false; + } + }); + _self.$elementFilestyle.find("#" + id + "-clear").click(function(e) { + _self.clear(); + }); + + // hidding input file and add filestyle + _self.$element + .css({ + position: "absolute", + clip: "rect(0px 0px 0px 0px)" // using 0px for work in IE8 + }) + .attr("tabindex", "-1") + .after(_self.$elementFilestyle); + + if (_self.options.disabled || _self.$element.attr("disabled")) { + _self.$element.attr("disabled", "true"); + } + + // Getting input file value + _self.$element.change(function() { + var files = _self.pushNameFiles(); + + if (_self.options.input == false && _self.options.badge) { + if (_self.$elementFilestyle.find(".badge").length == 0) { + _self.$elementFilestyle + .find("label") + .append(' ' + files.length + ""); + } else if (files.length == 0) { + _self.$elementFilestyle.find(".badge").remove(); + } else { + _self.$elementFilestyle.find(".badge").html(files.length); + } + } else { + _self.$elementFilestyle.find(".badge").remove(); + } + }); + + // Check if browser is Firefox + if (window.navigator.userAgent.search(/firefox/i) > -1) { + // Simulating choose file for firefox + _self.$elementFilestyle.find("label").click(function() { + _self.$element.click(); + return false; + }); + } + } + }; + + var old = $.fn.filestyle; + + $.fn.filestyle = function(option, value) { + var get = "", + element = this.each(function() { + if ($(this).attr("type") === "file") { + var $this = $(this), + data = $this.data("filestyle"), + options = $.extend( + {}, + $.fn.filestyle.defaults, + option, + typeof option === "object" && option + ); + + if (!data) { + $this.data("filestyle", (data = new Filestyle(this, options))); + data.constructor(); + } + + if (typeof option === "string") { + get = data[option](value); + } + } + }); + + if (typeof get !== undefined) { + return get; + } else { + return element; + } + }; + + $.fn.filestyle.defaults = { + buttonText: "Choose file", + iconName: "glyphicon glyphicon-folder-open", + buttonName: "btn-default", + size: "nr", + input: true, + badge: true, + icon: true, + buttonBefore: false, + disabled: false, + placeholder: "" + }; + + $.fn.filestyle.noConflict = function() { + $.fn.filestyle = old; + return this; + }; + + $(function() { + $(".filestyle").each(function() { + var $this = $(this), + options = { + input: $this.attr("data-input") !== "false", + icon: $this.attr("data-icon") !== "false", + buttonBefore: $this.attr("data-buttonBefore") === "true", + disabled: $this.attr("data-disabled") === "true", + size: $this.attr("data-size"), + buttonText: $this.attr("data-buttonText"), + buttonName: $this.attr("data-buttonName"), + iconName: $this.attr("data-iconName"), + badge: $this.attr("data-badge") !== "false", + placeholder: $this.attr("data-placeholder") + }; + + $this.filestyle(options); + }); + }); })(window.jQuery); diff --git a/js/services/alerts.js b/js/services/alerts.js index ec3ec161..ed12ea5d 100644 --- a/js/services/alerts.js +++ b/js/services/alerts.js @@ -1,21 +1,23 @@ -angular.module('webui.services.alerts', ['webui.services.deps']) -.factory('$alerts', ['$_', function(_) { - var alerters = []; - return { - addAlert: function() { - var args = Array.prototype.slice.call(arguments, 0); - setTimeout(function() { - _.each(alerters, function(alt) { - alt.apply({}, args); - }); - }, 0); - }, - addAlerter: function(cb) { - alerters.push(cb); - }, - // a simple function for debugging - log: function(msg) { - this.addAlert(msg, 'info'); - } - }; -}]); +angular.module("webui.services.alerts", ["webui.services.deps"]).factory("$alerts", [ + "$_", + function(_) { + var alerters = []; + return { + addAlert: function() { + var args = Array.prototype.slice.call(arguments, 0); + setTimeout(function() { + _.each(alerters, function(alt) { + alt.apply({}, args); + }); + }, 0); + }, + addAlerter: function(cb) { + alerters.push(cb); + }, + // a simple function for debugging + log: function(msg) { + this.addAlert(msg, "info"); + } + }; + } +]); diff --git a/js/services/base64.js b/js/services/base64.js index 95e23695..fff502fd 100644 --- a/js/services/base64.js +++ b/js/services/base64.js @@ -1,58 +1,65 @@ -angular - .module('webui.services.base64', []) - .factory('$base64', [function() { - var obj = {}; - var a64 = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/', - a256 = { - indexOf: function (c) { - return c.charCodeAt(0); - }, - charAt: String.fromCharCode - }; +angular.module("webui.services.base64", []).factory("$base64", [ + function() { + var obj = {}; + var a64 = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/", + a256 = { + indexOf: function(c) { + return c.charCodeAt(0); + }, + charAt: String.fromCharCode + }; - function code(s, discard, alpha, beta, w1, w2) { - s = String(s); - var b = 0, x = '', i, c, bs = 1, sb = 1, length = s.length, tmp; - for (i = 0; i < length || (!discard && sb > 1); i += 1) { - b *= w1; - bs *= w1; - if (i < length) { - c = alpha.indexOf(s.charAt(i)); - if (c <= -1 || c >= w1) { - throw new RangeError(); + function code(s, discard, alpha, beta, w1, w2) { + s = String(s); + var b = 0, + x = "", + i, + c, + bs = 1, + sb = 1, + length = s.length, + tmp; + for (i = 0; i < length || (!discard && sb > 1); i += 1) { + b *= w1; + bs *= w1; + if (i < length) { + c = alpha.indexOf(s.charAt(i)); + if (c <= -1 || c >= w1) { + throw new RangeError(); + } + sb *= w1; + b += c; } - sb *= w1; - b += c; - } - while (bs >= w2) { - bs /= w2; - if (sb > 1) { - tmp = b; - b %= bs; - x += beta.charAt((tmp - b) / bs); - sb /= w2; + while (bs >= w2) { + bs /= w2; + if (sb > 1) { + tmp = b; + b %= bs; + x += beta.charAt((tmp - b) / bs); + sb /= w2; + } } } + return x; } - return x; - } - obj.btoa = function (s) { - s = code(s, false, a256, a64, 256, 64); - return s + '===='.slice((s.length % 4) || 4); - }; + obj.btoa = function(s) { + s = code(s, false, a256, a64, 256, 64); + return s + "====".slice(s.length % 4 || 4); + }; - obj.atob = function (s) { - var i; - s = String(s).split('='); - for (i = s.length - 1; i >= 0; i -= 1) { - if (s[i].length % 4 === 1) { - throw new RangeError(); + obj.atob = function(s) { + var i; + s = String(s).split("="); + for (i = s.length - 1; i >= 0; i -= 1) { + if (s[i].length % 4 === 1) { + throw new RangeError(); + } + s[i] = code(s[i], true, a64, a256, 64, 256); } - s[i] = code(s[i], true, a64, a256, 64, 256); - } - return s.join(''); - }; + return s.join(""); + }; - return obj; -}]); + return obj; + } +]); diff --git a/js/services/deps.js b/js/services/deps.js index 804cdbe5..8476b29e 100644 --- a/js/services/deps.js +++ b/js/services/deps.js @@ -1,5 +1,5 @@ angular - .module('webui.services.deps', []) - .value('$', $) - .value('$_', _) - .value('$json', JSON); + .module("webui.services.deps", []) + .value("$", $) + .value("$_", _) + .value("$json", JSON); diff --git a/js/services/errors.js b/js/services/errors.js index 1c29dd02..c82431de 100644 --- a/js/services/errors.js +++ b/js/services/errors.js @@ -1,68 +1,66 @@ -angular - .module('webui.services.errors', []) - .value('$getErrorStatus', function(errorCode) { - // normalize it to 0 - errorCode = errorCode - 1; - switch(errorCode) { - case 0: - return "download was unsuccessful"; - case 1: - return "unknown error occurred"; - case 2: - return "time out occurred"; - case 3: - return "resource was not found"; - case 4: - return 'aria2 saw the specified number of "resource not found" error. See --max-file-not-found option'; - case 5: - return "download aborted because download speed was too slow. See --lowest-speed-limit option"; - case 6: - return "there were unfinished downloads"; - case 7: - return "remote server did not support resume when resume was required to complete download"; - case 8: - return "not enough disk space available"; - case 9: - return "piece length was different from one in .aria2 control"; - case 10: - return "downloading same file at that moment"; - case 11: - return "downloading same info hash torrent at that moment"; - case 12: - return "file already existed"; - case 13: - return "renaming file failed"; - case 14: - return "could not open existing file"; - case 15: - return "could not create new file or truncate existing file"; - case 16: - return "file I/O error occurred"; - case 17: - return "could not create directory"; - case 18: - return "name resolution failed"; - case 19: - return "could not parse Metalink document"; - case 20: - return "FTP command failed"; - case 21: - return "HTTP response header was bad or unexpected"; - case 22: - return "too many redirects occurred"; - case 23: - return "HTTP authorization failed"; - case 24: - return "could not parse bencoded file"; - case 25: - return ' ".torrent" file was corrupted or missing information '; - case 26: - return "Magnet URI was bad"; - case 27: - return "bad/unrecognized option was given or unexpected option argument was given"; - case 28: - return "remote server was unable to handle the request due to a temporary overloading or maintenance"; - case 29: - return "could not parse JSON-RPC request"; - } +angular.module("webui.services.errors", []).value("$getErrorStatus", function(errorCode) { + // normalize it to 0 + errorCode = errorCode - 1; + switch (errorCode) { + case 0: + return "download was unsuccessful"; + case 1: + return "unknown error occurred"; + case 2: + return "time out occurred"; + case 3: + return "resource was not found"; + case 4: + return 'aria2 saw the specified number of "resource not found" error. See --max-file-not-found option'; + case 5: + return "download aborted because download speed was too slow. See --lowest-speed-limit option"; + case 6: + return "there were unfinished downloads"; + case 7: + return "remote server did not support resume when resume was required to complete download"; + case 8: + return "not enough disk space available"; + case 9: + return "piece length was different from one in .aria2 control"; + case 10: + return "downloading same file at that moment"; + case 11: + return "downloading same info hash torrent at that moment"; + case 12: + return "file already existed"; + case 13: + return "renaming file failed"; + case 14: + return "could not open existing file"; + case 15: + return "could not create new file or truncate existing file"; + case 16: + return "file I/O error occurred"; + case 17: + return "could not create directory"; + case 18: + return "name resolution failed"; + case 19: + return "could not parse Metalink document"; + case 20: + return "FTP command failed"; + case 21: + return "HTTP response header was bad or unexpected"; + case 22: + return "too many redirects occurred"; + case 23: + return "HTTP authorization failed"; + case 24: + return "could not parse bencoded file"; + case 25: + return ' ".torrent" file was corrupted or missing information '; + case 26: + return "Magnet URI was bad"; + case 27: + return "bad/unrecognized option was given or unexpected option argument was given"; + case 28: + return "remote server was unable to handle the request due to a temporary overloading or maintenance"; + case 29: + return "could not parse JSON-RPC request"; + } }); diff --git a/js/services/modals.js b/js/services/modals.js index 82da9c88..8b6712fd 100644 --- a/js/services/modals.js +++ b/js/services/modals.js @@ -1,5 +1,4 @@ -angular.module('webui.services.modals', []) -.factory('$modals', function() { +angular.module("webui.services.modals", []).factory("$modals", function() { var modals = {}; return { // register a new modal, cb is the function which diff --git a/js/services/rpc/helpers.js b/js/services/rpc/helpers.js index 73e0663a..b09348c3 100644 --- a/js/services/rpc/helpers.js +++ b/js/services/rpc/helpers.js @@ -1,56 +1,65 @@ -angular.module('webui.services.rpc.helpers', [ - 'webui.services.deps', 'webui.services.rpc', 'webui.services.alerts' -]) -.factory('$rpchelpers', ['$_', '$rpc', '$alerts', function(_, rpc, alerts) { - var miscellaneous = {version: '', enabledFeatures: []}; - rpc.once('getVersion', [], function(data) { miscellaneous = data[0]}); - return { - isFeatureEnabled: function(feature) { - return miscellaneous.enabledFeatures.indexOf(feature) != -1; - }, - getAria2Version: function() { - return miscellaneous.version; - }, - addUris: function(uris, settings, cb) { - _.each(uris, function(uri) { - var uri_parsed = []; - // parse options passed in the URIs. E.g. http://ex1.com/f1.jpg --out=image.jpg --check-integrity - var uriSettings = _.cloneDeep(settings); - _.each(uri, function(uri_element) { - if (uri_element.startsWith('--')) { - uri_options = uri_element.split(/--|=(.*)/); - if (uri_options.length > 2) { - uriSettings[uri_options[2]] = uri_options[3] || 'true'; - } - } - else { - uri_parsed.push(uri_element); - } - }); - // passing true to batch all the addUri calls - rpc.once('addUri', [uri_parsed, uriSettings], cb, true); +angular + .module("webui.services.rpc.helpers", [ + "webui.services.deps", + "webui.services.rpc", + "webui.services.alerts" + ]) + .factory("$rpchelpers", [ + "$_", + "$rpc", + "$alerts", + function(_, rpc, alerts) { + var miscellaneous = { version: "", enabledFeatures: [] }; + rpc.once("getVersion", [], function(data) { + miscellaneous = data[0]; }); + return { + isFeatureEnabled: function(feature) { + return miscellaneous.enabledFeatures.indexOf(feature) != -1; + }, + getAria2Version: function() { + return miscellaneous.version; + }, + addUris: function(uris, settings, cb) { + _.each(uris, function(uri) { + var uri_parsed = []; + // parse options passed in the URIs. E.g. http://ex1.com/f1.jpg --out=image.jpg --check-integrity + var uriSettings = _.cloneDeep(settings); + _.each(uri, function(uri_element) { + if (uri_element.startsWith("--")) { + uri_options = uri_element.split(/--|=(.*)/); + if (uri_options.length > 2) { + uriSettings[uri_options[2]] = uri_options[3] || "true"; + } + } else { + uri_parsed.push(uri_element); + } + }); + // passing true to batch all the addUri calls + rpc.once("addUri", [uri_parsed, uriSettings], cb, true); + }); - // now dispatch all addUri syscalls - rpc.forceUpdate(); - }, - addTorrents: function(txts, settings, cb) { - _.each(txts, function(txt) { - // passing true to batch all the addUri calls - rpc.once('addTorrent', [txt, [], settings], cb, true); - }); + // now dispatch all addUri syscalls + rpc.forceUpdate(); + }, + addTorrents: function(txts, settings, cb) { + _.each(txts, function(txt) { + // passing true to batch all the addUri calls + rpc.once("addTorrent", [txt, [], settings], cb, true); + }); - // now dispatch all addUri syscalls - rpc.forceUpdate(); - }, - addMetalinks: function(txts, settings, cb) { - _.each(txts, function(txt) { - // passing true to batch all the addUri calls - rpc.once('addMetalink', [txt, settings], cb, true); - }); + // now dispatch all addUri syscalls + rpc.forceUpdate(); + }, + addMetalinks: function(txts, settings, cb) { + _.each(txts, function(txt) { + // passing true to batch all the addUri calls + rpc.once("addMetalink", [txt, settings], cb, true); + }); - // now dispatch all addUri syscalls - rpc.forceUpdate(); + // now dispatch all addUri syscalls + rpc.forceUpdate(); + } + }; } - }; -}]); + ]); diff --git a/js/services/rpc/jsoncall.js b/js/services/rpc/jsoncall.js index 4c15f992..cbd2879a 100644 --- a/js/services/rpc/jsoncall.js +++ b/js/services/rpc/jsoncall.js @@ -1,76 +1,85 @@ angular - .module('webui.services.rpc.jsoncall', [ - 'webui.services.deps', 'webui.services.base64']) - .factory('$jsoncall', ['$', '$json', '$base64', function($, JSON, base64) { - return { - init: function(conf) { - this.avgTimeout = 2000; - this.serverConf = conf; - }, - ariaRequest: function(url, funcName, params, success, error) { - var startTime = new Date(); - var conn = this; - $.post({ - url: url, - timeout: this.avgTimeout, - contentType: 'application/json', - data: JSON.stringify({ - jsonrpc: 2.0, - id: 'webui', - method: funcName, - params: params - }), - success: function(data) { - conn.avgTimeout = 2000 + 3 * (new Date() - startTime); - return success(data); + .module("webui.services.rpc.jsoncall", ["webui.services.deps", "webui.services.base64"]) + .factory("$jsoncall", [ + "$", + "$json", + "$base64", + function($, JSON, base64) { + return { + init: function(conf) { + this.avgTimeout = 2000; + this.serverConf = conf; }, - error: error - }); - }, - invoke: function(opts) { - var rpc = this; - var scheme = rpc.serverConf.encrypt ? 'https' : 'http'; - rpc.ariaRequest( - scheme + '://' + rpc.serverConf.host + ':' + rpc.serverConf.port + (rpc.serverConf.path || '/jsonrpc'), - opts.name, - opts.params, - opts.success, - function() { - // check if authentication details are given, if yes then use a hack to support - // http authentication otherwise emit error - if (!rpc.serverConf.auth || !rpc.serverConf.auth.user) { - console.log("jsonrpc disconnect!!!"); - return opts.error(); - } - - var authUrl = scheme + '://' + - rpc.serverConf.auth.user + ":" + - rpc.serverConf.auth.pass + "@" + - rpc.serverConf.host + ':' + - rpc.serverConf.port + (rpc.serverConf.path || '/jsonrpc'); - - // hack is to basically inject an image with same uri as the aria2 rpc url, - // most browsers will then cache the authentication details and we dont have - // to give them next time we make a request - var img = $('').attr("src", authUrl); - $('body').append(img); - img.remove(); - - // timeout to let the image load and then make a request, - setTimeout(function() { - rpc.ariaRequest( - authUrl, - opts.name, - opts.params, - opts.success, - function() { + ariaRequest: function(url, funcName, params, success, error) { + var startTime = new Date(); + var conn = this; + $.post({ + url: url, + timeout: this.avgTimeout, + contentType: "application/json", + data: JSON.stringify({ + jsonrpc: 2.0, + id: "webui", + method: funcName, + params: params + }), + success: function(data) { + conn.avgTimeout = 2000 + 3 * (new Date() - startTime); + return success(data); + }, + error: error + }); + }, + invoke: function(opts) { + var rpc = this; + var scheme = rpc.serverConf.encrypt ? "https" : "http"; + rpc.ariaRequest( + scheme + + "://" + + rpc.serverConf.host + + ":" + + rpc.serverConf.port + + (rpc.serverConf.path || "/jsonrpc"), + opts.name, + opts.params, + opts.success, + function() { + // check if authentication details are given, if yes then use a hack to support + // http authentication otherwise emit error + if (!rpc.serverConf.auth || !rpc.serverConf.auth.user) { console.log("jsonrpc disconnect!!!"); return opts.error(); } - ); - }, rpc.avgTimeout); + + var authUrl = + scheme + + "://" + + rpc.serverConf.auth.user + + ":" + + rpc.serverConf.auth.pass + + "@" + + rpc.serverConf.host + + ":" + + rpc.serverConf.port + + (rpc.serverConf.path || "/jsonrpc"); + + // hack is to basically inject an image with same uri as the aria2 rpc url, + // most browsers will then cache the authentication details and we dont have + // to give them next time we make a request + var img = $("").attr("src", authUrl); + $("body").append(img); + img.remove(); + + // timeout to let the image load and then make a request, + setTimeout(function() { + rpc.ariaRequest(authUrl, opts.name, opts.params, opts.success, function() { + console.log("jsonrpc disconnect!!!"); + return opts.error(); + }); + }, rpc.avgTimeout); + } + ); } - ); + }; } - }; -}]); + ]); diff --git a/js/services/rpc/rpc.js b/js/services/rpc/rpc.js index 3083b070..b477ce19 100644 --- a/js/services/rpc/rpc.js +++ b/js/services/rpc/rpc.js @@ -1,272 +1,306 @@ angular -.module('webui.services.rpc', [ - 'webui.services.rpc.syscall', 'webui.services.configuration', 'webui.services.alerts', - 'webui.services.utils' -]) -.factory('$rpc', [ - '$syscall', '$globalTimeout', '$alerts', '$utils', - '$rootScope', '$location', '$authconf', '$filter', -function(syscall, globalTimeout, alerts, utils, rootScope, uri, authconf, filter) { - - var subscriptions = [] - , configurations = [authconf] - , currentConf = {} - , currentToken - , timeout = null - , forceNextUpdate = false; - - var cookieConf = utils.getCookie('aria2conf'); - // try at the start, so that it is presistant even when default authconf works - if(cookieConf) configurations.unshift(cookieConf); - - if (uri.search().host) { - configurations.unshift(uri.search()); - configurations[0].auth = { - token: configurations[0].token, - user: configurations[0].username, - pass: configurations[0].password - }; - } - - if (['http', 'https'].indexOf(uri.protocol()) != -1 && uri.host() != 'localhost') { - configurations.push({ - host: uri.host(), - path: '/jsonrpc', - port: 6800, - encrypt: false - }, - { - host: uri.host(), - port: uri.port(), - path: '/jsonrpc', - encrypt: ( uri.protocol() == 'https' ) - }, - { - host: uri.host(), - port: uri.port(), - path: authconf.path, - encrypt: ( uri.protocol() == 'https' ) - }); - } - - - // set if we got error on connection. This will cause another connection attempt. - var needNewConnection = true; - - // update is implemented such that - // only one syscall at max is ongoing - // (i.e. serially) so should be private - // to maintain that invariant - var update = function() { - - clearTimeout(timeout); - timeout = null; - - subscriptions = _.filter(subscriptions, function(e) { - return !!e && e.once !== 2; - }); - var subs = subscriptions.slice(); - if (!subs.length) { - timeout = setTimeout(update, globalTimeout); - return; - } - - if (syscall.state == 'initializing') { - console.log("Syscall is initializing, waiting"); - timeout = setTimeout(update, globalTimeout); - return; - } - - if (needNewConnection && configurations.length) { - needNewConnection = false; - currentConf = configurations[0]; - if (currentConf && currentConf.auth && currentConf.auth.token) { - currentToken = currentConf.auth.token; + .module("webui.services.rpc", [ + "webui.services.rpc.syscall", + "webui.services.configuration", + "webui.services.alerts", + "webui.services.utils" + ]) + .factory("$rpc", [ + "$syscall", + "$globalTimeout", + "$alerts", + "$utils", + "$rootScope", + "$location", + "$authconf", + "$filter", + function(syscall, globalTimeout, alerts, utils, rootScope, uri, authconf, filter) { + var subscriptions = [], + configurations = [authconf], + currentConf = {}, + currentToken, + timeout = null, + forceNextUpdate = false; + + var cookieConf = utils.getCookie("aria2conf"); + // try at the start, so that it is presistant even when default authconf works + if (cookieConf) configurations.unshift(cookieConf); + + if (uri.search().host) { + configurations.unshift(uri.search()); + configurations[0].auth = { + token: configurations[0].token, + user: configurations[0].username, + pass: configurations[0].password + }; } - else { - currentToken = null; - } - syscall.init(currentConf); - timeout = setTimeout(update, globalTimeout); - return; - } - var params = _.map(subs, function(s) { - var p = s.params; - if (currentToken) { - p = ["token:" + currentToken].concat(p || []); + if (["http", "https"].indexOf(uri.protocol()) != -1 && uri.host() != "localhost") { + configurations.push( + { + host: uri.host(), + path: "/jsonrpc", + port: 6800, + encrypt: false + }, + { + host: uri.host(), + port: uri.port(), + path: "/jsonrpc", + encrypt: uri.protocol() == "https" + }, + { + host: uri.host(), + port: uri.port(), + path: authconf.path, + encrypt: uri.protocol() == "https" + } + ); } - return { - methodName: s.name, - params: p && p.length ? p : undefined - }; - }); - var error = function() { - needNewConnection = true; - var ind = configurations.indexOf(currentConf); - if (ind != -1) configurations.splice(ind, 1); + // set if we got error on connection. This will cause another connection attempt. + var needNewConnection = true; - // If some proposed configurations are still in the pipeline then retry - if (configurations.length) { - alerts.log(filter('translate')("The last connection attempt was unsuccessful. Trying another configuration")); - timeout = setTimeout(update, 0); - } - else { - alerts.addAlert('' + filter('translate')('Oh Snap!') + ' ' + - filter('translate')('Could not connect to the aria2 RPC server. Will retry in 10 secs. You might want to check the connection settings by going to Settings > Connection Settings') - , 'error'); - timeout = setTimeout(update, globalTimeout); - } - }; - - syscall.invoke({ - name: 'system.multicall', - params: [params], - success: function(data) { - var failed = _.some(data.result, function(d) { - return d.code && d.message === "Unauthorized"; - }); + // update is implemented such that + // only one syscall at max is ongoing + // (i.e. serially) so should be private + // to maintain that invariant + var update = function() { + clearTimeout(timeout); + timeout = null; - if (failed) { - needNewConnection = true; - alerts.addAlert('' + filter('translate')('Oh Snap!') + ' ' + - filter('translate')('Authentication failed while connecting to Aria2 RPC server. Will retry in 10 secs. You might want to confirm your authentication details by going to Settings > Connection Settings', 'error')); + subscriptions = _.filter(subscriptions, function(e) { + return !!e && e.once !== 2; + }); + var subs = subscriptions.slice(); + if (!subs.length) { timeout = setTimeout(update, globalTimeout); return; } - if (configurations.length) { - // configuration worked, save it in cookie for next time and - // delete the pipelined configurations!! - if (currentToken) - alerts.addAlert(filter('translate')('Successfully connected to Aria2 through its remote RPC …'), 'success'); - else - alerts.addAlert(filter('translate')('Successfully connected to Aria2 through remote RPC, however the connection is still insecure. For complete security try adding an authorization secret token while starting Aria2 (through the flag --rpc-secret)')); - configurations = []; + if (syscall.state == "initializing") { + console.log("Syscall is initializing, waiting"); + timeout = setTimeout(update, globalTimeout); + return; } - utils.setCookie('aria2conf', currentConf); + if (needNewConnection && configurations.length) { + needNewConnection = false; + currentConf = configurations[0]; + if (currentConf && currentConf.auth && currentConf.auth.token) { + currentToken = currentConf.auth.token; + } else { + currentToken = null; + } + syscall.init(currentConf); + timeout = setTimeout(update, globalTimeout); + return; + } - var cbs = []; - _.each(data.result, function(d, i) { - var handle = subs[i]; - if (handle) { - if (d.code) { - console.error(handle, d); - alerts.addAlert(d.message, 'error'); - } - // run them later as the cb itself can mutate the subscriptions - cbs.push({cb: handle.cb, data: d}); - if (handle.once) { - handle.once = 2; - } + var params = _.map(subs, function(s) { + var p = s.params; + if (currentToken) { + p = ["token:" + currentToken].concat(p || []); } + return { + methodName: s.name, + params: p && p.length ? p : undefined + }; }); + var error = function() { + needNewConnection = true; + var ind = configurations.indexOf(currentConf); + if (ind != -1) configurations.splice(ind, 1); + + // If some proposed configurations are still in the pipeline then retry + if (configurations.length) { + alerts.log( + filter("translate")( + "The last connection attempt was unsuccessful. Trying another configuration" + ) + ); + timeout = setTimeout(update, 0); + } else { + alerts.addAlert( + "" + + filter("translate")("Oh Snap!") + + " " + + filter("translate")( + "Could not connect to the aria2 RPC server. Will retry in 10 secs. You might want to check the connection settings by going to Settings > Connection Settings" + ), + "error" + ); + timeout = setTimeout(update, globalTimeout); + } + }; + + syscall.invoke({ + name: "system.multicall", + params: [params], + success: function(data) { + var failed = _.some(data.result, function(d) { + return d.code && d.message === "Unauthorized"; + }); + + if (failed) { + needNewConnection = true; + alerts.addAlert( + "" + + filter("translate")("Oh Snap!") + + " " + + filter("translate")( + "Authentication failed while connecting to Aria2 RPC server. Will retry in 10 secs. You might want to confirm your authentication details by going to Settings > Connection Settings", + "error" + ) + ); + timeout = setTimeout(update, globalTimeout); + return; + } + + if (configurations.length) { + // configuration worked, save it in cookie for next time and + // delete the pipelined configurations!! + if (currentToken) + alerts.addAlert( + filter("translate")("Successfully connected to Aria2 through its remote RPC …"), + "success" + ); + else + alerts.addAlert( + filter("translate")( + "Successfully connected to Aria2 through remote RPC, however the connection is still insecure. For complete security try adding an authorization secret token while starting Aria2 (through the flag --rpc-secret)" + ) + ); + configurations = []; + } - _.each(cbs, function(hnd) { - hnd.cb(hnd.data); + utils.setCookie("aria2conf", currentConf); + + var cbs = []; + _.each(data.result, function(d, i) { + var handle = subs[i]; + if (handle) { + if (d.code) { + console.error(handle, d); + alerts.addAlert(d.message, "error"); + } + // run them later as the cb itself can mutate the subscriptions + cbs.push({ cb: handle.cb, data: d }); + if (handle.once) { + handle.once = 2; + } + } + }); + + _.each(cbs, function(hnd) { + hnd.cb(hnd.data); + }); + + rootScope.$digest(); + + if (forceNextUpdate) { + forceNextUpdate = false; + timeout = setTimeout(update, 0); + } else { + timeout = setTimeout(update, globalTimeout); + } + }, + error: error }); + }; - rootScope.$digest(); + // initiate the update loop + timeout = setTimeout(update, globalTimeout); - if (forceNextUpdate) { - forceNextUpdate = false; - timeout = setTimeout(update, 0); - } - else { - timeout = setTimeout(update, globalTimeout); + return { + // conf can be configuration or array of configurations, + // each one will be tried one after the other till success, + // for all options for one conf read rpc/syscall.js + configure: function(conf) { + alerts.addAlert( + filter("translate")( + "Trying to connect to aria2 using the new connection configuration" + ), + "info" + ); + + if (conf instanceof Array) configurations = conf; + else configurations = [conf]; + + if (timeout) { + clearTimeout(timeout); + timeout = setTimeout(update, 0); + } + }, + + // get current configuration being used + getConfiguration: function() { + return currentConf; + }, + + // get currently configured directURL + getDirectURL: function() { + return currentConf.directURL; + }, + + // syscall is done only once, delay is optional + // and pass true to only dispatch it in the global timeout + // which can be used to batch up once calls + once: function(name, params, cb, delay) { + cb = cb || angular.noop; + params = params || []; + + subscriptions.push({ + once: true, + name: "aria2." + name, + params: params, + cb: cb + }); + + if (!delay) { + this.forceUpdate(); + } + }, + + // callback is called each time with updated syscall data + // after the global timeout, delay is optional and pass it + // true to dispatch the first syscall also on global timeout + // which can be used to batch the subscribe calls + subscribe: function(name, params, cb, delay) { + cb = cb || angular.noop; + params = params || []; + + var handle = { + once: false, + name: "aria2." + name, + params: params, + cb: cb + }; + subscriptions.push(handle); + + if (!delay) this.forceUpdate(); + return handle; + }, + + // remove the subscribed callback by passing + // the returned handle bysubscribe + unsubscribe: function(handle) { + var ind = subscriptions.indexOf(handle); + subscriptions[ind] = null; + }, + + // force the global syscall update + forceUpdate: function() { + if (timeout) { + clearTimeout(timeout); + timeout = setTimeout(update, 0); + } else { + // a batch call is already in progress, + // wait till it returns and force the next one + forceNextUpdate = true; + } } - }, - error: error - }); - }; - - // initiate the update loop - timeout = setTimeout(update, globalTimeout); - - return { - // conf can be configuration or array of configurations, - // each one will be tried one after the other till success, - // for all options for one conf read rpc/syscall.js - configure: function(conf) { - alerts.addAlert(filter('translate')('Trying to connect to aria2 using the new connection configuration'), 'info'); - - if (conf instanceof Array) - configurations = conf; - else - configurations = [conf]; - - if (timeout) { - clearTimeout(timeout); - timeout = setTimeout(update, 0); - } - }, - - // get current configuration being used - getConfiguration: function() { return currentConf }, - - // get currently configured directURL - getDirectURL : function() { return currentConf.directURL }, - - // syscall is done only once, delay is optional - // and pass true to only dispatch it in the global timeout - // which can be used to batch up once calls - once: function(name, params, cb, delay) { - cb = cb || angular.noop; - params = params || []; - - subscriptions.push({ - once: true, - name: 'aria2.' + name, - params: params, - cb: cb - }); - - if (!delay) { - this.forceUpdate(); - } - }, - - // callback is called each time with updated syscall data - // after the global timeout, delay is optional and pass it - // true to dispatch the first syscall also on global timeout - // which can be used to batch the subscribe calls - subscribe: function(name, params, cb, delay) { - cb = cb || angular.noop; - params = params || []; - - var handle = { - once: false, - name: 'aria2.' + name, - params: params, - cb: cb }; - subscriptions.push(handle); - - if (!delay) this.forceUpdate(); - return handle; - }, - - // remove the subscribed callback by passing - // the returned handle bysubscribe - unsubscribe: function(handle) { - var ind = subscriptions.indexOf(handle); - subscriptions[ind] = null; - }, - - // force the global syscall update - forceUpdate: function() { - if (timeout) { - clearTimeout(timeout); - timeout = setTimeout(update, 0); - } - else { - // a batch call is already in progress, - // wait till it returns and force the next one - forceNextUpdate = true; - } } - }; -}]); + ]); diff --git a/js/services/rpc/sockcall.js b/js/services/rpc/sockcall.js index 4468c9b8..4830e761 100644 --- a/js/services/rpc/sockcall.js +++ b/js/services/rpc/sockcall.js @@ -1,143 +1,157 @@ angular -.module('webui.services.rpc.sockcall', [ - 'webui.services.deps', 'webui.services.utils', 'webui.services.base64', - 'webui.services.alerts' -]) -.factory('$sockcall', ['$_', '$json', '$name', '$utils', '$alerts', -function(_, JSON, name, utils, alerts) { - var sockRPC = { - // true when sockrpc is ready to be used, - // false when either initializing - // or no support for web sockets - initialized: false, - - // ongoing connection handles containing connection id and callbacks - handles: [], - - // websocket connection socket used for all connections - sock: null, - - // connection configuration - conf: null, - - // socket connection scheme, default to unencrypted connection - scheme: 'ws', - - // called when a connection error occurs - onerror: function(ev) { - _.each(sockRPC.handles, function(h) { h.error() }); - sockRPC.handles = []; - sockRPC.initialized = false; - if (sockRPC.onready) { - sockRPC.onready(); - sockRPC.onready = null; - } - }, - onclose: function(ev) { - if (sockRPC.handles && sockRPC.handles.length) - sockRPC.onerror('Connection reset while calling aria2'); - sockRPC.initialized = false; - if (sockRPC.onready) { - sockRPC.onready(); - sockRPC.onready = null; - } - }, - - // when connection opens - onopen: function() { - console.log('websocket initialized!!!'); - sockRPC.initialized = true; - if (sockRPC.onready) { - sockRPC.onready(); - sockRPC.onready = null; - } - }, - - - // when message is recieved - onmessage: function(message) { - var data = JSON.parse(message.data); - - // reverse loop because we are deleting elements - // while looping over the old items - for (var i = sockRPC.handles.length - 1; i >= 0; i--) { - if (sockRPC.handles[i].id === data.id) { - sockRPC.handles[i].success(data); - sockRPC.handles.splice(i, 1); - return; + .module("webui.services.rpc.sockcall", [ + "webui.services.deps", + "webui.services.utils", + "webui.services.base64", + "webui.services.alerts" + ]) + .factory("$sockcall", [ + "$_", + "$json", + "$name", + "$utils", + "$alerts", + function(_, JSON, name, utils, alerts) { + var sockRPC = { + // true when sockrpc is ready to be used, + // false when either initializing + // or no support for web sockets + initialized: false, + + // ongoing connection handles containing connection id and callbacks + handles: [], + + // websocket connection socket used for all connections + sock: null, + + // connection configuration + conf: null, + + // socket connection scheme, default to unencrypted connection + scheme: "ws", + + // called when a connection error occurs + onerror: function(ev) { + _.each(sockRPC.handles, function(h) { + h.error(); + }); + sockRPC.handles = []; + sockRPC.initialized = false; + if (sockRPC.onready) { + sockRPC.onready(); + sockRPC.onready = null; + } + }, + onclose: function(ev) { + if (sockRPC.handles && sockRPC.handles.length) + sockRPC.onerror("Connection reset while calling aria2"); + sockRPC.initialized = false; + if (sockRPC.onready) { + sockRPC.onready(); + sockRPC.onready = null; + } + }, + + // when connection opens + onopen: function() { + console.log("websocket initialized!!!"); + sockRPC.initialized = true; + if (sockRPC.onready) { + sockRPC.onready(); + sockRPC.onready = null; + } + }, + + // when message is recieved + onmessage: function(message) { + var data = JSON.parse(message.data); + + // reverse loop because we are deleting elements + // while looping over the old items + for (var i = sockRPC.handles.length - 1; i >= 0; i--) { + if (sockRPC.handles[i].id === data.id) { + sockRPC.handles[i].success(data); + sockRPC.handles.splice(i, 1); + return; + } + } + }, + + // call to use the rpc + invoke: function(opts) { + var data = { + jsonrpc: 2.0, + id: utils.uuid(), + method: opts.name, + params: opts.params && opts.params.length ? opts.params : undefined + }; + + if (data.params && !data.params.length) data.params = undefined; + + sockRPC.handles.push({ + success: opts.success || angular.noop, + error: opts.error || angular.noop, + id: data.id + }); + sockRPC.sock.send(JSON.stringify(data)); + }, + + // should be called initially to start using the sock rpc + // onready is called when initial connection is resolved + init: function(conf, onready) { + sockRPC.initialized = false; + if (sockRPC.onready) { + // make previous call is resolved + sockRPC.onready(); + sockRPC.onready = null; + } + + if (typeof WebSocket == "undefined") { + alerts.addAlert("Web sockets are not supported! Falling back to JSONP.", "info"); + onready(); + return; + } + sockRPC.conf = conf || sockRPC.conf; + + sockRPC.scheme = sockRPC.conf.encrypt ? "wss" : "ws"; + + if (sockRPC.sock) { + sockRPC.sock.onopen = sockRPC.sock.onmessage = sockRPC.sock.onerror = sockRPC.sock.onclose = null; + sockRPC.onerror({ message: "Changing the websocket aria2 server details" }); + } + + try { + var authUrl = + sockRPC.scheme + "://" + conf.host + ":" + conf.port + (conf.path || "/jsonrpc"); + if (sockRPC.conf.auth && sockRPC.conf.auth.user && sockRPC.conf.auth.pass) { + authUrl = + sockRPC.scheme + + "://" + + sockRPC.conf.auth.user + + ":" + + sockRPC.conf.auth.pass + + "@" + + sockRPC.conf.host + + ":" + + sockRPC.conf.port + + (conf.path || "/jsonrpc"); + } + + sockRPC.sock = new WebSocket(authUrl); + sockRPC.sock.onopen = sockRPC.onopen; + sockRPC.sock.onclose = sockRPC.onclose; + sockRPC.sock.onerror = sockRPC.onerror; + sockRPC.sock.onmessage = sockRPC.onmessage; + sockRPC.onready = onready; + } catch (ex) { + // ignoring IE security exception on local ip addresses + console.log("not using websocket for aria2 rpc due to: ", ex); + alerts.addAlert("Web sockets not working due to " + ex.message, "info"); + onready(); + } } - } - }, - - // call to use the rpc - invoke: function(opts) { - var data = { - jsonrpc: 2.0, - id: utils.uuid(), - method: opts.name, - params: opts.params && opts.params.length ? opts.params : undefined }; - if (data.params && !data.params.length) data.params = undefined; - - sockRPC.handles.push({ - success: opts.success || angular.noop, - error: opts.error || angular.noop, - id: data.id - }); - sockRPC.sock.send( JSON.stringify(data) ); - }, - - // should be called initially to start using the sock rpc - // onready is called when initial connection is resolved - init: function(conf, onready) { - sockRPC.initialized = false; - if (sockRPC.onready) { - // make previous call is resolved - sockRPC.onready(); - sockRPC.onready = null; - } - - if (typeof WebSocket == "undefined") { - alerts.addAlert('Web sockets are not supported! Falling back to JSONP.', 'info'); - onready(); - return; - } - sockRPC.conf = conf || sockRPC.conf; - - sockRPC.scheme = sockRPC.conf.encrypt ? 'wss' : 'ws'; - - if (sockRPC.sock) { - sockRPC.sock.onopen = sockRPC.sock.onmessage = sockRPC.sock.onerror = sockRPC.sock.onclose = null; - sockRPC.onerror({message: 'Changing the websocket aria2 server details'}); - } - - try { - var authUrl = sockRPC.scheme + '://' + conf.host + ':' + conf.port + (conf.path || '/jsonrpc'); - if (sockRPC.conf.auth && sockRPC.conf.auth.user && sockRPC.conf.auth.pass) { - authUrl = sockRPC.scheme + '://' + - sockRPC.conf.auth.user + ":" + - sockRPC.conf.auth.pass + "@" + - sockRPC.conf.host + ':' + - sockRPC.conf.port + (conf.path || '/jsonrpc'); - } - - sockRPC.sock = new WebSocket(authUrl); - sockRPC.sock.onopen = sockRPC.onopen; - sockRPC.sock.onclose = sockRPC.onclose; - sockRPC.sock.onerror = sockRPC.onerror; - sockRPC.sock.onmessage = sockRPC.onmessage; - sockRPC.onready = onready; - } - catch (ex) { - // ignoring IE security exception on local ip addresses - console.log('not using websocket for aria2 rpc due to: ', ex); - alerts.addAlert('Web sockets not working due to ' + ex.message, 'info'); - onready(); - } - }, - }; - - return sockRPC; -}]); - + return sockRPC; + } + ]); diff --git a/js/services/rpc/syscall.js b/js/services/rpc/syscall.js index d5bd3e2d..c5c56b0f 100644 --- a/js/services/rpc/syscall.js +++ b/js/services/rpc/syscall.js @@ -1,51 +1,57 @@ angular -.module('webui.services.rpc.syscall', [ - 'webui.services.rpc.jsoncall', 'webui.services.rpc.sockcall', - 'webui.services.utils', 'webui.services.alerts' -]) -.factory('$syscall', ['$log', '$jsoncall', '$sockcall', '$alerts', -function(log, jsonRPC, sockRPC, alerts) { - return { - state: 'none', - // called to initialize the rpc interface, call everytime configuration changes - // conf has the following structure: - // { - // host (string): host for the aria2 server - // port (number): port number for the aria2 server - // encrypt (boolean, optional): true if encryption is enabled in the aria2 server - // auth (optional): { - // token (string): secret token for authentication (--rpc-secret) - // user (string): username for http authentication if enabled - // pass (string): password for the http authentication if enabled - // } - init: function(conf) { - console.log("Syscall is initializing to", conf); - this.state = 'initializing'; - jsonRPC.init(conf); - var syscall = this; - sockRPC.init(conf, function() { - console.log("Syscall is ready"); - syscall.state = 'ready'; - }); - }, + .module("webui.services.rpc.syscall", [ + "webui.services.rpc.jsoncall", + "webui.services.rpc.sockcall", + "webui.services.utils", + "webui.services.alerts" + ]) + .factory("$syscall", [ + "$log", + "$jsoncall", + "$sockcall", + "$alerts", + function(log, jsonRPC, sockRPC, alerts) { + return { + state: "none", + // called to initialize the rpc interface, call everytime configuration changes + // conf has the following structure: + // { + // host (string): host for the aria2 server + // port (number): port number for the aria2 server + // encrypt (boolean, optional): true if encryption is enabled in the aria2 server + // auth (optional): { + // token (string): secret token for authentication (--rpc-secret) + // user (string): username for http authentication if enabled + // pass (string): password for the http authentication if enabled + // } + init: function(conf) { + console.log("Syscall is initializing to", conf); + this.state = "initializing"; + jsonRPC.init(conf); + var syscall = this; + sockRPC.init(conf, function() { + console.log("Syscall is ready"); + syscall.state = "ready"; + }); + }, - // call this to start an rpc call, opts has the following structure: - // { - // name (string): name of the actual aria2 syscall - // success (function): callback called with (parsed) data if rpc is successfull - // error (function): callback called when an error occurs - // params (array, optional): the params for some syscall (like multicall) and is optional for others - // } - invoke: function(opts) { - opts.success = opts.success || angular.noop; - opts.error = opts.error || angular.noop; + // call this to start an rpc call, opts has the following structure: + // { + // name (string): name of the actual aria2 syscall + // success (function): callback called with (parsed) data if rpc is successfull + // error (function): callback called when an error occurs + // params (array, optional): the params for some syscall (like multicall) and is optional for others + // } + invoke: function(opts) { + opts.success = opts.success || angular.noop; + opts.error = opts.error || angular.noop; - if (sockRPC.initialized) { - return sockRPC.invoke(opts); - } - else { - return jsonRPC.invoke(opts); - } + if (sockRPC.initialized) { + return sockRPC.invoke(opts); + } else { + return jsonRPC.invoke(opts); + } + } + }; } - }; -}]); + ]); diff --git a/js/services/settings/filters.js b/js/services/settings/filters.js index 27552a0e..23248428 100644 --- a/js/services/settings/filters.js +++ b/js/services/settings/filters.js @@ -1,14 +1,17 @@ -angular.module('webui.services.settings.filters', []) -.value('$globalsettingsexclude', [ - "checksum", "index-out", "out", "pause", "select-file" -]) -.value('$waitingsettingsexclude', [ - "dry-run", "metalink-base-uri", "parameterized-uri", "pause", - "piece-length" -]) -.value('$activesettingsfilter', [ - "bt-max-peers", "bt-request-peer-speed-limit", "bt-remove-unselected-file", - "max-download-limit", "max-upload-limit", -]); - - +angular + .module("webui.services.settings.filters", []) + .value("$globalsettingsexclude", ["checksum", "index-out", "out", "pause", "select-file"]) + .value("$waitingsettingsexclude", [ + "dry-run", + "metalink-base-uri", + "parameterized-uri", + "pause", + "piece-length" + ]) + .value("$activesettingsfilter", [ + "bt-max-peers", + "bt-request-peer-speed-limit", + "bt-remove-unselected-file", + "max-download-limit", + "max-upload-limit" + ]); diff --git a/js/services/settings/settings.js b/js/services/settings/settings.js index d24c213d..fa910e59 100644 --- a/js/services/settings/settings.js +++ b/js/services/settings/settings.js @@ -1,739 +1,830 @@ -angular.module('webui.services.settings', []) -.value('$fileSettings', { - // {{{ settings (for files) - "all-proxy": { - val: '', - desc: 'Use this proxy server for all protocols. To erase previously defined proxy, use "". You can override this setting and specify a proxy server for a particular protocol using http-proxy, https-proxy and ftp-proxy options. This affects all URIs. The format of PROXY is [http://][USER:PASSWORD@]HOST[:PORT].' - }, - - "all-proxy-passwd": { - val: '', - desc: "Set password for all-proxy option." - }, - - "all-proxy-user": { - val: '', - desc: "Set user for all-proxy option." - }, - - "allow-overwrite": { - val: false, - options: ["true", "false"], - desc: "Restart download from scratch if the corresponding control file doesn't exist. See also auto-file-renaming option. Default: false" - }, - - "allow-piece-length-change": { - val: false, - options: ["true", "false"], - desc: "If false is given, aria2 aborts download when a piece length is different from one in a control file. If true is given, you can proceed but some download progress will be lost. Default: false" - }, - - "always-resume": { - val: true, - options: ["true", "false"], - desc: "Always resume download. If true is given, aria2 always tries to resume download and if resume is not possible, aborts download. If false is given, when all given URIs do not support resume or aria2 encounters N URIs which does not support resume (N is the value specified using --max-resume-failure-tries option), aria2 downloads file from scratch. See --max-resume-failure-tries option. Default: true" - }, - - "async-dns": { - val: true, - options: ["true", "false"], - desc: "Enable asynchronous DNS. Default: true" - }, - - "auto-file-renaming": { - val: true, - options: ["true", "false"], - desc: "Rename file name if the same file already exists. This option works only in HTTP(S)/FTP download. The new file name has a dot and a number(1..9999) appended. Default: true" - }, - - "bt-detach-seed-only": { - desc: "Exclude seed only downloads when counting concurrent active downloads (See -j option). This means that if -j3 is given and this option is turned on and 3 downloads are active and one of those enters seed mode, then it is excluded from active download count (thus it becomes 2), and the next download waiting in queue gets started. But be aware that seeding item is still recognized as active download in RPC method. Default: false", - val: false, - options: ["true", "false"], - }, - - "bt-enable-hook-after-hash-check": { - desc: "Allow hook command invocation after hash check (see -V option) in BitTorrent download. By default, when hash check succeeds, the command given by --on-bt-download-complete is executed. To disable this action, give false to this option. Default: true", - val: true, - options: ["true", "false"], - }, - - "bt-enable-lpd": { - desc: "Enable Local Peer Discovery. If a private flag is set in a torrent, aria2 doesn't use this feature for that download even if true is given. Default: false", - val: false, - options: ["true", "false"], - }, - - "bt-exclude-tracker": { - val: '', - desc: "Comma separated list of BitTorrent tracker's announce URI to remove. You can use special value * which matches all URIs, thus removes all announce URIs. When specifying * in shell command-line, don't forget to escape or quote it. See also --bt-tracker option." - }, - - "bt-external-ip": { - val: '', - desc: "Specify the external IP address to report to a BitTorrent tracker. Although this function is named external, it can accept any kind of IP addresses. IPADDRESS must be a numeric IP address." - - }, - - "bt-force-encryption": { - desc: "Requires BitTorrent message payload encryption with arc4. This is a shorthand of --bt-require-crypto --bt-min-crypto-level=arc4. This option does not change the option value of those options. If true is given, deny legacy BitTorrent handshake and only use Obfuscation handshake and always encrypt message payload. Default: false", - val: false, - options: ["true", "false"], - }, - - "bt-hash-check-seed": { - desc: "If true is given, after hash check using --check-integrity option and file is complete, continue to seed file. If you want to check file and download it only when it is damaged or incomplete, set this option to false. This option has effect only on BitTorrent download. Default: true", - val: true, - options: ["true", "false"], - }, - - "bt-max-open-files": { - val: 100, - desc: "Specify maximum number of files to open in each BitTorrent download. Default: 100" - }, - - "bt-max-peers": { - val: 55, - desc: "Specify the maximum number of peers per torrent. 0 means unlimited. See also bt-request-peer-speed-limit option. Default: 55" - }, - - "bt-metadata-only": { - desc: "Download metadata only. The file(s) described in metadata will not be downloaded. This option has effect only when BitTorrent Magnet URI is used. See also --bt-save-metadata option. Default: false", - val: false, - options: ["true", "false"], - }, - - "bt-min-crypto-level": { - desc: "Set minimum level of encryption method. If several encryption methods are provided by a peer, aria2 chooses the lowest one which satisfies the given level. Default: plain", - val: 'plain', - options: ["plain", "arc4"] - }, - - "bt-prioritize-piece": { - val: '', - desc: "Try to download first and last pieces of each file first. This is useful for previewing files. The argument can contain 2 keywords: head and tail. To include both keywords, they must be separated by comma. These keywords can take one parameter, SIZE. For example, if head= is specified, pieces in the range of first SIZE bytes of each file get higher priority. tail= means the range of last SIZE bytes of each file. SIZE can include K or M (1K = 1024, 1M = 1024K). If SIZE is omitted, SIZE=1M is used." - }, - - "bt-request-peer-speed-limit": { - val: '50K', - desc: "If the whole download speed of every torrent is lower than SPEED, aria2 temporarily increases the number of peers to try for more download speed. Configuring this option with your preferred download speed can increase your download speed in some cases. You can append K or M (1K = 1024, 1M = 1024K). Default: 50K" - }, - - "bt-require-crypto": { - desc: "If true is given, aria2 doesn't accept and establish connection with legacy BitTorrent handshake(19BitTorrent protocol). Thus aria2 always uses Obfuscation handshake. Default: false", - val: false, - options: ["true", "false"], - }, - - "bt-save-metadata": { - desc: "Save metadata as .torrent file. This option has effect only when BitTorrent Magnet URI is used. The filename is hex encoded info hash with suffix .torrent. The directory to be saved is the same directory where download file is saved. If the same file already exists, metadata is not saved. See also --bt-metadata-only option. Default: false", - val: false, - options: ["true", "false"], - }, - - "bt-seed-unverified": { - desc: "Seed previously downloaded files without verifying piece hashes. Default: false", - val: false, - options: ["true", "false"], - }, - - "bt-stop-timeout": { - val: 0, - desc: "Stop BitTorrent download if download speed is 0 in consecutive SEC seconds. If 0 is given, this feature is disabled. Default: 0" - }, - - "bt-tracker": { - val: '', - desc: "Comma separated list of additional BitTorrent tracker's announce URI. These URIs are not affected by --bt-exclude-tracker option because they are added after URIs in --bt-exclude-tracker option are removed." - }, - - "bt-tracker-connect-timeout": { - val: 60, - desc: "Set the connect timeout in seconds to establish connection to tracker. After the connection is established, this option makes no effect and --bt-tracker-timeout option is used instead. Default: 60" - }, - - "bt-tracker-interval": { - val: 0, - desc: "Set the interval in seconds between tracker requests. This completely overrides interval value and aria2 just uses this value and ignores the min interval and interval value in the response of tracker. If 0 is set, aria2 determines interval based on the response of tracker and the download progress. Default: 0" - }, - - "bt-tracker-timeout": { - val: 60, - desc: "Set timeout in seconds. Default: 60" - }, - - "bt-remove-unselected-file": { - desc: "Removes the unselected files when download is completed in BitTorrent. To select files, use --select-file option. If it is not used, all files are assumed to be selected. Please use this option with care because it will actually remove files from your disk. Default: false", - val: false, - options: ["true", "false"], - }, - - "check-certificate": { - desc: "Verify the peer using certificates specified in --ca-certificate option. Default: true", - val: true, - options: ["true", "false"], - }, - - "check-integrity": { - desc: "Check file integrity by validating piece hashes or a hash of entire file. This option has effect only in BitTorrent, Metalink downloads with checksums or HTTP(S)/FTP downloads with --checksum option. If piece hashes are provided, this option can detect damaged portions of a file and re-download them. If a hash of entire file is provided, hash check is only done when file has been already download. This is determined by file length. If hash check fails, file is re-downloaded from scratch. If both piece hashes and a hash of entire file are provided, only piece hashes are used. Default: false", - val: false, - options: ["true", "false"], - }, - - "conditional-get": { - desc: "Download file only when the local file is older than remote file. This function only works with HTTP(S) downloads only. It does not work if file size is specified in Metalink. It also ignores Content-Disposition header. If a control file exists, this option will be ignored. This function uses If-Modified-Since header to get only newer file conditionally. When getting modification time of local file, it uses user supplied filename(see --out option) or filename part in URI if --out is not specified. To overwrite existing file, --allow-overwrite is required. Default: false", - val: false, - options: ["true", "false"], - }, - - "connect-timeout": { - val: 60, - desc: "Set the connect timeout in seconds to establish connection to HTTP/FTP/proxy server. After the connection is established, this option makes no effect and --timeout option is used instead. Default: 60" - }, - - "continue": { - desc: "Continue downloading a partially downloaded file. Use this option to resume a download started by a web browser or another program which downloads files sequentially from the beginning. Currently this option is only applicable to HTTP(S)/FTP downloads.", - val: true, - options: ["true", "false"], - }, - - "daemon": { - desc: "Run as daemon. The current working directory will be changed to / and standard input, standard output and standard error will be redirected to /dev/null. Default: false", - val: false, - options: ["true", "false"], - }, - - "deferred-input": { - desc: "If true is given, aria2 does not read all URIs and options from file specified by --input-file option at startup, but it reads one by one when it needs later. This may reduce memory usage if input file contains a lot of URIs to download. If false is given, aria2 reads all URIs and options at startup. Default: false", - val: false, - options: ["true", "false"], - }, - - "dir": { - val: '', - desc: "The directory to store the downloaded file." - }, - - "disable-ipv6": { - desc: "Disable IPv6. This is useful if you have to use broken DNS and want to avoid terribly slow AAAA record lookup. Default: false", - val: false, - options: ["true", "false"], - }, - - "dry-run": { - desc: "If true is given, aria2 just checks whether the remote file is available and doesn't download data. This option has effect on HTTP/FTP download. BitTorrent downloads are canceled if true is specified. Default: false", - val: false, - options: ["true", "false"], - }, - - "enable-async-dns6": { - desc: "Enable IPv6 name resolution in asynchronous DNS resolver. This option will be ignored when --async-dns=false. Default: false", - val: false, - options: ["true", "false"], - }, - - "enable-color": { - desc: "Enable color output for a terminal. Default: true", - val: true, - options: ["true", "false"], - }, - - "enable-dht": { - desc: "Enable IPv4 DHT functionality. It also enables UDP tracker support. If a private flag is set in a torrent, aria2 doesn’t use DHT for that download even if true is given. Default: true", - val: true, - options: ["true", "false"], - }, - - "enable-dht6": { - desc: "Enable IPv6 DHT functionality. If a private flag is set in a torrent, aria2 doesn’t use DHT for that download even if true is given. Use --dht-listen-port option to specify port number to listen on. See also --dht-listen-addr6 option.", - val: false, - options: ["true", "false"], - }, - - "enable-http-keep-alive": { - desc: "Enable HTTP/1.1 persistent connection. Default: true", - val: true, - options: ["true", "false"], - }, - - "enable-http-pipelining": { - desc: "Enable HTTP/1.1 pipelining. Default: false", - val: false, - options: ["true", "false"], - }, - - "enable-peer-exchange": { - desc: "Enable Peer Exchange extension. If a private flag is set in a torrent, this feature is disabled for that download even if true is given. Default: true", - val: true, - options: ["true", "false"], - }, - - "enable-mmap": { - desc: "Map files into memory. This option may not work if the file space is not pre-allocated. See --file-allocation. Default: false", - val: false, - options: ["true", "false"], - }, - - "enable-rpc": { - desc: "Enable JSON-RPC/XML-RPC server. It is strongly recommended to set secret authorization token using --rpc-secret option. See also --rpc-listen-port option. Default: false", - val: false, - options: ["true", "false"], - }, - - "file-allocation": { - desc: "Specify file allocation method. none doesn't pre-allocate file space. prealloc pre-allocates file space before download begins. This may take some time depending on the size of the file. If you are using newer file systems such as ext4 (with extents support), btrfs, xfs or NTFS(MinGW build only), falloc is your best choice. It allocates large(few GiB) files almost instantly. Don't use falloc with legacy file systems such as ext3 and FAT32 because it takes almost same time as prealloc and it blocks aria2 entirely until allocation finishes. falloc may not be available if your system doesn't have posix_fallocate(3) function. Possible Values: none, prealloc, falloc Default: prealloc", - val: undefined, - options: ["none", "prealloc", "falloc", "trunc"] - }, - - "follow-metalink": { - desc: "If true or mem is specified, when a file whose suffix is .meta4 or .metalink or content type of application/metalink4+xml or application/metalink+xml is downloaded, aria2 parses it as a metalink file and downloads files mentioned in it. If mem is specified, a metalink file is not written to the disk, but is just kept in memory. If false is specified, the action mentioned above is not taken. Default: true", - val: true, - options: ["true", "false"], - }, - - "follow-torrent": { - desc: "If true or mem is specified, when a file whose suffix is .torrent or content type is application/x-bittorrent is downloaded, aria2 parses it as a torrent file and downloads files mentioned in it. If mem is specified, a torrent file is not written to the disk, but is just kept in memory. If false is specified, the action mentioned above is not taken. Default: true", - val: true, - options: ["true", "false"], - }, - - "force-save": { - desc: "Save download with --save-session option even if the download is completed or removed. This option also saves control file in that situations. This may be useful to save BitTorrent seeding which is recognized as completed state. Default: false", - val: false, - options: ["true", "false"], - }, - - "ftp-passwd": { - val: 'ARIA2USER@', - desc: "Set FTP password. This affects all URIs. If user name is embedded but password is missing in URI, aria2 tries to resolve password using .netrc. If password is found in .netrc, then use it as password. If not, use the password specified in this option. Default: ARIA2USER@" - }, - - "ftp-pasv": { - desc: "Use the passive mode in FTP. If false is given, the active mode will be used. Default: true", - val: true, - options: ["true", "false"], - }, - - "ftp-proxy": { - val: '', - desc: 'Use this proxy server for FTP. To erase previously defined proxy, use "". See also --all-proxy option. This affects all URIs. The format of PROXY is [http://][USER:PASSWORD@]HOST[:PORT].' - }, - - "ftp-proxy-passwd": { - val: '', - desc: "Set password for --ftp-proxy option." - }, - - "ftp-proxy-user": { - val: '', - desc: "Set user for --ftp-proxy option." - }, - - "ftp-reuse-connection": { - desc: "Reuse connection in FTP. Default: true.", - val: true, - options: ["true", "false"], - }, - - "ftp-type": { - desc: "Set FTP transfer type. TYPE is either binary or ascii. Default: binary", - val: 'binary', - options: ["binary", "ascii"] - }, - - "ftp-user": { - val: 'anonymous', - desc: "Set FTP user. This affects all URIs. Default: anonymous" - }, - - "header": { - val: '', - desc: "Append HEADER to HTTP request header.", - multiline: true, - }, - - "http-accept-gzip": { - desc: "Send Accept: deflate, gzip request header and inflate response if remote server responds with Content-Encoding: gzip or Content-Encoding: deflate. Default: false", - val: false, - options: ["true", "false"], - }, - - "http-auth-challenge": { - desc: "Send HTTP authorization header only when it is requested by the server. If false is set, then authorization header is always sent to the server. There is an exception: if username and password are embedded in URI, authorization header is always sent to the server regardless of this option. Default: false", - val: false, - options: ["true", "false"], - }, - - "http-no-cache": { - desc: "Send Cache-Control: no-cache and Pragma: no-cache header to avoid cached content. If false is given, these headers are not sent and you can add Cache-Control header with a directive you like using --header option. Default: true", - val: true, - options: ["true", "false"], - }, - - "http-user": { - val: '', - desc: "Set HTTP username.", - }, - - "http-passwd": { - val: '', - desc: "Set HTTP password.", - }, - - "http-proxy": { - val: '', - desc: 'Use this proxy server for HTTP. To erase previously defined proxy, use "". See also --all-proxy option. This affects all URIs. The format of PROXY is [http://][USER:PASSWORD@]HOST[:PORT].' - }, - - "http-proxy-passwd": { - val: '', - desc: "Set password for --http-proxy option." - }, - - "http-proxy-user": { - val: '', - desc: "Set user for --http-proxy option." - }, - - "human-readable": { - desc: "Print sizes and speed in human readable format (e.g., 1.2Ki, 3.4Mi) in the console readout. Default: true", - val: true, - options: ["true", "false"], - }, - - "index-out": { - val: undefined, - desc: "Set file path for file with index=INDEX. You can find the file index using the --show-files option. PATH is a relative path to the path specified in --dir option. You can use this option multiple times. Using this option, you can specify the output filenames of BitTorrent downloads." - }, - - "lowest-speed-limit": { - val: '0', - desc: "Close connection if download speed is lower than or equal to this value(bytes per sec). 0 means aria2 does not have a lowest speed limit. You can append K or M (1K = 1024, 1M = 1024K). This option does not affect BitTorrent downloads. Default: 0" - }, - - "max-connection-per-server": { - val: 1, - desc: "The maximum number of connections to one server for each download. Default: 1" - }, - - "max-download-limit": { - val: '0', - desc: "Set max download speed per each download in bytes/sec. 0 means unrestricted. You can append K or M (1K = 1024, 1M = 1024K). To limit the overall download speed, use --max-overall-download-limit option. Default: 0" - }, - - "max-file-not-found": { - val: 0, - desc: 'If aria2 receives "file not found" status from the remote HTTP/FTP servers NUM times without getting a single byte, then force the download to fail. Specify 0 to disable this option. This options is effective only when using HTTP/FTP servers. Default: 0' - }, - - "max-resume-failure-tries": { - val: 0, - desc: "When used with --always-resume=false, aria2 downloads file from scratch when aria2 detects N number of URIs that does not support resume. If N is 0, aria2 downloads file from scratch when all given URIs do not support resume. See --always-resume option. Default: 0" - }, - - "max-tries": { - val: 0, - desc: "Set number of tries. 0 means unlimited. See also --retry-wait. Default: 5" - }, - - "max-upload-limit": { - val: '0', - desc: "Set max upload speed per each torrent in bytes/sec. 0 means unrestricted. You can append K or M (1K = 1024, 1M = 1024K). To limit the overall upload speed, use --max-overall-upload-limit option. Default: 0" - }, - - "metalink-enable-unique-protocol": { - desc: "If true is given and several protocols are available for a mirror in a metalink file, aria2 uses one of them. Use --metalink-preferred-protocol option to specify the preference of protocol. Default: true", - val: true, - options: ["true", "false"], - }, - - "metalink-language": { - val: '', - desc: "The language of the file to download." - }, - - "metalink-location": { - val: '', - desc: "The location of the preferred server. A comma-delimited list of locations is acceptable, for example, jp,us." - }, - - "metalink-os": { - val: '', - desc: "The operating system of the file to download." - }, - - "metalink-version": { - val: '', - desc: "The version of the file to download." - }, - - "min-split-size": { - val: '20M', - desc: "aria2 does not split less than 2*SIZE byte range. For example, let's consider downloading 20MiB file. If SIZE is 10M, aria2 can split file into 2 range [0-10MiB) and [10MiB-20MiB) and download it using 2 sources(if --split >= 2, of course). If SIZE is 15M, since 2*15M > 20MiB, aria2 does not split file and download it using 1 source. You can append K or M (1K = 1024, 1M = 1024K). Possible Values: 1M -1024M Default: 20M" - }, - - "no-conf": { - desc: "Disable loading aria2.conf file.", - val: false, - options: ["true", "false"], - }, - - "no-file-allocation-limit": { - val: '5M', - desc: "No file allocation is made for files whose size is smaller than SIZE. You can append K or M (1K = 1024, 1M = 1024K). Default: 5M" - }, - - "no-netrc": { - desc: "Disables netrc support. netrc support is enabled by default.Note netrc file is only read at the startup if --no-netrc is false. So if --no-netrc is true at the startup, no netrc is available throughout the session. You cannot get netrc enabled even if you change this setting.", - val: true, - options: ["true", "false"], - }, - - "no-proxy": { - val: '', - desc: "Specify comma separated hostnames, domains and network address with or without CIDR block where proxy should not be used." - }, - - "out": { - val: '', - desc: "The file name of the downloaded file. When --force-sequential option is used, this option is ignored." - }, - - "parameterized-uri": { - desc: "Enable parameterized URI support. You can specify set of parts: http://{sv1,sv2,sv3}/foo.iso. Also you can specify numeric sequences with step counter: http://host/image[000-100:2].img. A step counter can be omitted. If all URIs do not point to the same file, such as the second example above, -Z option is required. Default: false", - val: false, - options: ["true", "false"], - }, - - "pause-metadata": { - desc: "Pause downloads created as a result of metadata download. There are 3 types of metadata downloads in aria2: (1) downloading .torrent file. (2) downloading torrent metadata using magnet link. (3) downloading metalink file. These metadata downloads will generate downloads using their metadata. This option pauses these subsequent downloads. This option is effective only when --enable-rpc=true is given. Default: false", - val: false, - options: ["true", "false"], - }, - - "proxy-method": { - desc: "Set the method to use in proxy request. METHOD is either get or tunnel. HTTPS downloads always use tunnel regardless of this option. Default: get", - val: 'get', - options: ["get", "tunnel"] - }, - - "quiet": { - desc: "Make aria2 quiet (no console output). Default: false", - val: false, - options: ["true", "false"], - }, - - "realtime-chunk-checksum": { - desc: "Validate chunk of data by calculating checksum while downloading a file if chunk checksums are provided. Default: true", - val: true, - options: ["true", "false"], - }, - - "referer": { - val: '', - desc: "Set Referer. This affects all URIs." - }, - - "remote-time": { - desc: "Retrieve timestamp of the remote file from the remote HTTP/FTP server and if it is available, apply it to the local file. Default: false", - val: false, - options: ["true", "false"], - }, - - "remove-control-file": { - desc: "Remove control file before download. Using with --allow-overwrite=true, download always starts from scratch. This will be useful for users behind proxy server which disables resume.", - val: false, - options: ["true", "false"], - }, - - "reuse-uri": { - desc: "Reuse already used URIs if no unused URIs are left. Default: true", - val: true, - options: ["true", "false"], - }, - - "seed-ratio": { - val: 0.0, - desc: "Specify share ratio. Seed completed torrents until share ratio reaches RATIO. You are strongly encouraged to specify equals or more than 1.0 here. Specify 0.0 if you intend to do seeding regardless of share ratio. If --seed-time option is specified along with this option, seeding ends when at least one of the conditions is satisfied. Default: 1.0" - }, - - "seed-time": { - val: 0, - desc: "Specify seeding time in minutes. Also see the --seed-ratio option. Note Specifying --seed-time=0 disables seeding after download completed." - }, - - "select-file": { - val: '', - desc: "Set file to download by specifying its index. You can find the file index using the --show-files option. Multiple indexes can be specified by using ,, for example: 3,6. You can also use - to specify a range: 1-5. , and - can be used together: 1-5,8,9. When used with the -M option, index may vary depending on the query ." - }, - - "split": { - val: 5, - desc: "Download a file using N connections. If more than N URIs are given, first N URIs are used and remaining URIs are used for backup. If less than N URIs are given, those URIs are used more than once so that N connections total are made simultaneously. The number of connections to the same host is restricted by --max-connection-per-server option. See also --min-split-size option. Default: 5" - }, - - "timeout": { - val: 60, - desc: "Set timeout in seconds. Default: 60" - }, - - "use-head": { - desc: "Use HEAD method for the first request to the HTTP server. Default: false", - val: false, - options: ["true", "false"], - }, - - "user-agent": { - val: 'aria2/$VERSION', - desc: "Set user agent for HTTP(S) downloads. Default: aria2/$VERSION, $VERSION is replaced by package version." - }, - - "retry-wait": { - val: 0, - desc: "Set the seconds to wait between retries. With SEC > 0, aria2 will retry download when the HTTP server returns 503 response. Default: 0." - }, - - "metalink-base-uri": { - val: '', - desc: "Specify base URI to resolve relative URI in metalink:url and metalink:metaurl element in a metalink file stored in local disk. If URI points to a directory, URI must end with /." - }, - - "pause": { - desc: "Pause download after added. This option is effective only when --enable-rpc=true is given. Default: false", - val: "false", - options: ["true", "false"], - }, - - "rpc-allow-origin-all": { - desc: "Add Access-Control-Allow-Origin header field with value * to the RPC response. Default: false", - val: false, - options: ["true", "false"], - }, - - "rpc-listen-all": { - desc: "Listen incoming JSON-RPC/XML-RPC requests on all network interfaces. If false is given, listen only on local loopback interface. Default: false", - val: false, - options: ["true", "false"], - }, - - "rpc-secure": { - desc: "RPC transport will be encrypted by SSL/TLS. The RPC clients must use https scheme to access the server. For WebSocket client, use wss scheme. Use --rpc-certificate and --rpc-private-key options to specify the server certificate and private key.", - val: false, - options: ["true", "false"], - }, - - "stream-piece-selector": { - desc: "Specify piece selection algorithm used in HTTP/FTP download. Piece means fixed length segment which is downloaded in parallel in segmented download. If default is given, aria2 selects piece so that it reduces the number of establishing connection. This is reasonable default behaviour because establishing connection is an expensive operation. If inorder is given, aria2 selects piece which has minimum index. Index=0 means first of the file. This will be useful to view movie while downloading it. --enable-http-pipelining option may be useful to reduce reconnection overhead. Please note that aria2 honors --min-split-size option, so it will be necessary to specify a reasonable value to --min-split-size option. If geom is given, at the beginning aria2 selects piece which has minimum index like inorder, but it exponentially increasingly keeps space from previously selected piece. This will reduce the number of establishing connection and at the same time it will download the beginning part of the file first. This will be useful to view movie while downloading it. Default: default", - val: 'default', - options: ["default", "inorder", "geom"] - }, - - "show-console-readout": { - desc: "Show console readout. Default: true", - val: true, - options: ["true", "false"], - }, - - "show-files": { - desc: "Print file listing of “.torrent”, “.meta4” and “.metalink” file and exit. In case of “.torrent” file, additional information (infohash, piece length, etc) is also printed.", - val: false, - options: ["true", "false"], - }, - - "truncate-console-readout": { - desc: "Truncate console readout to fit in a single line. Default: true", - val: true, - options: ["true", "false"], - }, - - "hash-check-only": { - desc: "If true is given, after hash check using --check-integrity option, abort download whether or not download is complete. Default: false", - val: false, - options: ["true", "false"], - }, - - "checksum": { - val: undefined, - desc: "Set checksum. TYPE is hash type. The supported hash type is listed in Hash Algorithms in aria2c -v. DIGEST is hex digest. For example, setting sha-1 digest looks like this: sha-1=0192ba11326fe2298c8cb4de616f4d4140213838 This option applies only to HTTP(S)/FTP downloads." - }, - - "piece-length": { - val: '1M', - desc: "Set a piece length for HTTP/FTP downloads. This is the boundary when aria2 splits a file. All splits occur at multiple of this length. This option will be ignored in BitTorrent downloads. It will be also ignored if Metalink file contains piece hashes. Default: 1M" - }, - - "uri-selector": { - desc: "Specify URI selection algorithm. The possible values are inorder, feedback and adaptive. If inorder is given, URI is tried in the order appeared in the URI list. If feedback is given, aria2 uses download speed observed in the previous downloads and choose fastest server in the URI list. This also effectively skips dead mirrors. The observed download speed is a part of performance profile of servers mentioned in --server-stat-of and --server-stat-if options. If adaptive is given, selects one of the best mirrors for the first and reserved connections. For supplementary ones, it returns mirrors which has not been tested yet, and if each of them has already been tested, returns mirrors which has to be tested again. Otherwise, it doesn't select anymore mirrors. Like feedback, it uses a performance profile of servers. Default: feedback", - val: 'feedback', - options: ["inorder", "feedback", "adaptive"] - } -//}}} -}) -.value('$globalSettings', { - // {{{ settings (global) - "download-result": { - desc: "This option changes the way Download Results is formatted. If OPT is default, print GID, status, average download speed and path/URI. If multiple files are involved, path/URI of first requested file is printed and remaining ones are omitted. If OPT is full, print GID, status, average download speed, percentage of progress and path/URI. The percentage of progress and path/URI are printed for each requested file in each row. Default: default", - val: 'default', - options: ["default", "full"] - }, - "log": { - val: '', - desc: 'The file name of the log file. If - is specified, log is written to stdout. If empty string("") is specified, log is not written to file.' - }, - "log-level": { - desc: "Set log level to output. LEVEL is either debug, info, notice, warn or error. Default: debug.", - val: 'debug', - options: ["debug", "info", "notice", "warn", "error"] - }, - "max-concurrent-downloads": { - val: 5, - desc: "Set maximum number of parallel downloads for every static (HTTP/FTP) URI, torrent and metalink. See also --split option. Default: 5" - }, - "max-download-result": { - val: 1000, - desc: "Set maximum number of download result kept in memory. The download results are completed/error/removed downloads. The download results are stored in FIFO queue and it can store at most NUM download results. When queue is full and new download result is created, oldest download result is removed from the front of the queue and new one is pushed to the back. Setting big number in this option may result high memory consumption after thousands of downloads. Specifying 0 means no download result is kept. Default: 1000" - }, - "max-overall-download-limit": { - val: '0', - desc: "Set max overall download speed in bytes/sec. 0 means unrestricted. You can append K or M (1K = 1024, 1M = 1024K). To limit the download speed per download, use --max-download-limit option. Default: 0." - }, - "max-overall-upload-limit": { - val: '0', - desc: "Set max overall upload speed in bytes/sec. 0 means unrestricted. You can append K or M (1K = 1024, 1M = 1024K). To limit the upload speed per torrent, use --max-upload-limit option. Default: 0." - }, - "save-cookies": { - val: '', - desc: "Save Cookies to FILE in Mozilla/Firefox(1.x/2.x)/ Netscape format. If FILE already exists, it is overwritten. Session Cookies are also saved and their expiry values are treated as 0. Possible Values: /path/to/file." - }, - "save-session": { - val: '', - desc: "Save error/unfinished downloads to FILE on exit. You can pass this output file to aria2c with --input-file option on restart." - }, - "server-stat-of": { - val: '', - desc: "Specify the filename to which performance profile of the servers is saved. You can load saved data using --server-stat-if option. See Server Performance Profile subsection below for file format." - } - // }}} -}) -.value('$globalExclude', [ - "checksum", - "index-out", - "out", - "pause", - "select-file" -]) -.value('$waitingExclude', [ - "dry-run", - "metalink-base-uri", - "parameterized-uri", - "pause", - "piece-length" -]) -.value('$activeInclude', [ - "bt-max-peers", - "bt-request-peer-speed-limit", - "bt-remove-unselected-file", - "max-download-limit", - "max-upload-limit" -]); +angular + .module("webui.services.settings", []) + .value("$fileSettings", { + // {{{ settings (for files) + "all-proxy": { + val: "", + desc: + 'Use this proxy server for all protocols. To erase previously defined proxy, use "". You can override this setting and specify a proxy server for a particular protocol using http-proxy, https-proxy and ftp-proxy options. This affects all URIs. The format of PROXY is [http://][USER:PASSWORD@]HOST[:PORT].' + }, + + "all-proxy-passwd": { + val: "", + desc: "Set password for all-proxy option." + }, + + "all-proxy-user": { + val: "", + desc: "Set user for all-proxy option." + }, + + "allow-overwrite": { + val: false, + options: ["true", "false"], + desc: + "Restart download from scratch if the corresponding control file doesn't exist. See also auto-file-renaming option. Default: false" + }, + + "allow-piece-length-change": { + val: false, + options: ["true", "false"], + desc: + "If false is given, aria2 aborts download when a piece length is different from one in a control file. If true is given, you can proceed but some download progress will be lost. Default: false" + }, + + "always-resume": { + val: true, + options: ["true", "false"], + desc: + "Always resume download. If true is given, aria2 always tries to resume download and if resume is not possible, aborts download. If false is given, when all given URIs do not support resume or aria2 encounters N URIs which does not support resume (N is the value specified using --max-resume-failure-tries option), aria2 downloads file from scratch. See --max-resume-failure-tries option. Default: true" + }, + + "async-dns": { + val: true, + options: ["true", "false"], + desc: "Enable asynchronous DNS. Default: true" + }, + + "auto-file-renaming": { + val: true, + options: ["true", "false"], + desc: + "Rename file name if the same file already exists. This option works only in HTTP(S)/FTP download. The new file name has a dot and a number(1..9999) appended. Default: true" + }, + + "bt-detach-seed-only": { + desc: + "Exclude seed only downloads when counting concurrent active downloads (See -j option). This means that if -j3 is given and this option is turned on and 3 downloads are active and one of those enters seed mode, then it is excluded from active download count (thus it becomes 2), and the next download waiting in queue gets started. But be aware that seeding item is still recognized as active download in RPC method. Default: false", + val: false, + options: ["true", "false"] + }, + + "bt-enable-hook-after-hash-check": { + desc: + "Allow hook command invocation after hash check (see -V option) in BitTorrent download. By default, when hash check succeeds, the command given by --on-bt-download-complete is executed. To disable this action, give false to this option. Default: true", + val: true, + options: ["true", "false"] + }, + + "bt-enable-lpd": { + desc: + "Enable Local Peer Discovery. If a private flag is set in a torrent, aria2 doesn't use this feature for that download even if true is given. Default: false", + val: false, + options: ["true", "false"] + }, + + "bt-exclude-tracker": { + val: "", + desc: + "Comma separated list of BitTorrent tracker's announce URI to remove. You can use special value * which matches all URIs, thus removes all announce URIs. When specifying * in shell command-line, don't forget to escape or quote it. See also --bt-tracker option." + }, + + "bt-external-ip": { + val: "", + desc: + "Specify the external IP address to report to a BitTorrent tracker. Although this function is named external, it can accept any kind of IP addresses. IPADDRESS must be a numeric IP address." + }, + + "bt-force-encryption": { + desc: + "Requires BitTorrent message payload encryption with arc4. This is a shorthand of --bt-require-crypto --bt-min-crypto-level=arc4. This option does not change the option value of those options. If true is given, deny legacy BitTorrent handshake and only use Obfuscation handshake and always encrypt message payload. Default: false", + val: false, + options: ["true", "false"] + }, + + "bt-hash-check-seed": { + desc: + "If true is given, after hash check using --check-integrity option and file is complete, continue to seed file. If you want to check file and download it only when it is damaged or incomplete, set this option to false. This option has effect only on BitTorrent download. Default: true", + val: true, + options: ["true", "false"] + }, + + "bt-max-open-files": { + val: 100, + desc: "Specify maximum number of files to open in each BitTorrent download. Default: 100" + }, + + "bt-max-peers": { + val: 55, + desc: + "Specify the maximum number of peers per torrent. 0 means unlimited. See also bt-request-peer-speed-limit option. Default: 55" + }, + + "bt-metadata-only": { + desc: + "Download metadata only. The file(s) described in metadata will not be downloaded. This option has effect only when BitTorrent Magnet URI is used. See also --bt-save-metadata option. Default: false", + val: false, + options: ["true", "false"] + }, + + "bt-min-crypto-level": { + desc: + "Set minimum level of encryption method. If several encryption methods are provided by a peer, aria2 chooses the lowest one which satisfies the given level. Default: plain", + val: "plain", + options: ["plain", "arc4"] + }, + + "bt-prioritize-piece": { + val: "", + desc: + "Try to download first and last pieces of each file first. This is useful for previewing files. The argument can contain 2 keywords: head and tail. To include both keywords, they must be separated by comma. These keywords can take one parameter, SIZE. For example, if head= is specified, pieces in the range of first SIZE bytes of each file get higher priority. tail= means the range of last SIZE bytes of each file. SIZE can include K or M (1K = 1024, 1M = 1024K). If SIZE is omitted, SIZE=1M is used." + }, + + "bt-request-peer-speed-limit": { + val: "50K", + desc: + "If the whole download speed of every torrent is lower than SPEED, aria2 temporarily increases the number of peers to try for more download speed. Configuring this option with your preferred download speed can increase your download speed in some cases. You can append K or M (1K = 1024, 1M = 1024K). Default: 50K" + }, + + "bt-require-crypto": { + desc: + "If true is given, aria2 doesn't accept and establish connection with legacy BitTorrent handshake(19BitTorrent protocol). Thus aria2 always uses Obfuscation handshake. Default: false", + val: false, + options: ["true", "false"] + }, + + "bt-save-metadata": { + desc: + "Save metadata as .torrent file. This option has effect only when BitTorrent Magnet URI is used. The filename is hex encoded info hash with suffix .torrent. The directory to be saved is the same directory where download file is saved. If the same file already exists, metadata is not saved. See also --bt-metadata-only option. Default: false", + val: false, + options: ["true", "false"] + }, + + "bt-seed-unverified": { + desc: "Seed previously downloaded files without verifying piece hashes. Default: false", + val: false, + options: ["true", "false"] + }, + + "bt-stop-timeout": { + val: 0, + desc: + "Stop BitTorrent download if download speed is 0 in consecutive SEC seconds. If 0 is given, this feature is disabled. Default: 0" + }, + + "bt-tracker": { + val: "", + desc: + "Comma separated list of additional BitTorrent tracker's announce URI. These URIs are not affected by --bt-exclude-tracker option because they are added after URIs in --bt-exclude-tracker option are removed." + }, + + "bt-tracker-connect-timeout": { + val: 60, + desc: + "Set the connect timeout in seconds to establish connection to tracker. After the connection is established, this option makes no effect and --bt-tracker-timeout option is used instead. Default: 60" + }, + + "bt-tracker-interval": { + val: 0, + desc: + "Set the interval in seconds between tracker requests. This completely overrides interval value and aria2 just uses this value and ignores the min interval and interval value in the response of tracker. If 0 is set, aria2 determines interval based on the response of tracker and the download progress. Default: 0" + }, + + "bt-tracker-timeout": { + val: 60, + desc: "Set timeout in seconds. Default: 60" + }, + + "bt-remove-unselected-file": { + desc: + "Removes the unselected files when download is completed in BitTorrent. To select files, use --select-file option. If it is not used, all files are assumed to be selected. Please use this option with care because it will actually remove files from your disk. Default: false", + val: false, + options: ["true", "false"] + }, + + "check-certificate": { + desc: + "Verify the peer using certificates specified in --ca-certificate option. Default: true", + val: true, + options: ["true", "false"] + }, + + "check-integrity": { + desc: + "Check file integrity by validating piece hashes or a hash of entire file. This option has effect only in BitTorrent, Metalink downloads with checksums or HTTP(S)/FTP downloads with --checksum option. If piece hashes are provided, this option can detect damaged portions of a file and re-download them. If a hash of entire file is provided, hash check is only done when file has been already download. This is determined by file length. If hash check fails, file is re-downloaded from scratch. If both piece hashes and a hash of entire file are provided, only piece hashes are used. Default: false", + val: false, + options: ["true", "false"] + }, + + "conditional-get": { + desc: + "Download file only when the local file is older than remote file. This function only works with HTTP(S) downloads only. It does not work if file size is specified in Metalink. It also ignores Content-Disposition header. If a control file exists, this option will be ignored. This function uses If-Modified-Since header to get only newer file conditionally. When getting modification time of local file, it uses user supplied filename(see --out option) or filename part in URI if --out is not specified. To overwrite existing file, --allow-overwrite is required. Default: false", + val: false, + options: ["true", "false"] + }, + + "connect-timeout": { + val: 60, + desc: + "Set the connect timeout in seconds to establish connection to HTTP/FTP/proxy server. After the connection is established, this option makes no effect and --timeout option is used instead. Default: 60" + }, + + continue: { + desc: + "Continue downloading a partially downloaded file. Use this option to resume a download started by a web browser or another program which downloads files sequentially from the beginning. Currently this option is only applicable to HTTP(S)/FTP downloads.", + val: true, + options: ["true", "false"] + }, + + daemon: { + desc: + "Run as daemon. The current working directory will be changed to / and standard input, standard output and standard error will be redirected to /dev/null. Default: false", + val: false, + options: ["true", "false"] + }, + + "deferred-input": { + desc: + "If true is given, aria2 does not read all URIs and options from file specified by --input-file option at startup, but it reads one by one when it needs later. This may reduce memory usage if input file contains a lot of URIs to download. If false is given, aria2 reads all URIs and options at startup. Default: false", + val: false, + options: ["true", "false"] + }, + + dir: { + val: "", + desc: "The directory to store the downloaded file." + }, + + "disable-ipv6": { + desc: + "Disable IPv6. This is useful if you have to use broken DNS and want to avoid terribly slow AAAA record lookup. Default: false", + val: false, + options: ["true", "false"] + }, + + "dry-run": { + desc: + "If true is given, aria2 just checks whether the remote file is available and doesn't download data. This option has effect on HTTP/FTP download. BitTorrent downloads are canceled if true is specified. Default: false", + val: false, + options: ["true", "false"] + }, + + "enable-async-dns6": { + desc: + "Enable IPv6 name resolution in asynchronous DNS resolver. This option will be ignored when --async-dns=false. Default: false", + val: false, + options: ["true", "false"] + }, + + "enable-color": { + desc: "Enable color output for a terminal. Default: true", + val: true, + options: ["true", "false"] + }, + + "enable-dht": { + desc: + "Enable IPv4 DHT functionality. It also enables UDP tracker support. If a private flag is set in a torrent, aria2 doesn’t use DHT for that download even if true is given. Default: true", + val: true, + options: ["true", "false"] + }, + + "enable-dht6": { + desc: + "Enable IPv6 DHT functionality. If a private flag is set in a torrent, aria2 doesn’t use DHT for that download even if true is given. Use --dht-listen-port option to specify port number to listen on. See also --dht-listen-addr6 option.", + val: false, + options: ["true", "false"] + }, + + "enable-http-keep-alive": { + desc: "Enable HTTP/1.1 persistent connection. Default: true", + val: true, + options: ["true", "false"] + }, + + "enable-http-pipelining": { + desc: "Enable HTTP/1.1 pipelining. Default: false", + val: false, + options: ["true", "false"] + }, + + "enable-peer-exchange": { + desc: + "Enable Peer Exchange extension. If a private flag is set in a torrent, this feature is disabled for that download even if true is given. Default: true", + val: true, + options: ["true", "false"] + }, + + "enable-mmap": { + desc: + "Map files into memory. This option may not work if the file space is not pre-allocated. See --file-allocation. Default: false", + val: false, + options: ["true", "false"] + }, + + "enable-rpc": { + desc: + "Enable JSON-RPC/XML-RPC server. It is strongly recommended to set secret authorization token using --rpc-secret option. See also --rpc-listen-port option. Default: false", + val: false, + options: ["true", "false"] + }, + + "file-allocation": { + desc: + "Specify file allocation method. none doesn't pre-allocate file space. prealloc pre-allocates file space before download begins. This may take some time depending on the size of the file. If you are using newer file systems such as ext4 (with extents support), btrfs, xfs or NTFS(MinGW build only), falloc is your best choice. It allocates large(few GiB) files almost instantly. Don't use falloc with legacy file systems such as ext3 and FAT32 because it takes almost same time as prealloc and it blocks aria2 entirely until allocation finishes. falloc may not be available if your system doesn't have posix_fallocate(3) function. Possible Values: none, prealloc, falloc Default: prealloc", + val: undefined, + options: ["none", "prealloc", "falloc", "trunc"] + }, + + "follow-metalink": { + desc: + "If true or mem is specified, when a file whose suffix is .meta4 or .metalink or content type of application/metalink4+xml or application/metalink+xml is downloaded, aria2 parses it as a metalink file and downloads files mentioned in it. If mem is specified, a metalink file is not written to the disk, but is just kept in memory. If false is specified, the action mentioned above is not taken. Default: true", + val: true, + options: ["true", "false"] + }, + + "follow-torrent": { + desc: + "If true or mem is specified, when a file whose suffix is .torrent or content type is application/x-bittorrent is downloaded, aria2 parses it as a torrent file and downloads files mentioned in it. If mem is specified, a torrent file is not written to the disk, but is just kept in memory. If false is specified, the action mentioned above is not taken. Default: true", + val: true, + options: ["true", "false"] + }, + + "force-save": { + desc: + "Save download with --save-session option even if the download is completed or removed. This option also saves control file in that situations. This may be useful to save BitTorrent seeding which is recognized as completed state. Default: false", + val: false, + options: ["true", "false"] + }, + + "ftp-passwd": { + val: "ARIA2USER@", + desc: + "Set FTP password. This affects all URIs. If user name is embedded but password is missing in URI, aria2 tries to resolve password using .netrc. If password is found in .netrc, then use it as password. If not, use the password specified in this option. Default: ARIA2USER@" + }, + + "ftp-pasv": { + desc: + "Use the passive mode in FTP. If false is given, the active mode will be used. Default: true", + val: true, + options: ["true", "false"] + }, + + "ftp-proxy": { + val: "", + desc: + 'Use this proxy server for FTP. To erase previously defined proxy, use "". See also --all-proxy option. This affects all URIs. The format of PROXY is [http://][USER:PASSWORD@]HOST[:PORT].' + }, + + "ftp-proxy-passwd": { + val: "", + desc: "Set password for --ftp-proxy option." + }, + + "ftp-proxy-user": { + val: "", + desc: "Set user for --ftp-proxy option." + }, + + "ftp-reuse-connection": { + desc: "Reuse connection in FTP. Default: true.", + val: true, + options: ["true", "false"] + }, + + "ftp-type": { + desc: "Set FTP transfer type. TYPE is either binary or ascii. Default: binary", + val: "binary", + options: ["binary", "ascii"] + }, + + "ftp-user": { + val: "anonymous", + desc: "Set FTP user. This affects all URIs. Default: anonymous" + }, + + header: { + val: "", + desc: "Append HEADER to HTTP request header.", + multiline: true + }, + + "http-accept-gzip": { + desc: + "Send Accept: deflate, gzip request header and inflate response if remote server responds with Content-Encoding: gzip or Content-Encoding: deflate. Default: false", + val: false, + options: ["true", "false"] + }, + + "http-auth-challenge": { + desc: + "Send HTTP authorization header only when it is requested by the server. If false is set, then authorization header is always sent to the server. There is an exception: if username and password are embedded in URI, authorization header is always sent to the server regardless of this option. Default: false", + val: false, + options: ["true", "false"] + }, + + "http-no-cache": { + desc: + "Send Cache-Control: no-cache and Pragma: no-cache header to avoid cached content. If false is given, these headers are not sent and you can add Cache-Control header with a directive you like using --header option. Default: true", + val: true, + options: ["true", "false"] + }, + + "http-user": { + val: "", + desc: "Set HTTP username." + }, + + "http-passwd": { + val: "", + desc: "Set HTTP password." + }, + + "http-proxy": { + val: "", + desc: + 'Use this proxy server for HTTP. To erase previously defined proxy, use "". See also --all-proxy option. This affects all URIs. The format of PROXY is [http://][USER:PASSWORD@]HOST[:PORT].' + }, + + "http-proxy-passwd": { + val: "", + desc: "Set password for --http-proxy option." + }, + + "http-proxy-user": { + val: "", + desc: "Set user for --http-proxy option." + }, + + "human-readable": { + desc: + "Print sizes and speed in human readable format (e.g., 1.2Ki, 3.4Mi) in the console readout. Default: true", + val: true, + options: ["true", "false"] + }, + + "index-out": { + val: undefined, + desc: + "Set file path for file with index=INDEX. You can find the file index using the --show-files option. PATH is a relative path to the path specified in --dir option. You can use this option multiple times. Using this option, you can specify the output filenames of BitTorrent downloads." + }, + + "lowest-speed-limit": { + val: "0", + desc: + "Close connection if download speed is lower than or equal to this value(bytes per sec). 0 means aria2 does not have a lowest speed limit. You can append K or M (1K = 1024, 1M = 1024K). This option does not affect BitTorrent downloads. Default: 0" + }, + + "max-connection-per-server": { + val: 1, + desc: "The maximum number of connections to one server for each download. Default: 1" + }, + + "max-download-limit": { + val: "0", + desc: + "Set max download speed per each download in bytes/sec. 0 means unrestricted. You can append K or M (1K = 1024, 1M = 1024K). To limit the overall download speed, use --max-overall-download-limit option. Default: 0" + }, + + "max-file-not-found": { + val: 0, + desc: + 'If aria2 receives "file not found" status from the remote HTTP/FTP servers NUM times without getting a single byte, then force the download to fail. Specify 0 to disable this option. This options is effective only when using HTTP/FTP servers. Default: 0' + }, + + "max-resume-failure-tries": { + val: 0, + desc: + "When used with --always-resume=false, aria2 downloads file from scratch when aria2 detects N number of URIs that does not support resume. If N is 0, aria2 downloads file from scratch when all given URIs do not support resume. See --always-resume option. Default: 0" + }, + + "max-tries": { + val: 0, + desc: "Set number of tries. 0 means unlimited. See also --retry-wait. Default: 5" + }, + + "max-upload-limit": { + val: "0", + desc: + "Set max upload speed per each torrent in bytes/sec. 0 means unrestricted. You can append K or M (1K = 1024, 1M = 1024K). To limit the overall upload speed, use --max-overall-upload-limit option. Default: 0" + }, + + "metalink-enable-unique-protocol": { + desc: + "If true is given and several protocols are available for a mirror in a metalink file, aria2 uses one of them. Use --metalink-preferred-protocol option to specify the preference of protocol. Default: true", + val: true, + options: ["true", "false"] + }, + + "metalink-language": { + val: "", + desc: "The language of the file to download." + }, + + "metalink-location": { + val: "", + desc: + "The location of the preferred server. A comma-delimited list of locations is acceptable, for example, jp,us." + }, + + "metalink-os": { + val: "", + desc: "The operating system of the file to download." + }, + + "metalink-version": { + val: "", + desc: "The version of the file to download." + }, + + "min-split-size": { + val: "20M", + desc: + "aria2 does not split less than 2*SIZE byte range. For example, let's consider downloading 20MiB file. If SIZE is 10M, aria2 can split file into 2 range [0-10MiB) and [10MiB-20MiB) and download it using 2 sources(if --split >= 2, of course). If SIZE is 15M, since 2*15M > 20MiB, aria2 does not split file and download it using 1 source. You can append K or M (1K = 1024, 1M = 1024K). Possible Values: 1M -1024M Default: 20M" + }, + + "no-conf": { + desc: "Disable loading aria2.conf file.", + val: false, + options: ["true", "false"] + }, + + "no-file-allocation-limit": { + val: "5M", + desc: + "No file allocation is made for files whose size is smaller than SIZE. You can append K or M (1K = 1024, 1M = 1024K). Default: 5M" + }, + + "no-netrc": { + desc: + "Disables netrc support. netrc support is enabled by default.Note netrc file is only read at the startup if --no-netrc is false. So if --no-netrc is true at the startup, no netrc is available throughout the session. You cannot get netrc enabled even if you change this setting.", + val: true, + options: ["true", "false"] + }, + + "no-proxy": { + val: "", + desc: + "Specify comma separated hostnames, domains and network address with or without CIDR block where proxy should not be used." + }, + + out: { + val: "", + desc: + "The file name of the downloaded file. When --force-sequential option is used, this option is ignored." + }, + + "parameterized-uri": { + desc: + "Enable parameterized URI support. You can specify set of parts: http://{sv1,sv2,sv3}/foo.iso. Also you can specify numeric sequences with step counter: http://host/image[000-100:2].img. A step counter can be omitted. If all URIs do not point to the same file, such as the second example above, -Z option is required. Default: false", + val: false, + options: ["true", "false"] + }, + + "pause-metadata": { + desc: + "Pause downloads created as a result of metadata download. There are 3 types of metadata downloads in aria2: (1) downloading .torrent file. (2) downloading torrent metadata using magnet link. (3) downloading metalink file. These metadata downloads will generate downloads using their metadata. This option pauses these subsequent downloads. This option is effective only when --enable-rpc=true is given. Default: false", + val: false, + options: ["true", "false"] + }, + + "proxy-method": { + desc: + "Set the method to use in proxy request. METHOD is either get or tunnel. HTTPS downloads always use tunnel regardless of this option. Default: get", + val: "get", + options: ["get", "tunnel"] + }, + + quiet: { + desc: "Make aria2 quiet (no console output). Default: false", + val: false, + options: ["true", "false"] + }, + + "realtime-chunk-checksum": { + desc: + "Validate chunk of data by calculating checksum while downloading a file if chunk checksums are provided. Default: true", + val: true, + options: ["true", "false"] + }, + + referer: { + val: "", + desc: "Set Referer. This affects all URIs." + }, + + "remote-time": { + desc: + "Retrieve timestamp of the remote file from the remote HTTP/FTP server and if it is available, apply it to the local file. Default: false", + val: false, + options: ["true", "false"] + }, + + "remove-control-file": { + desc: + "Remove control file before download. Using with --allow-overwrite=true, download always starts from scratch. This will be useful for users behind proxy server which disables resume.", + val: false, + options: ["true", "false"] + }, + + "reuse-uri": { + desc: "Reuse already used URIs if no unused URIs are left. Default: true", + val: true, + options: ["true", "false"] + }, + + "seed-ratio": { + val: 0.0, + desc: + "Specify share ratio. Seed completed torrents until share ratio reaches RATIO. You are strongly encouraged to specify equals or more than 1.0 here. Specify 0.0 if you intend to do seeding regardless of share ratio. If --seed-time option is specified along with this option, seeding ends when at least one of the conditions is satisfied. Default: 1.0" + }, + + "seed-time": { + val: 0, + desc: + "Specify seeding time in minutes. Also see the --seed-ratio option. Note Specifying --seed-time=0 disables seeding after download completed." + }, + + "select-file": { + val: "", + desc: + "Set file to download by specifying its index. You can find the file index using the --show-files option. Multiple indexes can be specified by using ,, for example: 3,6. You can also use - to specify a range: 1-5. , and - can be used together: 1-5,8,9. When used with the -M option, index may vary depending on the query ." + }, + + split: { + val: 5, + desc: + "Download a file using N connections. If more than N URIs are given, first N URIs are used and remaining URIs are used for backup. If less than N URIs are given, those URIs are used more than once so that N connections total are made simultaneously. The number of connections to the same host is restricted by --max-connection-per-server option. See also --min-split-size option. Default: 5" + }, + + timeout: { + val: 60, + desc: "Set timeout in seconds. Default: 60" + }, + + "use-head": { + desc: "Use HEAD method for the first request to the HTTP server. Default: false", + val: false, + options: ["true", "false"] + }, + + "user-agent": { + val: "aria2/$VERSION", + desc: + "Set user agent for HTTP(S) downloads. Default: aria2/$VERSION, $VERSION is replaced by package version." + }, + + "retry-wait": { + val: 0, + desc: + "Set the seconds to wait between retries. With SEC > 0, aria2 will retry download when the HTTP server returns 503 response. Default: 0." + }, + + "metalink-base-uri": { + val: "", + desc: + "Specify base URI to resolve relative URI in metalink:url and metalink:metaurl element in a metalink file stored in local disk. If URI points to a directory, URI must end with /." + }, + + pause: { + desc: + "Pause download after added. This option is effective only when --enable-rpc=true is given. Default: false", + val: "false", + options: ["true", "false"] + }, + + "rpc-allow-origin-all": { + desc: + "Add Access-Control-Allow-Origin header field with value * to the RPC response. Default: false", + val: false, + options: ["true", "false"] + }, + + "rpc-listen-all": { + desc: + "Listen incoming JSON-RPC/XML-RPC requests on all network interfaces. If false is given, listen only on local loopback interface. Default: false", + val: false, + options: ["true", "false"] + }, + + "rpc-secure": { + desc: + "RPC transport will be encrypted by SSL/TLS. The RPC clients must use https scheme to access the server. For WebSocket client, use wss scheme. Use --rpc-certificate and --rpc-private-key options to specify the server certificate and private key.", + val: false, + options: ["true", "false"] + }, + + "stream-piece-selector": { + desc: + "Specify piece selection algorithm used in HTTP/FTP download. Piece means fixed length segment which is downloaded in parallel in segmented download. If default is given, aria2 selects piece so that it reduces the number of establishing connection. This is reasonable default behaviour because establishing connection is an expensive operation. If inorder is given, aria2 selects piece which has minimum index. Index=0 means first of the file. This will be useful to view movie while downloading it. --enable-http-pipelining option may be useful to reduce reconnection overhead. Please note that aria2 honors --min-split-size option, so it will be necessary to specify a reasonable value to --min-split-size option. If geom is given, at the beginning aria2 selects piece which has minimum index like inorder, but it exponentially increasingly keeps space from previously selected piece. This will reduce the number of establishing connection and at the same time it will download the beginning part of the file first. This will be useful to view movie while downloading it. Default: default", + val: "default", + options: ["default", "inorder", "geom"] + }, + + "show-console-readout": { + desc: "Show console readout. Default: true", + val: true, + options: ["true", "false"] + }, + + "show-files": { + desc: + "Print file listing of “.torrent”, “.meta4” and “.metalink” file and exit. In case of “.torrent” file, additional information (infohash, piece length, etc) is also printed.", + val: false, + options: ["true", "false"] + }, + + "truncate-console-readout": { + desc: "Truncate console readout to fit in a single line. Default: true", + val: true, + options: ["true", "false"] + }, + + "hash-check-only": { + desc: + "If true is given, after hash check using --check-integrity option, abort download whether or not download is complete. Default: false", + val: false, + options: ["true", "false"] + }, + + checksum: { + val: undefined, + desc: + "Set checksum. TYPE is hash type. The supported hash type is listed in Hash Algorithms in aria2c -v. DIGEST is hex digest. For example, setting sha-1 digest looks like this: sha-1=0192ba11326fe2298c8cb4de616f4d4140213838 This option applies only to HTTP(S)/FTP downloads." + }, + + "piece-length": { + val: "1M", + desc: + "Set a piece length for HTTP/FTP downloads. This is the boundary when aria2 splits a file. All splits occur at multiple of this length. This option will be ignored in BitTorrent downloads. It will be also ignored if Metalink file contains piece hashes. Default: 1M" + }, + + "uri-selector": { + desc: + "Specify URI selection algorithm. The possible values are inorder, feedback and adaptive. If inorder is given, URI is tried in the order appeared in the URI list. If feedback is given, aria2 uses download speed observed in the previous downloads and choose fastest server in the URI list. This also effectively skips dead mirrors. The observed download speed is a part of performance profile of servers mentioned in --server-stat-of and --server-stat-if options. If adaptive is given, selects one of the best mirrors for the first and reserved connections. For supplementary ones, it returns mirrors which has not been tested yet, and if each of them has already been tested, returns mirrors which has to be tested again. Otherwise, it doesn't select anymore mirrors. Like feedback, it uses a performance profile of servers. Default: feedback", + val: "feedback", + options: ["inorder", "feedback", "adaptive"] + } + //}}} + }) + .value("$globalSettings", { + // {{{ settings (global) + "download-result": { + desc: + "This option changes the way Download Results is formatted. If OPT is default, print GID, status, average download speed and path/URI. If multiple files are involved, path/URI of first requested file is printed and remaining ones are omitted. If OPT is full, print GID, status, average download speed, percentage of progress and path/URI. The percentage of progress and path/URI are printed for each requested file in each row. Default: default", + val: "default", + options: ["default", "full"] + }, + log: { + val: "", + desc: + 'The file name of the log file. If - is specified, log is written to stdout. If empty string("") is specified, log is not written to file.' + }, + "log-level": { + desc: + "Set log level to output. LEVEL is either debug, info, notice, warn or error. Default: debug.", + val: "debug", + options: ["debug", "info", "notice", "warn", "error"] + }, + "max-concurrent-downloads": { + val: 5, + desc: + "Set maximum number of parallel downloads for every static (HTTP/FTP) URI, torrent and metalink. See also --split option. Default: 5" + }, + "max-download-result": { + val: 1000, + desc: + "Set maximum number of download result kept in memory. The download results are completed/error/removed downloads. The download results are stored in FIFO queue and it can store at most NUM download results. When queue is full and new download result is created, oldest download result is removed from the front of the queue and new one is pushed to the back. Setting big number in this option may result high memory consumption after thousands of downloads. Specifying 0 means no download result is kept. Default: 1000" + }, + "max-overall-download-limit": { + val: "0", + desc: + "Set max overall download speed in bytes/sec. 0 means unrestricted. You can append K or M (1K = 1024, 1M = 1024K). To limit the download speed per download, use --max-download-limit option. Default: 0." + }, + "max-overall-upload-limit": { + val: "0", + desc: + "Set max overall upload speed in bytes/sec. 0 means unrestricted. You can append K or M (1K = 1024, 1M = 1024K). To limit the upload speed per torrent, use --max-upload-limit option. Default: 0." + }, + "save-cookies": { + val: "", + desc: + "Save Cookies to FILE in Mozilla/Firefox(1.x/2.x)/ Netscape format. If FILE already exists, it is overwritten. Session Cookies are also saved and their expiry values are treated as 0. Possible Values: /path/to/file." + }, + "save-session": { + val: "", + desc: + "Save error/unfinished downloads to FILE on exit. You can pass this output file to aria2c with --input-file option on restart." + }, + "server-stat-of": { + val: "", + desc: + "Specify the filename to which performance profile of the servers is saved. You can load saved data using --server-stat-if option. See Server Performance Profile subsection below for file format." + } + // }}} + }) + .value("$globalExclude", ["checksum", "index-out", "out", "pause", "select-file"]) + .value("$waitingExclude", [ + "dry-run", + "metalink-base-uri", + "parameterized-uri", + "pause", + "piece-length" + ]) + .value("$activeInclude", [ + "bt-max-peers", + "bt-request-peer-speed-limit", + "bt-remove-unselected-file", + "max-download-limit", + "max-upload-limit" + ]); diff --git a/js/services/utils.js b/js/services/utils.js index e7d81d0d..8c00e1e0 100644 --- a/js/services/utils.js +++ b/js/services/utils.js @@ -1,168 +1,187 @@ -angular.module('webui.services.utils', ['webui.services.configuration']) -.factory('$utils', ['$filter', '$name', '$titlePattern', function(filter, $name, $titlePattern) { - var rnd16 = (function() { - "use strict"; - var rndBuffer = new Uint8Array(16); - var rnd16Weak = function() { - for (var i = 0, r; i < 16; i++) { - if (!(i % 0x3)) r = Math.random() * 0x100000000 | 0; - rndBuffer[i] = r >>> ((i & 0x3) << 0x3) & 0xff; - } - return rndBuffer; - }; - - if (!window.crypto || !crypto.getRandomValues) { - return rnd16Weak; - } - return function() { - try { - crypto.getRandomValues(rndBuffer); +angular.module("webui.services.utils", ["webui.services.configuration"]).factory("$utils", [ + "$filter", + "$name", + "$titlePattern", + function(filter, $name, $titlePattern) { + var rnd16 = (function() { + "use strict"; + var rndBuffer = new Uint8Array(16); + var rnd16Weak = function() { + for (var i = 0, r; i < 16; i++) { + if (!(i % 0x3)) r = (Math.random() * 0x100000000) | 0; + rndBuffer[i] = (r >>> ((i & 0x3) << 0x3)) & 0xff; + } return rndBuffer; - } - catch (ex) { - // Entropy might be exhausted - return rnd16Weak(); - } - }; - })(); - - var utils = { + }; - fmtsize: function(len) { - len = +len; // coerce to number - if (len <= 1024) { - return len.toFixed(0) + " B"; - } - len /= 1024; - if (len <= 1024) { - return len.toFixed(1) + " KB" + if (!window.crypto || !crypto.getRandomValues) { + return rnd16Weak; } - len /= 1024; - if (len <= 1024) { - return len.toFixed(2) + " MB"; - } - len /= 1024; - return len.toFixed(3) + " GB"; - }, + return function() { + try { + crypto.getRandomValues(rndBuffer); + return rndBuffer; + } catch (ex) { + // Entropy might be exhausted + return rnd16Weak(); + } + }; + })(); - fmtspeed: function(speed) { - return utils.fmtsize(speed) + "/s"; - }, - // saves the key value pair in cookies - setCookie: function(key, value) { - var exdate = new Date(); - exdate.setDate(exdate.getDate() + 30 * 12); - var cvalue = escape(JSON.stringify(value)) + "; expires=" + exdate.toUTCString(); - document.cookie = key + "=" + cvalue; - }, - // gets a value for a key stored in cookies - getCookie: function(key) { - var chunks = document.cookie.split(";"); - for (var i = 0; i < chunks.length; i++) { - var ckey = chunks[i].substr(0, chunks[i].indexOf("=")).replace(/^\s+|\s+$/g,""); - var cvalue = chunks[i].substr(chunks[i].indexOf("=") + 1); - if (key == ckey) { - return JSON.parse(unescape(cvalue)); + var utils = { + fmtsize: function(len) { + len = +len; // coerce to number + if (len <= 1024) { + return len.toFixed(0) + " B"; } - } + len /= 1024; + if (len <= 1024) { + return len.toFixed(1) + " KB"; + } + len /= 1024; + if (len <= 1024) { + return len.toFixed(2) + " MB"; + } + len /= 1024; + return len.toFixed(3) + " GB"; + }, - return null; - }, - getFileName: function(path) { - var seed = path.split(/[/\\]/); - return seed[seed.length - 1]; - }, - uuid: (function() { - var bt = []; - for (var i = 0; i < 0x100; ++i) { - bt.push((i + 0x100).toString(16).substr(1)); - } - Object.freeze(bt); + fmtspeed: function(speed) { + return utils.fmtsize(speed) + "/s"; + }, + // saves the key value pair in cookies + setCookie: function(key, value) { + var exdate = new Date(); + exdate.setDate(exdate.getDate() + 30 * 12); + var cvalue = escape(JSON.stringify(value)) + "; expires=" + exdate.toUTCString(); + document.cookie = key + "=" + cvalue; + }, + // gets a value for a key stored in cookies + getCookie: function(key) { + var chunks = document.cookie.split(";"); + for (var i = 0; i < chunks.length; i++) { + var ckey = chunks[i].substr(0, chunks[i].indexOf("=")).replace(/^\s+|\s+$/g, ""); + var cvalue = chunks[i].substr(chunks[i].indexOf("=") + 1); + if (key == ckey) { + return JSON.parse(unescape(cvalue)); + } + } - return function() { - var r = rnd16(); - r[6] = (r[6] & 0xf) | 0x40; // Version 4 - r[8] = (r[8] & 0x3f) | 0x80; // Version 4y - return bt[r[0]] + bt[r[1]] + bt[r[2]] + bt[r[3]] + "-" + - bt[r[4]] + bt[r[5]] + "-" + - bt[r[6]] + bt[r[7]] + "-" + - bt[r[8]] + bt[r[9]] + "-" + - bt[r[10]] + bt[r[11]] + bt[r[12]] + bt[r[13]] + bt[r[14]] + bt[r[15]]; - }; - })(), - randStr: function() { - return utils.uuid(); - }, + return null; + }, + getFileName: function(path) { + var seed = path.split(/[/\\]/); + return seed[seed.length - 1]; + }, + uuid: (function() { + var bt = []; + for (var i = 0; i < 0x100; ++i) { + bt.push((i + 0x100).toString(16).substr(1)); + } + Object.freeze(bt); - // maps the array in place to the destination - // arr, dest (optional): array - // func: a merge mapping func, see ctrls/download.js - mergeMap: function(arr, dest, func) { - if (!dest) { - dest = []; - } + return function() { + var r = rnd16(); + r[6] = (r[6] & 0xf) | 0x40; // Version 4 + r[8] = (r[8] & 0x3f) | 0x80; // Version 4y + return ( + bt[r[0]] + + bt[r[1]] + + bt[r[2]] + + bt[r[3]] + + "-" + + bt[r[4]] + + bt[r[5]] + + "-" + + bt[r[6]] + + bt[r[7]] + + "-" + + bt[r[8]] + + bt[r[9]] + + "-" + + bt[r[10]] + + bt[r[11]] + + bt[r[12]] + + bt[r[13]] + + bt[r[14]] + + bt[r[15]] + ); + }; + })(), + randStr: function() { + return utils.uuid(); + }, - for (var i = 0, e = Math.min(arr.length, dest.length); i < e; ++i) { - func(arr[i], dest[i]); - } + // maps the array in place to the destination + // arr, dest (optional): array + // func: a merge mapping func, see ctrls/download.js + mergeMap: function(arr, dest, func) { + if (!dest) { + dest = []; + } - // Insert newly created downloads - while (i < arr.length) { - dest.push(func(arr[i++])); - } + for (var i = 0, e = Math.min(arr.length, dest.length); i < e; ++i) { + func(arr[i], dest[i]); + } - // Truncate if necessary. - dest.length = arr.length; + // Insert newly created downloads + while (i < arr.length) { + dest.push(func(arr[i++])); + } + + // Truncate if necessary. + dest.length = arr.length; - return dest; - }, - // get info title from global statistics - getTitle: function(stats) { - if(!stats) { - stats = {}; + return dest; + }, + // get info title from global statistics + getTitle: function(stats) { + if (!stats) { + stats = {}; } return $titlePattern - .replace('{active}', stats.numActive || '⌛') - .replace('{waiting}', stats.numWaiting || '⌛') - .replace('{download_speed}', utils.fmtspeed(stats.downloadSpeed) || '⌛') - .replace('{upload_speed}', utils.fmtspeed(stats.uploadSpeed) || '⌛') - .replace('{stopped}', stats.numStopped || '⌛') - .replace('{name}', $name); - }, + .replace("{active}", stats.numActive || "⌛") + .replace("{waiting}", stats.numWaiting || "⌛") + .replace("{download_speed}", utils.fmtspeed(stats.downloadSpeed) || "⌛") + .replace("{upload_speed}", utils.fmtspeed(stats.uploadSpeed) || "⌛") + .replace("{stopped}", stats.numStopped || "⌛") + .replace("{name}", $name); + }, - // get download chunks from aria2 bitfield - getChunksFromHex: function(bitfield, numOfPieces) { - var chunks = [], len = 0, numPieces = parseInt(numOfPieces); - if (!bitfield) return []; + // get download chunks from aria2 bitfield + getChunksFromHex: function(bitfield, numOfPieces) { + var chunks = [], + len = 0, + numPieces = parseInt(numOfPieces); + if (!bitfield) return []; - var totalDownloaded = 0; - if (numPieces > 1) { - var chunk_ratio = 1 / numPieces; - var piecesProcessed = 0; - for (var i = 0; i < bitfield.length; i++) { - var hex = parseInt(bitfield[i], 16); - for (var j = 1; j <= 4; j++) { - var bit = hex & (1 << (4 - j)); - if (bit) totalDownloaded++; - var prog = !!bit; - if (len >= 1 && chunks[len - 1].show == prog) { - chunks[len - 1].ratio += chunk_ratio; + var totalDownloaded = 0; + if (numPieces > 1) { + var chunk_ratio = 1 / numPieces; + var piecesProcessed = 0; + for (var i = 0; i < bitfield.length; i++) { + var hex = parseInt(bitfield[i], 16); + for (var j = 1; j <= 4; j++) { + var bit = hex & (1 << (4 - j)); + if (bit) totalDownloaded++; + var prog = !!bit; + if (len >= 1 && chunks[len - 1].show == prog) { + chunks[len - 1].ratio += chunk_ratio; + } else { + chunks.push({ + ratio: chunk_ratio, + show: prog + }); + len++; + } + piecesProcessed++; + if (piecesProcessed == numPieces) return chunks; } - else { - chunks.push({ - ratio: chunk_ratio, - show: prog - }); - len++; - } - piecesProcessed++; - if (piecesProcessed == numPieces) - return chunks; } } + return chunks; } - return chunks; - } - }; - return utils; -}]); + }; + return utils; + } +]); diff --git a/js/translate/cs_CZ.js b/js/translate/cs_CZ.js index f3e09b4d..46cc40d5 100644 --- a/js/translate/cs_CZ.js +++ b/js/translate/cs_CZ.js @@ -1,154 +1,163 @@ -if(typeof translations == 'undefined'){ - translations = {}; +if (typeof translations == "undefined") { + translations = {}; } translations.cs_CZ = { -// header - 'Search': 'Hledat', - // Nav menu - 'Add': 'Přidat', - 'By URIs': 'Z URI', - 'By Torrents': 'Z torrentu', - 'By Metalinks': 'Z metalinku', - 'Manage': 'Spravovat', - 'Pause All': 'Zastavit vše', - 'Resume Paused': 'Obnovit zastavené', - 'Purge Completed': 'Odstranit hotové', - 'Shutdown Server': 'Vypnout server', - 'Settings': 'Nastavení', - 'Connection Settings': 'Nastavení připojení', - 'Global Settings': 'Obecné nastavení', - 'Server info': 'Informace o serveru', - 'About and contribute': 'Informace', - 'Toggle navigation': 'Přepnout ovládání', -// body -// nav side bar - 'Miscellaneous': 'Různé', - 'Global Statistics': 'Globální statistika', - 'About': 'Informace', - 'Displaying': 'Zobrazuji', - 'of': 'z', - 'downloads': 'stahování', - 'Language': 'Jazyk', -// download filters - 'Download Filters': 'Filtry stahování', - 'Running': 'Stahují se', - 'Active': 'Aktivní', - 'Waiting': 'Čekající', - 'Complete': 'Hotové', - 'Error': 'Chyba', - 'Paused': 'Zastavené', - 'Removed': 'Odstraněné', - 'Hide linked meta-data': 'Skrýt připojená meta-data', - 'Toggle': 'Prohodit', - 'Reset filters': 'Smazat filtry', -// download status - 'Verifing': 'Ověřování', - 'Verify Pending': 'Čekání na ověření', -// starred properties - 'Quick Access Settings': 'Rychlé nastavení', - 'Save': 'Uložit', - 'Save settings': 'Uložit nastavení', - 'Currently no download in line to display, use the': 'Není co zobrazit, použijte', - 'download button to start downloading files!': 'tlačítko pro stáhnutí souborů!', - 'Peers': 'Zdroje', - 'More Info': 'Víc informací', - 'Remove': 'Odstranit', - '# of': '# z', - 'Length': 'Délka', -// modals - 'Add Downloads By URIs': 'Přidat stahování z URI', - '- You can add multiple downloads (files) at the same time by putting URIs for each file on a separate line.': - '- Můžete začít stahovat více souborů v jeden okamžik, tak že na každý řádek dáte jinou URI', - '- You can also add multiple URIs (mirrors) for the *same* file. To do this, separate the URIs by a space.': - '- Také můžete přidat více URI (Zrcadel) pro *stejný* soubor, tak že je dáte na jeden řádek oddělené mezerou ', - '- A URI can be HTTP(S)/FTP/BitTorrent-Magnet.': '- URI může být HTTP(S)/FTP/BitTorrent-Magnet.', - 'Download settings': 'Nastavení stahování', - 'Advanced settings': 'Pokročilé nastavení', - 'Cancel': 'Zrušit', - 'Start': 'Spustit', - 'Choose': 'Zvolit', - 'Quick Access (shown on the main page)': 'Rychlý přístup (Zobrazení na hlavní stránce)', -// add torrent modal - 'Add Downloads By Torrents': 'Přidat stahování z torrentu', - '- Select the torrent from the local filesystem to start the download.': '- Pro stahování vyberte torrent soubor z disku', - '- You can select multiple torrents to start multiple downloads.': ' - Můžete zvolit víc torrentů pro spuštění více stahování', - '- To add a BitTorrent-Magnet URL, use the Add By URI option and add it there.': '- Pro stahování pomocí BitTorrent-Magnet URL, použijte možnost \"Z URI\"', - 'Select Torrents': 'Vyberte torrenty', - 'Select a Torrent': 'Vyberte torrent', -// add metalink modal - 'Add Downloads By Metalinks': 'Přidat stahovní pomocí metalinku', - 'Select Metalinks': 'Výběr metalinků', - '- Select the Metalink from the local filesystem to start the download.': '- Pro stahování vyberte metalink soubor z disku', - '- You can select multiple Metalinks to start multiple downloads.': '- Můžete zvolit víc mentalinků pro spuštění více stahování', - 'Select a Metalink': 'Vyberte metalink', -// select file modal - 'Choose files to start download for': 'Vyberte soubory pro stažení', - 'Select to download': 'Vyberte ke stažení', -// settings modal - 'Aria2 RPC host and port': 'Aria2 RPC host a port', - 'Enter the host': 'Zadejte hosta', - 'Enter the IP or DNS name of the server on which the RPC for Aria2 is running (default: localhost)': - 'Zadejte IP nebo DNS jméno serveru na kterém běží Aria2 RPC (výchozí: localhost)', - 'Enter the port': 'Zadejte port', - 'Enter the port of the server on which the RPC for Aria2 is running (default: 6800)': - 'Zadejte port serveru na kterém běží Aria2 RPC (výchozí: 6800)', - 'Enter the RPC path': 'Zadejte cestu k RPC', - 'Enter the path for the Aria2 RPC endpoint (default: /jsonrpc)': 'Zadejte cestu k endpointu Aria2 RPC (výchozí: /jsonrpc)', - 'SSL/TLS encryption': 'SSL/TLS šifrování', - 'Enable SSL/TLS encryption': 'Zapnout SSL/TLS šifrování', - 'Enter the secret token (optional)': 'Zadejte bezpečnostní token (volitelné)', - 'Enter the Aria2 RPC secret token (leave empty if authentication is not enabled)': - 'Zadejte bezpečnostní token k Aria2 RPC (nechte prázné pokud autentifikace není nastavena)', - 'Enter the username (optional)': 'Zadejte uživatelské jméno (volitelné)', - 'Enter the Aria2 RPC username (empty if authentication not enabled)': - 'Zadejte uživatelské jméno pro Aria2 RPC (nechte prázné pokud autentifikace není nastavena)', - 'Enter the password (optional)': 'Zadejte heslo (volitelné)', - 'Enter the Aria2 RPC password (empty if authentication not enabled)': 'Zadej heslo k Aria2 RPC (nechte prázné pokud autentifikace není nastavena)', - 'Enter base URL (optional)': 'Zadejte kořenovou URL serveru (volitelné)', - 'Direct Download': 'Přímé stažení', - 'If supplied, links will be created to enable direct download from the Aria2 server.': - 'Jestliže je nastaveno, je možné stáhnout soubor přímo z Aria2 serveru.', - '(Requires appropriate webserver to be configured.)': '(Je třeba udělat patřičnou konfiguraci webserveru)', - 'Save Connection configuration': 'Uložit nastavení', - 'Filter': 'Filtr', -// server info modal - 'Aria2 server info': 'Informace o Aria2 serveru', - 'Aria2 Version': 'Verze Aria2', - 'Features Enabled': 'Zapnuté funkce', -// about modal - 'To download the latest version of the project, add issues or to contribute back, head on to': - 'Ke stažení aktuální verze, nahlášení problému či přispění, zamiřte na', - 'Or you can open the latest version in the browser through': 'Nebo můžete spustit aktuální verzi pomocí:', - 'Close': 'Zavřít', -// labels - 'Download status':'Stav stahování', - 'Download Speed':'Rychlost stahování', - 'Upload Speed':'Rychlost nahrávání', - 'Estimated time':'Odhadovaný čas', - 'Download Size':'Velikost', - 'Downloaded':'Staženo', - 'Progress':'Průběh', - 'Download Path':'Cesta', - 'Uploaded':'Nahráno', - 'Download GID':'GID', - 'Number of Pieces':'Počet fragmentů', - 'Piece Length':'Délka fragmentu', + // header + Search: "Hledat", + // Nav menu + Add: "Přidat", + "By URIs": "Z URI", + "By Torrents": "Z torrentu", + "By Metalinks": "Z metalinku", + Manage: "Spravovat", + "Pause All": "Zastavit vše", + "Resume Paused": "Obnovit zastavené", + "Purge Completed": "Odstranit hotové", + "Shutdown Server": "Vypnout server", + Settings: "Nastavení", + "Connection Settings": "Nastavení připojení", + "Global Settings": "Obecné nastavení", + "Server info": "Informace o serveru", + "About and contribute": "Informace", + "Toggle navigation": "Přepnout ovládání", + // body + // nav side bar + Miscellaneous: "Různé", + "Global Statistics": "Globální statistika", + About: "Informace", + Displaying: "Zobrazuji", + of: "z", + downloads: "stahování", + Language: "Jazyk", + // download filters + "Download Filters": "Filtry stahování", + Running: "Stahují se", + Active: "Aktivní", + Waiting: "Čekající", + Complete: "Hotové", + Error: "Chyba", + Paused: "Zastavené", + Removed: "Odstraněné", + "Hide linked meta-data": "Skrýt připojená meta-data", + Toggle: "Prohodit", + "Reset filters": "Smazat filtry", + // download status + Verifing: "Ověřování", + "Verify Pending": "Čekání na ověření", + // starred properties + "Quick Access Settings": "Rychlé nastavení", + Save: "Uložit", + "Save settings": "Uložit nastavení", + "Currently no download in line to display, use the": "Není co zobrazit, použijte", + "download button to start downloading files!": "tlačítko pro stáhnutí souborů!", + Peers: "Zdroje", + "More Info": "Víc informací", + Remove: "Odstranit", + "# of": "# z", + Length: "Délka", + // modals + "Add Downloads By URIs": "Přidat stahování z URI", + "- You can add multiple downloads (files) at the same time by putting URIs for each file on a separate line.": + "- Můžete začít stahovat více souborů v jeden okamžik, tak že na každý řádek dáte jinou URI", + "- You can also add multiple URIs (mirrors) for the *same* file. To do this, separate the URIs by a space.": + "- Také můžete přidat více URI (Zrcadel) pro *stejný* soubor, tak že je dáte na jeden řádek oddělené mezerou ", + "- A URI can be HTTP(S)/FTP/BitTorrent-Magnet.": "- URI může být HTTP(S)/FTP/BitTorrent-Magnet.", + "Download settings": "Nastavení stahování", + "Advanced settings": "Pokročilé nastavení", + Cancel: "Zrušit", + Start: "Spustit", + Choose: "Zvolit", + "Quick Access (shown on the main page)": "Rychlý přístup (Zobrazení na hlavní stránce)", + // add torrent modal + "Add Downloads By Torrents": "Přidat stahování z torrentu", + "- Select the torrent from the local filesystem to start the download.": + "- Pro stahování vyberte torrent soubor z disku", + "- You can select multiple torrents to start multiple downloads.": + " - Můžete zvolit víc torrentů pro spuštění více stahování", + "- To add a BitTorrent-Magnet URL, use the Add By URI option and add it there.": + '- Pro stahování pomocí BitTorrent-Magnet URL, použijte možnost "Z URI"', + "Select Torrents": "Vyberte torrenty", + "Select a Torrent": "Vyberte torrent", + // add metalink modal + "Add Downloads By Metalinks": "Přidat stahovní pomocí metalinku", + "Select Metalinks": "Výběr metalinků", + "- Select the Metalink from the local filesystem to start the download.": + "- Pro stahování vyberte metalink soubor z disku", + "- You can select multiple Metalinks to start multiple downloads.": + "- Můžete zvolit víc mentalinků pro spuštění více stahování", + "Select a Metalink": "Vyberte metalink", + // select file modal + "Choose files to start download for": "Vyberte soubory pro stažení", + "Select to download": "Vyberte ke stažení", + // settings modal + "Aria2 RPC host and port": "Aria2 RPC host a port", + "Enter the host": "Zadejte hosta", + "Enter the IP or DNS name of the server on which the RPC for Aria2 is running (default: localhost)": + "Zadejte IP nebo DNS jméno serveru na kterém běží Aria2 RPC (výchozí: localhost)", + "Enter the port": "Zadejte port", + "Enter the port of the server on which the RPC for Aria2 is running (default: 6800)": + "Zadejte port serveru na kterém běží Aria2 RPC (výchozí: 6800)", + "Enter the RPC path": "Zadejte cestu k RPC", + "Enter the path for the Aria2 RPC endpoint (default: /jsonrpc)": + "Zadejte cestu k endpointu Aria2 RPC (výchozí: /jsonrpc)", + "SSL/TLS encryption": "SSL/TLS šifrování", + "Enable SSL/TLS encryption": "Zapnout SSL/TLS šifrování", + "Enter the secret token (optional)": "Zadejte bezpečnostní token (volitelné)", + "Enter the Aria2 RPC secret token (leave empty if authentication is not enabled)": + "Zadejte bezpečnostní token k Aria2 RPC (nechte prázné pokud autentifikace není nastavena)", + "Enter the username (optional)": "Zadejte uživatelské jméno (volitelné)", + "Enter the Aria2 RPC username (empty if authentication not enabled)": + "Zadejte uživatelské jméno pro Aria2 RPC (nechte prázné pokud autentifikace není nastavena)", + "Enter the password (optional)": "Zadejte heslo (volitelné)", + "Enter the Aria2 RPC password (empty if authentication not enabled)": + "Zadej heslo k Aria2 RPC (nechte prázné pokud autentifikace není nastavena)", + "Enter base URL (optional)": "Zadejte kořenovou URL serveru (volitelné)", + "Direct Download": "Přímé stažení", + "If supplied, links will be created to enable direct download from the Aria2 server.": + "Jestliže je nastaveno, je možné stáhnout soubor přímo z Aria2 serveru.", + "(Requires appropriate webserver to be configured.)": + "(Je třeba udělat patřičnou konfiguraci webserveru)", + "Save Connection configuration": "Uložit nastavení", + Filter: "Filtr", + // server info modal + "Aria2 server info": "Informace o Aria2 serveru", + "Aria2 Version": "Verze Aria2", + "Features Enabled": "Zapnuté funkce", + // about modal + "To download the latest version of the project, add issues or to contribute back, head on to": + "Ke stažení aktuální verze, nahlášení problému či přispění, zamiřte na", + "Or you can open the latest version in the browser through": + "Nebo můžete spustit aktuální verzi pomocí:", + Close: "Zavřít", + // labels + "Download status": "Stav stahování", + "Download Speed": "Rychlost stahování", + "Upload Speed": "Rychlost nahrávání", + "Estimated time": "Odhadovaný čas", + "Download Size": "Velikost", + Downloaded: "Staženo", + Progress: "Průběh", + "Download Path": "Cesta", + Uploaded: "Nahráno", + "Download GID": "GID", + "Number of Pieces": "Počet fragmentů", + "Piece Length": "Délka fragmentu", -//alerts - 'The last connection attempt was unsuccessful. Trying another configuration': - 'Poslední pokus o připojení se nezdařil. Zkuste jiné nastavení', - 'Oh Snap!': 'A sakra!', - 'Could not connect to the aria2 RPC server. Will retry in 10 secs. You might want to check the connection settings by going to Settings > Connection Settings': - 'Nemohu se připojit k Aria2 RPC serveru. Zkusím to znovu za 10 sekund. Možná by se to chtělo podívat do Nastavení > Nastavení připojení', - 'Authentication failed while connecting to Aria2 RPC server. Will retry in 10 secs. You might want to confirm your authentication details by going to Settings > Connection Settings': - 'Během připojování k Aria2 RPC serveru selhala autentifikace. Zkusím to znovu za 10 sekund. Možná by se to chtělo podívat do Nastavení > Nastavení připojení', - 'Successfully connected to Aria2 through its remote RPC …': - 'Úspěšně připojeno k Aria2 pomocí RPC...', - 'Successfully connected to Aria2 through remote RPC, however the connection is still insecure. For complete security try adding an authorization secret token while starting Aria2 (through the flag --rpc-secret)': - 'Úspěšně připojeno k Aria2 pomocí RPC, ale připojení není zabezpečené. Pro úplné zabezpečení přidejte bezpečnostní token při spuštění Aria2 (pomocí možnosti --rpc-secret) ', - 'Trying to connect to aria2 using the new connection configuration': - 'Zkouším se připojit k Aria2 za pomocí nového nastavení', - 'Remove {{name}} and associated meta-data?': // {{name}} refers to the download name, do not modify. - 'Odstranit {{name}} a příslušná meta-data?' + //alerts + "The last connection attempt was unsuccessful. Trying another configuration": + "Poslední pokus o připojení se nezdařil. Zkuste jiné nastavení", + "Oh Snap!": "A sakra!", + "Could not connect to the aria2 RPC server. Will retry in 10 secs. You might want to check the connection settings by going to Settings > Connection Settings": + "Nemohu se připojit k Aria2 RPC serveru. Zkusím to znovu za 10 sekund. Možná by se to chtělo podívat do Nastavení > Nastavení připojení", + "Authentication failed while connecting to Aria2 RPC server. Will retry in 10 secs. You might want to confirm your authentication details by going to Settings > Connection Settings": + "Během připojování k Aria2 RPC serveru selhala autentifikace. Zkusím to znovu za 10 sekund. Možná by se to chtělo podívat do Nastavení > Nastavení připojení", + "Successfully connected to Aria2 through its remote RPC …": + "Úspěšně připojeno k Aria2 pomocí RPC...", + "Successfully connected to Aria2 through remote RPC, however the connection is still insecure. For complete security try adding an authorization secret token while starting Aria2 (through the flag --rpc-secret)": + "Úspěšně připojeno k Aria2 pomocí RPC, ale připojení není zabezpečené. Pro úplné zabezpečení přidejte bezpečnostní token při spuštění Aria2 (pomocí možnosti --rpc-secret) ", + "Trying to connect to aria2 using the new connection configuration": + "Zkouším se připojit k Aria2 za pomocí nového nastavení", + // {{name}} refers to the download name, do not modify. + "Remove {{name}} and associated meta-data?": "Odstranit {{name}} a příslušná meta-data?" }; diff --git a/js/translate/de_DE.js b/js/translate/de_DE.js index 88ffdf81..40db3d58 100644 --- a/js/translate/de_DE.js +++ b/js/translate/de_DE.js @@ -1,132 +1,144 @@ -if(typeof translations == 'undefined'){ - translations = {}; +if (typeof translations == "undefined") { + translations = {}; } translations.de_DE = { -// header - 'Search': 'Suche', - // Nav menu - 'Add': 'Hinzufügen', - 'By URIs': 'mit URIs', - 'By Torrents': 'mit Torrents', - 'By Metalinks': 'mit Metalinks', - 'Manage': 'Verwalten', - 'Pause All': 'Alle anhalten', - 'Resume Paused': 'Angehaltene fortsetzen', - 'Purge Completed': 'Fertige entfernen', - 'Settings': 'Einstellungen', - 'Connection Settings': 'Verbindungseinstellungen', - 'Global Settings': 'Globale Einstellungen', - 'Server info': 'Server Information', - 'About and contribute': 'Über webui-aria2', - 'Toggle navigation': 'Navigation an/ausschalten', -// body -// nav side bar - 'Miscellaneous': 'Verschiedenes', - 'Global Statistics': 'Globale Statistiken', - 'About': 'Über', - 'Displaying': 'Anzeige', - 'of': 'von', - 'downloads': 'Downloads', - 'Language': 'Sprache', -// download filters - 'Download Filters': 'Download Filter', - 'Running': 'Laufende', - 'Active': 'Aktive', - 'Waiting': 'Wartende', - 'Complete': 'Fertige', - 'Error': 'Fehler', - 'Paused': 'Angehaltene', - 'Removed': 'Gelöschte', - 'Hide linked meta-data': 'Blende verlinkte Meta-Daten aus', - 'Toggle': 'Umschalten', - 'Reset filters': 'Filter zurücksetzen', -// starred properties - 'Quick Access Settings': 'Ausgewählte Einstellungen', - 'Save settings': 'Einstellungen speichern', - 'Currently no download in line to display, use the': 'Aktuell sind keine Downloads vorhanden, bitte benutz den', - 'download button to start downloading files!': 'Download Link um den Download von Dateien zu beginnen!', - 'Peers': 'Peers', - 'More Info': 'Mehr Infos', - 'Remove': 'Entfernen', - '# of': '# von', - 'Length': 'Länge', -// modals - 'Add Downloads By URIs': 'Downloads anhand von URIs hinzufügen', - '- You can add multiple downloads (files) at the same time by putting URIs for each file on a separate line.': - '- Es können mehrere Downloads (Dateien) gleichzeitig hinzugefügt werden, indem jede URI in eine separate Zeile eingegeben wird.', - '- You can also add multiple URIs (mirrors) for the *same* file. To do this, separate the URIs by a space.': - '- Es können auch mehrere URIs (Spiegelserver) für *dieselbe* Datei durch Leerzeichen getrennt angegeben werden.', - '- A URI can be HTTP(S)/FTP/BitTorrent-Magnet.': '- Eine URI kann folgende Protokolle besitzen: HTTP(S)/FTP/BitTorrent-Magnet.', - 'Download settings': 'Download Einstellungen', - 'Advanced settings': 'Erweiterte Einstellungen', - 'Cancel': 'Abbrechen', - 'Start': 'Beginnen', - 'Choose': 'Auswählen', - 'Quick Access (shown on the main page)': 'Schnellzugriff (Anzeige auf der Hauptseite)', -// add torrent modal - 'Add Downloads By Torrents': 'Downloads mit Torrents hinzufügen', - '- Select the torrent from the local filesystem to start the download.': '- Wähle ein Torrent vom lokalen Dateisystem um den Download zu starten', - '- You can select multiple torrents to start multiple downloads.': '- Es können mehrere Torrents ausgewählt werden um mehrere Downloads zu starten', - '- To add a BitTorrent-Magnet URL, use the Add By URI option and add it there.': '- Für BitTorrent-Magnet URLs benutz die Option \'Mit URIs hinzufügen\'', - 'Select Torrents': 'Wähle Torrents', - 'Select a Torrent': 'Wähle ein Torrent', -// add metalink modal - 'Add Downloads By Metalinks': 'Download mit Metalinks hinzufügen', - 'Select Metalinks': 'Wähle Metalinks', - '- Select the Metalink from the local filesystem to start the download.': '- Wähle ein Metalink vom lokalen Dateisystem um den Download zu starten', - '- You can select multiple Metalinks to start multiple downloads.': '- Es können mehrere Metalinks ausgewählt werden um mehrere Downloads zu starten', - 'Select a Metalink': 'Wähle einen Metalink', -// select file modal - 'Choose files to start download for': 'Wähle Dateien für den Download aus', - 'Select to download': 'Wähle zum Download', -// settings modal - 'Aria2 RPC host and port': 'Aria2 RPC host und port', - 'Enter the host': 'Host', - 'Enter the IP or DNS name of the server on which the RPC for Aria2 is running (default: localhost)': - 'Gib die IP oder den DNS Namen des Servers ein, auf dem Aria2 läuft und mit dem du eine RPC-Verbindung etablieren willst (Standard: localhost)', - 'Enter the port': 'Port', - 'Enter the port of the server on which the RPC for Aria2 is running (default: 6800)': - 'Gib den Port des Servers ein, auf dem der RPC-Dienst von Aria2 läuft (Standard: 6800)', - 'Enter the RPC path': 'RPC Pfad', - 'Enter the path for the Aria2 RPC endpoint (default: /jsonrpc)': 'Gib den Pfad zum Aria2 RPC Endpunkt an (Standard: /jsonrpc)', - 'SSL/TLS encryption': 'SSL/TLS', - 'Enable SSL/TLS encryption': 'Aktiviere SSL/TLS Verschlüsselung', - 'Enter the secret token (optional)': 'Secret Token (optional)', - 'Enter the Aria2 RPC secret token (leave empty if authentication is not enabled)': - 'Gib den Aria2 RPC secret Token ein (leer lassen falls keine Authentifizierung aktiv)', - 'Enter the username (optional)': 'Benutzername (optional)', - 'Enter the Aria2 RPC username (empty if authentication not enabled)': - 'Gib den Aria2 RPC Benutzernamen ein (leer lassen falls keine Authentifizierung aktiv)', - 'Enter the password (optional)': 'Passwort (optional)', - 'Enter the Aria2 RPC password (empty if authentication not enabled)': 'Gib das Aria2 RPC Passwort ein (leer lassen falls keine Authentifizierung aktiv)', - 'Enter base URL (optional)': 'Base URL (optional)', - 'Direct Download': 'Direkter Download', - 'If supplied, links will be created to enable direct download from the Aria2 server.': - 'Falls angegeben, werden Links erstellt um einen direkten Download vom Aria2 Server zu ermöglichen', - '(Requires appropriate webserver to be configured.)': '(Es wird ein entsprechend konfigurierter WebServer benötigt.)', - 'Save Connection configuration': 'Speichern der Verbindungseinstellung', - 'Filter': 'Filter', -// server info modal - 'Aria2 server info': 'Aria2 Server Info', - 'Aria2 Version': 'Aria2 Version', - 'Features Enabled': 'Aktive Funktionen', -// about modal - 'To download the latest version of the project, add issues or to contribute back, head on to': - 'Um die neuste Version des Projects zu laden, Fehler zu melden oder sich zu beteiligen, besuch', - 'Or you can open the latest version in the browser through': 'Oder du kannst die neueste Version direkt in deinem Browser verwenden', - 'Close': 'Schließen', -// lables - 'Download status':'Download Status', - 'Download Speed':'Download Geschwindigkeit', - 'Upload Speed':'Upload Geschwindigkeit', - 'Estimated time':'Geschätzte Zeit', - 'Download Size':'Download Größe', - 'Downloaded':'Heruntergeladen', - 'Progress':'Fortschritt', - 'Download Path':'Download Pfad', - 'Uploaded':'Hochgeladen', - 'Download GID':'Download GID', - 'Number of Pieces':'Anzahl der Stücken', - 'Piece Length':'Größe der Stücken' + // header + Search: "Suche", + // Nav menu + Add: "Hinzufügen", + "By URIs": "mit URIs", + "By Torrents": "mit Torrents", + "By Metalinks": "mit Metalinks", + Manage: "Verwalten", + "Pause All": "Alle anhalten", + "Resume Paused": "Angehaltene fortsetzen", + "Purge Completed": "Fertige entfernen", + Settings: "Einstellungen", + "Connection Settings": "Verbindungseinstellungen", + "Global Settings": "Globale Einstellungen", + "Server info": "Server Information", + "About and contribute": "Über webui-aria2", + "Toggle navigation": "Navigation an/ausschalten", + // body + // nav side bar + Miscellaneous: "Verschiedenes", + "Global Statistics": "Globale Statistiken", + About: "Über", + Displaying: "Anzeige", + of: "von", + downloads: "Downloads", + Language: "Sprache", + // download filters + "Download Filters": "Download Filter", + Running: "Laufende", + Active: "Aktive", + Waiting: "Wartende", + Complete: "Fertige", + Error: "Fehler", + Paused: "Angehaltene", + Removed: "Gelöschte", + "Hide linked meta-data": "Blende verlinkte Meta-Daten aus", + Toggle: "Umschalten", + "Reset filters": "Filter zurücksetzen", + // starred properties + "Quick Access Settings": "Ausgewählte Einstellungen", + "Save settings": "Einstellungen speichern", + "Currently no download in line to display, use the": + "Aktuell sind keine Downloads vorhanden, bitte benutz den", + "download button to start downloading files!": + "Download Link um den Download von Dateien zu beginnen!", + Peers: "Peers", + "More Info": "Mehr Infos", + Remove: "Entfernen", + "# of": "# von", + Length: "Länge", + // modals + "Add Downloads By URIs": "Downloads anhand von URIs hinzufügen", + "- You can add multiple downloads (files) at the same time by putting URIs for each file on a separate line.": + "- Es können mehrere Downloads (Dateien) gleichzeitig hinzugefügt werden, indem jede URI in eine separate Zeile eingegeben wird.", + "- You can also add multiple URIs (mirrors) for the *same* file. To do this, separate the URIs by a space.": + "- Es können auch mehrere URIs (Spiegelserver) für *dieselbe* Datei durch Leerzeichen getrennt angegeben werden.", + "- A URI can be HTTP(S)/FTP/BitTorrent-Magnet.": + "- Eine URI kann folgende Protokolle besitzen: HTTP(S)/FTP/BitTorrent-Magnet.", + "Download settings": "Download Einstellungen", + "Advanced settings": "Erweiterte Einstellungen", + Cancel: "Abbrechen", + Start: "Beginnen", + Choose: "Auswählen", + "Quick Access (shown on the main page)": "Schnellzugriff (Anzeige auf der Hauptseite)", + // add torrent modal + "Add Downloads By Torrents": "Downloads mit Torrents hinzufügen", + "- Select the torrent from the local filesystem to start the download.": + "- Wähle ein Torrent vom lokalen Dateisystem um den Download zu starten", + "- You can select multiple torrents to start multiple downloads.": + "- Es können mehrere Torrents ausgewählt werden um mehrere Downloads zu starten", + "- To add a BitTorrent-Magnet URL, use the Add By URI option and add it there.": + "- Für BitTorrent-Magnet URLs benutz die Option 'Mit URIs hinzufügen'", + "Select Torrents": "Wähle Torrents", + "Select a Torrent": "Wähle ein Torrent", + // add metalink modal + "Add Downloads By Metalinks": "Download mit Metalinks hinzufügen", + "Select Metalinks": "Wähle Metalinks", + "- Select the Metalink from the local filesystem to start the download.": + "- Wähle ein Metalink vom lokalen Dateisystem um den Download zu starten", + "- You can select multiple Metalinks to start multiple downloads.": + "- Es können mehrere Metalinks ausgewählt werden um mehrere Downloads zu starten", + "Select a Metalink": "Wähle einen Metalink", + // select file modal + "Choose files to start download for": "Wähle Dateien für den Download aus", + "Select to download": "Wähle zum Download", + // settings modal + "Aria2 RPC host and port": "Aria2 RPC host und port", + "Enter the host": "Host", + "Enter the IP or DNS name of the server on which the RPC for Aria2 is running (default: localhost)": + "Gib die IP oder den DNS Namen des Servers ein, auf dem Aria2 läuft und mit dem du eine RPC-Verbindung etablieren willst (Standard: localhost)", + "Enter the port": "Port", + "Enter the port of the server on which the RPC for Aria2 is running (default: 6800)": + "Gib den Port des Servers ein, auf dem der RPC-Dienst von Aria2 läuft (Standard: 6800)", + "Enter the RPC path": "RPC Pfad", + "Enter the path for the Aria2 RPC endpoint (default: /jsonrpc)": + "Gib den Pfad zum Aria2 RPC Endpunkt an (Standard: /jsonrpc)", + "SSL/TLS encryption": "SSL/TLS", + "Enable SSL/TLS encryption": "Aktiviere SSL/TLS Verschlüsselung", + "Enter the secret token (optional)": "Secret Token (optional)", + "Enter the Aria2 RPC secret token (leave empty if authentication is not enabled)": + "Gib den Aria2 RPC secret Token ein (leer lassen falls keine Authentifizierung aktiv)", + "Enter the username (optional)": "Benutzername (optional)", + "Enter the Aria2 RPC username (empty if authentication not enabled)": + "Gib den Aria2 RPC Benutzernamen ein (leer lassen falls keine Authentifizierung aktiv)", + "Enter the password (optional)": "Passwort (optional)", + "Enter the Aria2 RPC password (empty if authentication not enabled)": + "Gib das Aria2 RPC Passwort ein (leer lassen falls keine Authentifizierung aktiv)", + "Enter base URL (optional)": "Base URL (optional)", + "Direct Download": "Direkter Download", + "If supplied, links will be created to enable direct download from the Aria2 server.": + "Falls angegeben, werden Links erstellt um einen direkten Download vom Aria2 Server zu ermöglichen", + "(Requires appropriate webserver to be configured.)": + "(Es wird ein entsprechend konfigurierter WebServer benötigt.)", + "Save Connection configuration": "Speichern der Verbindungseinstellung", + Filter: "Filter", + // server info modal + "Aria2 server info": "Aria2 Server Info", + "Aria2 Version": "Aria2 Version", + "Features Enabled": "Aktive Funktionen", + // about modal + "To download the latest version of the project, add issues or to contribute back, head on to": + "Um die neuste Version des Projects zu laden, Fehler zu melden oder sich zu beteiligen, besuch", + "Or you can open the latest version in the browser through": + "Oder du kannst die neueste Version direkt in deinem Browser verwenden", + Close: "Schließen", + // lables + "Download status": "Download Status", + "Download Speed": "Download Geschwindigkeit", + "Upload Speed": "Upload Geschwindigkeit", + "Estimated time": "Geschätzte Zeit", + "Download Size": "Download Größe", + Downloaded: "Heruntergeladen", + Progress: "Fortschritt", + "Download Path": "Download Pfad", + Uploaded: "Hochgeladen", + "Download GID": "Download GID", + "Number of Pieces": "Anzahl der Stücken", + "Piece Length": "Größe der Stücken" }; diff --git a/js/translate/en_US.js b/js/translate/en_US.js index e3d3729c..a174f603 100644 --- a/js/translate/en_US.js +++ b/js/translate/en_US.js @@ -1,146 +1,162 @@ -if(typeof translations == 'undefined'){ - translations = {}; +if (typeof translations == "undefined") { + translations = {}; } translations.en_US = { -// header - 'Search': 'Search', - // Nav menu - 'Add': 'Add', - 'By URIs': 'By URIs', - 'By Torrents': 'By Torrents', - 'By Metalinks': 'By Metalinks', - 'Manage': 'Manage', - 'Pause All': 'Pause All', - 'Resume Paused': 'Resume Paused', - 'Purge Completed': 'Purge Completed', - 'Settings': 'Settings', - 'Connection Settings': 'Connection Settings', - 'Global Settings': 'Global Settings', - 'Server info': 'Server info', - 'About and contribute': 'About and contribute', - 'Toggle navigation': 'Toggle navigation', -// body -// nav side bar - 'Miscellaneous': 'Miscellaneous', - 'Global Statistics': 'Global Statistics', - 'About': 'About', - 'Displaying': 'Displaying', - 'of': 'of', - 'downloads': 'downloads', - 'Language': 'Language', -// download filters - 'Download Filters': 'Download Filters', - 'Running': 'Running', - 'Active': 'Active', - 'Waiting': 'Waiting', - 'Complete': 'Complete', - 'Error': 'Error', - 'Paused': 'Paused', - 'Removed': 'Removed', - 'Hide linked meta-data': 'Hide linked meta-data', - 'Toggle': 'Toggle', - 'Reset filters': 'Reset filters', -// download status - 'Verifing': 'Verifing', - 'Verify Pending': 'Verify Pending', -// starred properties - 'Quick Access Settings': 'Quick Access Settings', - 'Save': 'Save', - 'Save settings': 'Save settings', - 'Currently no download in line to display, use the': 'Currently no download in line to display, use the', - 'download button to start downloading files!': 'download button to start downloading files!', - 'Peers': 'Peers', - 'More Info': 'More Info', - 'Remove': 'Remove', - '# of': '# of', - 'Length': 'Length', -// modals - 'Add Downloads By URIs': 'Add Downloads By URIs', - '- You can add multiple downloads (files) at the same time by putting URIs for each file on a separate line.': - '- You can add multiple downloads (files) at the same time by putting URIs for each file on a separate line.', - '- You can also add multiple URIs (mirrors) for the *same* file. To do this, separate the URIs by a space.': - '- You can also add multiple URIs (mirrors) for the *same* file. To do this, separate the URIs by a space.', - '- A URI can be HTTP(S)/FTP/BitTorrent-Magnet.': '- A URI can be HTTP(S)/FTP/BitTorrent-Magnet.', - 'Download settings': 'Download settings', - 'Advanced settings': 'Advanced settings', - 'Cancel': 'Cancel', - 'Start': 'Start', - 'Choose': 'Choose', - 'Quick Access (shown on the main page)': 'Quick Access (shown on the main page)', -// add torrent modal - 'Add Downloads By Torrents': 'Add Downloads By Torrents', - '- Select the torrent from the local filesystem to start the download.': '- Select the torrent from the local filesystem to start the download.', - '- You can select multiple torrents to start multiple downloads.': '- You can select multiple torrents to start multiple downloads.', - '- To add a BitTorrent-Magnet URL, use the Add By URI option and add it there.': '- To add a BitTorrent-Magnet URL, use the Add By URI option and add it there.', - 'Select Torrents': 'Select Torrents', - 'Select a Torrent': 'Select a Torrent', -// add metalink modal - 'Add Downloads By Metalinks': 'Add Downloads By Metalinks', - 'Select Metalinks': 'Select Metalinks', - '- Select the Metalink from the local filesystem to start the download.': '- Select the Metalink from the local filesystem to start the download.', - '- You can select multiple Metalinks to start multiple downloads.': '- You can select multiple Metalinks to start multiple downloads.', - 'Select a Metalink': 'Select a Metalink', -// select file modal - 'Choose files to start download for': 'Choose files to start download for', - 'Select to download': 'Select to download', -// settings modal - 'Aria2 RPC host and port': 'Aria2 RPC host and port', - 'Enter the host': 'Enter the host', - 'Enter the IP or DNS name of the server on which the RPC for Aria2 is running (default: localhost)': - 'Enter the IP or DNS name of the server on which the RPC for Aria2 is running (default: localhost)', - 'Enter the port': 'Enter the port', - 'Enter the port of the server on which the RPC for Aria2 is running (default: 6800)': - 'Enter the port of the server on which the RPC for Aria2 is running (default: 6800)', - 'Enter the RPC path': 'Enter the RPC path', - 'Enter the path for the Aria2 RPC endpoint (default: /jsonrpc)': 'Enter the path for the Aria2 RPC endpoint (default: /jsonrpc)', - 'SSL/TLS encryption': 'SSL/TLS encryption', - 'Enable SSL/TLS encryption': 'Enable SSL/TLS encryption', - 'Enter the secret token (optional)': 'Enter the secret token (optional)', - 'Enter the Aria2 RPC secret token (leave empty if authentication is not enabled)': - 'Enter the Aria2 RPC secret token (leave empty if authentication is not enabled)', - 'Enter the username (optional)': 'Enter the username (optional)', - 'Enter the Aria2 RPC username (empty if authentication not enabled)': - 'Enter the Aria2 RPC username (empty if authentication not enabled)', - 'Enter the password (optional)': 'Enter the password (optional)', - 'Enter the Aria2 RPC password (empty if authentication not enabled)': 'Enter the Aria2 RPC password (empty if authentication not enabled)', - 'Enter base URL (optional)': 'Enter base URL (optional)', - 'Direct Download': 'Direct Download', - 'If supplied, links will be created to enable direct download from the Aria2 server.': - 'If supplied, links will be created to enable direct download from the Aria2 server.', - '(Requires appropriate webserver to be configured.)': '(Requires appropriate webserver to be configured.)', - 'Save Connection configuration': 'Save Connection configuration', - 'Filter': 'Filter', -// server info modal - 'Aria2 server info': 'Aria2 server info', - 'Aria2 Version': 'Aria2 Version', - 'Features Enabled': 'Features Enabled', -// about modal - 'To download the latest version of the project, add issues or to contribute back, head on to': - 'To download the latest version of the project, add issues or to contribute back, head on to', - 'Or you can open the latest version in the browser through': 'Or you can open the latest version in the browser through', - 'Close': 'Close', -// lables - 'Download status':'Download status', - 'Download Speed':'Download Speed', - 'Upload Speed':'Upload Speed', - 'Estimated time':'Estimated time', - 'Download Size':'Download Size', - 'Downloaded':'Downloaded', - 'Progress':'Progress', - 'Download Path':'Download Path', - 'Uploaded':'Uploaded', - 'Download GID':'Download GID', - 'Number of Pieces':'Number of Pieces', - 'Piece Length': 'Piece Length', - 'Shutdown Server': 'Shutdown Server', + // header + Search: "Search", + // Nav menu + Add: "Add", + "By URIs": "By URIs", + "By Torrents": "By Torrents", + "By Metalinks": "By Metalinks", + Manage: "Manage", + "Pause All": "Pause All", + "Resume Paused": "Resume Paused", + "Purge Completed": "Purge Completed", + Settings: "Settings", + "Connection Settings": "Connection Settings", + "Global Settings": "Global Settings", + "Server info": "Server info", + "About and contribute": "About and contribute", + "Toggle navigation": "Toggle navigation", + // body + // nav side bar + Miscellaneous: "Miscellaneous", + "Global Statistics": "Global Statistics", + About: "About", + Displaying: "Displaying", + of: "of", + downloads: "downloads", + Language: "Language", + // download filters + "Download Filters": "Download Filters", + Running: "Running", + Active: "Active", + Waiting: "Waiting", + Complete: "Complete", + Error: "Error", + Paused: "Paused", + Removed: "Removed", + "Hide linked meta-data": "Hide linked meta-data", + Toggle: "Toggle", + "Reset filters": "Reset filters", + // download status + Verifing: "Verifing", + "Verify Pending": "Verify Pending", + // starred properties + "Quick Access Settings": "Quick Access Settings", + Save: "Save", + "Save settings": "Save settings", + "Currently no download in line to display, use the": + "Currently no download in line to display, use the", + "download button to start downloading files!": "download button to start downloading files!", + Peers: "Peers", + "More Info": "More Info", + Remove: "Remove", + "# of": "# of", + Length: "Length", + // modals + "Add Downloads By URIs": "Add Downloads By URIs", + "- You can add multiple downloads (files) at the same time by putting URIs for each file on a separate line.": + "- You can add multiple downloads (files) at the same time by putting URIs for each file on a separate line.", + "- You can also add multiple URIs (mirrors) for the *same* file. To do this, separate the URIs by a space.": + "- You can also add multiple URIs (mirrors) for the *same* file. To do this, separate the URIs by a space.", + "- A URI can be HTTP(S)/FTP/BitTorrent-Magnet.": "- A URI can be HTTP(S)/FTP/BitTorrent-Magnet.", + "Download settings": "Download settings", + "Advanced settings": "Advanced settings", + Cancel: "Cancel", + Start: "Start", + Choose: "Choose", + "Quick Access (shown on the main page)": "Quick Access (shown on the main page)", + // add torrent modal + "Add Downloads By Torrents": "Add Downloads By Torrents", + "- Select the torrent from the local filesystem to start the download.": + "- Select the torrent from the local filesystem to start the download.", + "- You can select multiple torrents to start multiple downloads.": + "- You can select multiple torrents to start multiple downloads.", + "- To add a BitTorrent-Magnet URL, use the Add By URI option and add it there.": + "- To add a BitTorrent-Magnet URL, use the Add By URI option and add it there.", + "Select Torrents": "Select Torrents", + "Select a Torrent": "Select a Torrent", + // add metalink modal + "Add Downloads By Metalinks": "Add Downloads By Metalinks", + "Select Metalinks": "Select Metalinks", + "- Select the Metalink from the local filesystem to start the download.": + "- Select the Metalink from the local filesystem to start the download.", + "- You can select multiple Metalinks to start multiple downloads.": + "- You can select multiple Metalinks to start multiple downloads.", + "Select a Metalink": "Select a Metalink", + // select file modal + "Choose files to start download for": "Choose files to start download for", + "Select to download": "Select to download", + // settings modal + "Aria2 RPC host and port": "Aria2 RPC host and port", + "Enter the host": "Enter the host", + "Enter the IP or DNS name of the server on which the RPC for Aria2 is running (default: localhost)": + "Enter the IP or DNS name of the server on which the RPC for Aria2 is running (default: localhost)", + "Enter the port": "Enter the port", + "Enter the port of the server on which the RPC for Aria2 is running (default: 6800)": + "Enter the port of the server on which the RPC for Aria2 is running (default: 6800)", + "Enter the RPC path": "Enter the RPC path", + "Enter the path for the Aria2 RPC endpoint (default: /jsonrpc)": + "Enter the path for the Aria2 RPC endpoint (default: /jsonrpc)", + "SSL/TLS encryption": "SSL/TLS encryption", + "Enable SSL/TLS encryption": "Enable SSL/TLS encryption", + "Enter the secret token (optional)": "Enter the secret token (optional)", + "Enter the Aria2 RPC secret token (leave empty if authentication is not enabled)": + "Enter the Aria2 RPC secret token (leave empty if authentication is not enabled)", + "Enter the username (optional)": "Enter the username (optional)", + "Enter the Aria2 RPC username (empty if authentication not enabled)": + "Enter the Aria2 RPC username (empty if authentication not enabled)", + "Enter the password (optional)": "Enter the password (optional)", + "Enter the Aria2 RPC password (empty if authentication not enabled)": + "Enter the Aria2 RPC password (empty if authentication not enabled)", + "Enter base URL (optional)": "Enter base URL (optional)", + "Direct Download": "Direct Download", + "If supplied, links will be created to enable direct download from the Aria2 server.": + "If supplied, links will be created to enable direct download from the Aria2 server.", + "(Requires appropriate webserver to be configured.)": + "(Requires appropriate webserver to be configured.)", + "Save Connection configuration": "Save Connection configuration", + Filter: "Filter", + // server info modal + "Aria2 server info": "Aria2 server info", + "Aria2 Version": "Aria2 Version", + "Features Enabled": "Features Enabled", + // about modal + "To download the latest version of the project, add issues or to contribute back, head on to": + "To download the latest version of the project, add issues or to contribute back, head on to", + "Or you can open the latest version in the browser through": + "Or you can open the latest version in the browser through", + Close: "Close", + // lables + "Download status": "Download status", + "Download Speed": "Download Speed", + "Upload Speed": "Upload Speed", + "Estimated time": "Estimated time", + "Download Size": "Download Size", + Downloaded: "Downloaded", + Progress: "Progress", + "Download Path": "Download Path", + Uploaded: "Uploaded", + "Download GID": "Download GID", + "Number of Pieces": "Number of Pieces", + "Piece Length": "Piece Length", + "Shutdown Server": "Shutdown Server", - 'The last connection attempt was unsuccessful. Trying another configuration': 'The last connection attempt was unsuccessful. Trying another configuration', - 'Oh Snap!': 'Oh Snap!', - 'Could not connect to the aria2 RPC server. Will retry in 10 secs. You might want to check the connection settings by going to Settings > Connection Settings': 'Could not connect to the aria2 RPC server. Will retry in 10 secs. You might want to check the connection settings by going to Settings > Connection Settings', - 'Authentication failed while connecting to Aria2 RPC server. Will retry in 10 secs. You might want to confirm your authentication details by going to Settings > Connection Settings': 'Authentication failed while connecting to Aria2 RPC server. Will retry in 10 secs. You might want to confirm your authentication details by going to Settings > Connection Settings', - 'Successfully connected to Aria2 through its remote RPC …': 'Successfully connected to Aria2 through its remote RPC …', - 'Successfully connected to Aria2 through remote RPC, however the connection is still insecure. For complete security try adding an authorization secret token while starting Aria2 (through the flag --rpc-secret)': 'Successfully connected to Aria2 through remote RPC, however the connection is still insecure. For complete security try adding an authorization secret token while starting Aria2 (through the flag --rpc-secret)', - 'Trying to connect to aria2 using the new connection configuration': 'Trying to connect to aria2 using the new connection configuration', - 'Remove {{name}} and associated meta-data?': 'Remove {{name}} and associated meta-data?' + "The last connection attempt was unsuccessful. Trying another configuration": + "The last connection attempt was unsuccessful. Trying another configuration", + "Oh Snap!": "Oh Snap!", + "Could not connect to the aria2 RPC server. Will retry in 10 secs. You might want to check the connection settings by going to Settings > Connection Settings": + "Could not connect to the aria2 RPC server. Will retry in 10 secs. You might want to check the connection settings by going to Settings > Connection Settings", + "Authentication failed while connecting to Aria2 RPC server. Will retry in 10 secs. You might want to confirm your authentication details by going to Settings > Connection Settings": + "Authentication failed while connecting to Aria2 RPC server. Will retry in 10 secs. You might want to confirm your authentication details by going to Settings > Connection Settings", + "Successfully connected to Aria2 through its remote RPC …": + "Successfully connected to Aria2 through its remote RPC …", + "Successfully connected to Aria2 through remote RPC, however the connection is still insecure. For complete security try adding an authorization secret token while starting Aria2 (through the flag --rpc-secret)": + "Successfully connected to Aria2 through remote RPC, however the connection is still insecure. For complete security try adding an authorization secret token while starting Aria2 (through the flag --rpc-secret)", + "Trying to connect to aria2 using the new connection configuration": + "Trying to connect to aria2 using the new connection configuration", + "Remove {{name}} and associated meta-data?": "Remove {{name}} and associated meta-data?" }; diff --git a/js/translate/es_ES.js b/js/translate/es_ES.js index 1263f018..11ca135e 100644 --- a/js/translate/es_ES.js +++ b/js/translate/es_ES.js @@ -12,154 +12,166 @@ // 5. Browser determining preferred language automatically. // http://angular-translate.github.io/docs/en/#/guide/07_multi-language -if(typeof translations == 'undefined'){ - translations = {}; +if (typeof translations == "undefined") { + translations = {}; } -translations.es_ES = { // replace en_US to ll_CC, examples: zh_CN, de_AT. -// header - 'Search': 'Buscar', - // Nav menu - 'Add': 'Añadir', - 'By URIs': 'URIs', - 'By Torrents': 'Torrents', - 'By Metalinks': 'Metalinks', - 'Manage': 'Administrar', - 'Pause All': 'Pausar Todos', - 'Resume Paused': 'Reanudar Pausados', - 'Purge Completed': 'Purgar Completados', - 'Shutdown Server': 'Desactivar servidor', - 'Settings': 'Ajustes', - 'Connection Settings': 'Ajustes de Conexión', - 'Global Settings': 'Ajustes Globales', - 'Server info': 'Info de Servidor', - 'About and contribute': 'Acerca y Colaborar', - 'Toggle navigation': 'Conmutar Navegación', -// body -// nav side bar - 'Miscellaneous': 'Otros', - 'Global Statistics': 'Estadísticas Globales', - 'About': 'Acerca de', - 'Displaying': 'Mostrando', - 'of': 'de', - 'downloads': 'descargas', - 'Language': 'Idioma', -// download filters - 'Download Filters': 'Filtros de Descargas', - 'Running': 'Procesando', - 'Active': 'Activo', - 'Waiting': 'Esperando', - 'Complete': 'Completo', - 'Error': 'Error', - 'Paused': 'En Pausa', - 'Removed': 'Eliminado', - 'Hide linked meta-data': 'Ocultar metadatos adjuntos', - 'Toggle': 'Conmutar', - 'Reset filters': 'Restablecer Filtros', -// download status - 'Verifing': 'Verificando', - 'Verify Pending': 'Pendiente de verificación', -// starred properties - 'Quick Access Settings': 'Ajustes Rápidos', - 'Save': 'Guardar', - 'Save settings': 'Guardar Ajustes', - 'Currently no download in line to display, use the': 'En este momento no hay descargas para mostrar. ¡Use la opción', - 'download button to start downloading files!': 'para empezar a descargar sus archivos!', - 'Peers': 'Pares', - 'More Info': 'Mas Info', - 'Remove': 'Eliminar', - '# of': '# de', - 'Length': 'Longitud', -// modals - 'Add Downloads By URIs': 'Añadir descargas por URIs', - '- You can add multiple downloads (files) at the same time by putting URIs for each file on a separate line.': - 'Añada varias descargas colocando la URI de cada descarga en una línea separada.', - '- You can also add multiple URIs (mirrors) for the *same* file. To do this, separate the URIs by a space.': - 'Puede añadir URIs de espejo para *el mismo* archivo. Separe cada URI con un espacio.', - '- A URI can be HTTP(S)/FTP/BitTorrent-Magnet.': 'Una URI puede ser HTTP(S), FTP, BitTorrent o Magnet.', - 'Download settings': 'Ajustes de Descargas', - 'Advanced settings': 'Ajustes Avanzados', - 'Cancel': 'Cancelar', - 'Start': 'Iniciar', - 'Choose': 'Escoja', - 'Quick Access (shown on the main page)': 'Acceso Rápido (Se muestra en la pág principal)', -// add torrent modal - 'Add Downloads By Torrents': 'Añadir descargas Torrent', - '- Select the torrent from the local filesystem to start the download.': 'Seleccione el archivo Torrent de su equipo para iniciar la descarga', - '- You can select multiple torrents to start multiple downloads.': 'Puede seleccionar varios torrents', - '- To add a BitTorrent-Magnet URL, use the Add By URI option and add it there.': 'Para los enlaces Magnet, salga de este cuadro y use la opción Añadir \ URI', - 'Select Torrents': 'Escoja los Torrents', - 'Select a Torrent': 'Escoja el Torrent', -// add metalink modal - 'Add Downloads By Metalinks': 'Añadir descargas Metalink', - 'Select Metalinks': 'Seleccione el Metalink', - '- Select the Metalink from the local filesystem to start the download.': 'Escoja el archivo Metalink de su equipo para iniciar la descarga', - '- You can select multiple Metalinks to start multiple downloads.': 'Puede escoger varios archivos Metalink', - 'Select a Metalink': 'Escoja el archivo Metalink', -// select file modal - 'Choose files to start download for': 'Escoja los archivos que desea descargar', - 'Select to download': 'Escoja que descargar', -// settings modal - 'Aria2 RPC host and port': 'Servidor Aria2 y puerto', - 'Enter the host': 'Escriba la dirección', - 'Enter the IP or DNS name of the server on which the RPC for Aria2 is running (default: localhost)': - 'Escriba la dirección o nombre DNS del servidor Aria2 (por defecto: localhost)', - 'Enter the port': 'Escriba el puerto', - 'Enter the port of the server on which the RPC for Aria2 is running (default: 6800)': - 'Escriba el número del puerto del servidor Aria2 (por defecto: 6800)', - 'Enter the RPC path': 'Escriba la ruta RPC', - 'Enter the path for the Aria2 RPC endpoint (default: /jsonrpc)': 'Escriba la ruta de acceso RPC de Aria2 (por defecto: /jsonrpc)', - 'SSL/TLS encryption': 'Cifrado SSL/TLS', - 'Enable SSL/TLS encryption': 'Habilitar Cifrado SSL/TLS', - 'Enter the secret token (optional)': 'Escriba la frase Token (opcional)', - 'Enter the Aria2 RPC secret token (leave empty if authentication is not enabled)': - 'Escriba la frase Token secreta (vacío si la autenticación está deshabilitada)', - 'Enter the username (optional)': 'Usuario (opcional)', - 'Enter the Aria2 RPC username (empty if authentication not enabled)': - 'Escriba el nombre de usuario (vacío si la autenticación está deshabilitada)', - 'Enter the password (optional)': 'Escriba la contraseña', - 'Enter the Aria2 RPC password (empty if authentication not enabled)': 'Escriba la contraseña RPC (vacío si la autenticación está deshabilitada)', - 'Enter base URL (optional)': 'Escriba la URL base (opcional)', - 'Direct Download': 'Descarga Directa', - 'If supplied, links will be created to enable direct download from the Aria2 server.': - 'Esto permite crear enlaces de descarga de los archivos desde el servidor Aria2', - '(Requires appropriate webserver to be configured.)': '(Requiere configuración apropiada del servidor web)', - 'Save Connection configuration': 'Guardar Configuración', - 'Filter': 'Filrar', -// server info modal - 'Aria2 server info': 'Información de servidor Aria2', - 'Aria2 Version': 'Aria2 versión', - 'Features Enabled': 'Funcionalidad disponible', -// about modal - 'To download the latest version of the project, add issues or to contribute back, head on to': - 'Para obtener la última versión del proyecto, reportar problemas o colaborar, vaya a', - 'Or you can open the latest version in the browser through': 'Puede abrir la última versión en su navegador, directamente', - 'Close': 'Cerrar', -// labels - 'Download status':'Estado de descarga', - 'Download Speed':'Velocidad de descarga', - 'Upload Speed':'Vel. Subida', - 'Estimated time':'Tiempo estimado', - 'Download Size':'Tamaño de descarga', - 'Downloaded':'Descargado', - 'Progress':'Progreso', - 'Download Path':'Carpeta de descarga', - 'Uploaded':'Subido', - 'Download GID':'GID de Descarga', - 'Number of Pieces':'N° de Piezas', - 'Piece Length':'Tamaño de pieza', -//alerts - 'The last connection attempt was unsuccessful. Trying another configuration': - 'El último intento de conexión falló. Probando otra configuración', - 'Oh Snap!': 'Rayos…', - 'Could not connect to the aria2 RPC server. Will retry in 10 secs. You might want to check the connection settings by going to Settings > Connection Settings': - 'No se pudo establecer una conexión al servidor Aria2. Reintentando en 10 segundos. Pruebe revisando la configuración en Ajustes > Ajustes de Conexión', - 'Authentication failed while connecting to Aria2 RPC server. Will retry in 10 secs. You might want to confirm your authentication details by going to Settings > Connection Settings': - 'Autenticación fallida con el servior Aria2 RPC. Reintentando en 10 segundos. Puede que sea necesario revisar su info de autenticación en Ajustes > Ajustes de Conexión', - 'Successfully connected to Aria2 through its remote RPC …': - 'Conexión exitosa con el servidor Aria2 mediante la interfaz RPC', - 'Successfully connected to Aria2 through remote RPC, however the connection is still insecure. For complete security try adding an authorization secret token while starting Aria2 (through the flag --rpc-secret)': - 'Conexión exitosa con el servidor Aria2 mediante la interfaz RPC, sin embargo la conexión no es segura. Para mejorar la seguridad, añada un token de autorización al iniciar Aria2 (con la opción --rpc-secret)', - 'Trying to connect to aria2 using the new connection configuration': - 'Intentando conectar con el servidor Aria2 usando los nuevos Ajustes de Conexión' +translations.es_ES = { + // replace en_US to ll_CC, examples: zh_CN, de_AT. + // header + Search: "Buscar", + // Nav menu + Add: "Añadir", + "By URIs": "URIs", + "By Torrents": "Torrents", + "By Metalinks": "Metalinks", + Manage: "Administrar", + "Pause All": "Pausar Todos", + "Resume Paused": "Reanudar Pausados", + "Purge Completed": "Purgar Completados", + "Shutdown Server": "Desactivar servidor", + Settings: "Ajustes", + "Connection Settings": "Ajustes de Conexión", + "Global Settings": "Ajustes Globales", + "Server info": "Info de Servidor", + "About and contribute": "Acerca y Colaborar", + "Toggle navigation": "Conmutar Navegación", + // body + // nav side bar + Miscellaneous: "Otros", + "Global Statistics": "Estadísticas Globales", + About: "Acerca de", + Displaying: "Mostrando", + of: "de", + downloads: "descargas", + Language: "Idioma", + // download filters + "Download Filters": "Filtros de Descargas", + Running: "Procesando", + Active: "Activo", + Waiting: "Esperando", + Complete: "Completo", + Error: "Error", + Paused: "En Pausa", + Removed: "Eliminado", + "Hide linked meta-data": "Ocultar metadatos adjuntos", + Toggle: "Conmutar", + "Reset filters": "Restablecer Filtros", + // download status + Verifing: "Verificando", + "Verify Pending": "Pendiente de verificación", + // starred properties + "Quick Access Settings": "Ajustes Rápidos", + Save: "Guardar", + "Save settings": "Guardar Ajustes", + "Currently no download in line to display, use the": + "En este momento no hay descargas para mostrar. ¡Use la opción", + "download button to start downloading files!": "para empezar a descargar sus archivos!", + Peers: "Pares", + "More Info": "Mas Info", + Remove: "Eliminar", + "# of": "# de", + Length: "Longitud", + // modals + "Add Downloads By URIs": "Añadir descargas por URIs", + "- You can add multiple downloads (files) at the same time by putting URIs for each file on a separate line.": + "Añada varias descargas colocando la URI de cada descarga en una línea separada.", + "- You can also add multiple URIs (mirrors) for the *same* file. To do this, separate the URIs by a space.": + "Puede añadir URIs de espejo para *el mismo* archivo. Separe cada URI con un espacio.", + "- A URI can be HTTP(S)/FTP/BitTorrent-Magnet.": + "Una URI puede ser HTTP(S), FTP, BitTorrent o Magnet.", + "Download settings": "Ajustes de Descargas", + "Advanced settings": "Ajustes Avanzados", + Cancel: "Cancelar", + Start: "Iniciar", + Choose: "Escoja", + "Quick Access (shown on the main page)": "Acceso Rápido (Se muestra en la pág principal)", + // add torrent modal + "Add Downloads By Torrents": "Añadir descargas Torrent", + "- Select the torrent from the local filesystem to start the download.": + "Seleccione el archivo Torrent de su equipo para iniciar la descarga", + "- You can select multiple torrents to start multiple downloads.": + "Puede seleccionar varios torrents", + "- To add a BitTorrent-Magnet URL, use the Add By URI option and add it there.": + "Para los enlaces Magnet, salga de este cuadro y use la opción Añadir URI", + "Select Torrents": "Escoja los Torrents", + "Select a Torrent": "Escoja el Torrent", + // add metalink modal + "Add Downloads By Metalinks": "Añadir descargas Metalink", + "Select Metalinks": "Seleccione el Metalink", + "- Select the Metalink from the local filesystem to start the download.": + "Escoja el archivo Metalink de su equipo para iniciar la descarga", + "- You can select multiple Metalinks to start multiple downloads.": + "Puede escoger varios archivos Metalink", + "Select a Metalink": "Escoja el archivo Metalink", + // select file modal + "Choose files to start download for": "Escoja los archivos que desea descargar", + "Select to download": "Escoja que descargar", + // settings modal + "Aria2 RPC host and port": "Servidor Aria2 y puerto", + "Enter the host": "Escriba la dirección", + "Enter the IP or DNS name of the server on which the RPC for Aria2 is running (default: localhost)": + "Escriba la dirección o nombre DNS del servidor Aria2 (por defecto: localhost)", + "Enter the port": "Escriba el puerto", + "Enter the port of the server on which the RPC for Aria2 is running (default: 6800)": + "Escriba el número del puerto del servidor Aria2 (por defecto: 6800)", + "Enter the RPC path": "Escriba la ruta RPC", + "Enter the path for the Aria2 RPC endpoint (default: /jsonrpc)": + "Escriba la ruta de acceso RPC de Aria2 (por defecto: /jsonrpc)", + "SSL/TLS encryption": "Cifrado SSL/TLS", + "Enable SSL/TLS encryption": "Habilitar Cifrado SSL/TLS", + "Enter the secret token (optional)": "Escriba la frase Token (opcional)", + "Enter the Aria2 RPC secret token (leave empty if authentication is not enabled)": + "Escriba la frase Token secreta (vacío si la autenticación está deshabilitada)", + "Enter the username (optional)": "Usuario (opcional)", + "Enter the Aria2 RPC username (empty if authentication not enabled)": + "Escriba el nombre de usuario (vacío si la autenticación está deshabilitada)", + "Enter the password (optional)": "Escriba la contraseña", + "Enter the Aria2 RPC password (empty if authentication not enabled)": + "Escriba la contraseña RPC (vacío si la autenticación está deshabilitada)", + "Enter base URL (optional)": "Escriba la URL base (opcional)", + "Direct Download": "Descarga Directa", + "If supplied, links will be created to enable direct download from the Aria2 server.": + "Esto permite crear enlaces de descarga de los archivos desde el servidor Aria2", + "(Requires appropriate webserver to be configured.)": + "(Requiere configuración apropiada del servidor web)", + "Save Connection configuration": "Guardar Configuración", + Filter: "Filrar", + // server info modal + "Aria2 server info": "Información de servidor Aria2", + "Aria2 Version": "Aria2 versión", + "Features Enabled": "Funcionalidad disponible", + // about modal + "To download the latest version of the project, add issues or to contribute back, head on to": + "Para obtener la última versión del proyecto, reportar problemas o colaborar, vaya a", + "Or you can open the latest version in the browser through": + "Puede abrir la última versión en su navegador, directamente", + Close: "Cerrar", + // labels + "Download status": "Estado de descarga", + "Download Speed": "Velocidad de descarga", + "Upload Speed": "Vel. Subida", + "Estimated time": "Tiempo estimado", + "Download Size": "Tamaño de descarga", + Downloaded: "Descargado", + Progress: "Progreso", + "Download Path": "Carpeta de descarga", + Uploaded: "Subido", + "Download GID": "GID de Descarga", + "Number of Pieces": "N° de Piezas", + "Piece Length": "Tamaño de pieza", + //alerts + "The last connection attempt was unsuccessful. Trying another configuration": + "El último intento de conexión falló. Probando otra configuración", + "Oh Snap!": "Rayos…", + "Could not connect to the aria2 RPC server. Will retry in 10 secs. You might want to check the connection settings by going to Settings > Connection Settings": + "No se pudo establecer una conexión al servidor Aria2. Reintentando en 10 segundos. Pruebe revisando la configuración en Ajustes > Ajustes de Conexión", + "Authentication failed while connecting to Aria2 RPC server. Will retry in 10 secs. You might want to confirm your authentication details by going to Settings > Connection Settings": + "Autenticación fallida con el servior Aria2 RPC. Reintentando en 10 segundos. Puede que sea necesario revisar su info de autenticación en Ajustes > Ajustes de Conexión", + "Successfully connected to Aria2 through its remote RPC …": + "Conexión exitosa con el servidor Aria2 mediante la interfaz RPC", + "Successfully connected to Aria2 through remote RPC, however the connection is still insecure. For complete security try adding an authorization secret token while starting Aria2 (through the flag --rpc-secret)": + "Conexión exitosa con el servidor Aria2 mediante la interfaz RPC, sin embargo la conexión no es segura. Para mejorar la seguridad, añada un token de autorización al iniciar Aria2 (con la opción --rpc-secret)", + "Trying to connect to aria2 using the new connection configuration": + "Intentando conectar con el servidor Aria2 usando los nuevos Ajustes de Conexión" }; diff --git a/js/translate/fa_IR.js b/js/translate/fa_IR.js index 83febfc6..af8c70db 100644 --- a/js/translate/fa_IR.js +++ b/js/translate/fa_IR.js @@ -1,154 +1,163 @@ -if(typeof translations == 'undefined'){ - translations = {}; +if (typeof translations == "undefined") { + translations = {}; } translations.fa_IR = { -// header - 'Search': 'جستجو', - // Nav menu - 'Add': 'اضافه کردن', - 'By URIs': 'بر اساس مسیر سایت', - 'By Torrents': 'بر اساس تورنت', - 'By Metalinks': 'بر اساس متا لینک', - 'Manage': 'مدیریت', - 'Pause All': 'توقف همه', - 'Resume Paused': 'ادامه متوقف شده ها', - 'Purge Completed': 'حذف تکمیل شده ها', - 'Shutdown Server': 'خاموش کردن سرور', - 'Settings': 'تنظیمات', - 'Connection Settings': 'تنظیمات ارتباط', - 'Global Settings': 'تنظیمات سراسری', - 'Server info': 'اطلاعات سرور', - 'About and contribute': 'درباره و مشارکت', - 'Toggle navigation': 'تغییر ناوبری', -// body -// nav side bar - 'Miscellaneous': 'متفرقه', - 'Global Statistics': 'آمار سراسری', - 'About': 'درباره', - 'Displaying': 'نمایش', - 'of': 'از', - 'downloads': 'دانلودها', - 'Language': 'زبان', -// download filters - 'Download Filters': 'دانلود فیلترها', - 'Running': 'در حال اجرا', - 'Active': 'فعال', - 'Waiting': 'در انتظار', - 'Complete': 'تمام شده', - 'Error': 'خطا', - 'Paused': 'متوقف شده', - 'Removed': 'حذف شده', - 'Hide linked meta-data': 'مخفی کردن متا داده مرتبط', - 'Toggle': 'تغییر وضعیت', - 'Reset filters': 'حذف فیلترها', -// download status - 'Verifing': 'تأیید کردن', - 'Verify Pending': 'تأیید کردن در انتظارها', -// starred properties - 'Quick Access Settings': 'تنظیمات دسترسی سریع', - 'Save': 'ذخیره', - 'Save settings': 'ذخیره تنظیمات', - 'Currently no download in line to display, use the': 'در حال حاضر هیچ دانلودی برای نمایش وجود ندارد، استفاده از', - 'download button to start downloading files!': 'دکمه دانلود برای شروع دانلود فایل ها!', - 'Peers': 'همتایان', - 'More Info': 'اطلاعات بیشتر', - 'Remove': 'حذف', - '# of': 'از #', - 'Length': 'طول', -// modals - 'Add Downloads By URIs': 'اضافه کردن دانلود توسط لینک ها', - '- You can add multiple downloads (files) at the same time by putting URIs for each file on a separate line.': - '- شما می توانید چند بار دانلود (فایل ها) را همزمان با قرار دادن URI ها برای هر فایل در یک خط جداگانه اضافه کنید.', - '- You can also add multiple URIs (mirrors) for the *same* file. To do this, separate the URIs by a space.': - '- شما همچنین می توانید URI های متعدد (آینه ها) را برای فایل *همان* اضافه کنید. برای انجام این کار، URI ها را با یک فضای جداگانه جدا کنید.', - '- A URI can be HTTP(S)/FTP/BitTorrent-Magnet.': '- یک URI می تواند HTTP (S) / FTP / BitTorrent-Magnet باشد.', - 'Download settings': 'تنظیمات دانلود', - 'Advanced settings': 'تنظیمات پیشرفته', - 'Cancel': 'لغو', - 'Start': 'شروع', - 'Choose': 'انتخاب', - 'Quick Access (shown on the main page)': 'دسترسی سریع (نشان داده شده در صفحه اصلی)', -// add torrent modal - 'Add Downloads By Torrents': 'اضافه کردن دانلود توسط تورنت', - '- Select the torrent from the local filesystem to start the download.': '- تورنت را از سیستم فایل محلی انتخاب کنید تا دانلود را شروع کنید.', - '- You can select multiple torrents to start multiple downloads.': '- شما می توانید چندین تورنت را برای شروع بارگیری چندگانه انتخاب کنید.', - '- To add a BitTorrent-Magnet URL, use the Add By URI option and add it there.': '- برای اضافه کردن URL BitTorrent-Magnet، از گزینه بر اساس مسیر سایت استفاده کنید و آن را در آنجا اضافه کنید.', - 'Select Torrents': 'تورنت ها را انتخاب کنید', - 'Select a Torrent': 'تورنتی را انتخاب کنید', -// add metalink modal - 'Add Downloads By Metalinks': 'متالینک ها را انتخاب کنید', - 'Select Metalinks': 'Metalinks را انتخاب کنید', - '- Select the Metalink from the local filesystem to start the download.': '- Metalink را از سیستم فایل محلی انتخاب کنید تا دانلود را شروع کنید.', - '- You can select multiple Metalinks to start multiple downloads.': '- شما می توانید چندین Metalinks را برای شروع چندین بار انتخاب کنید.', - 'Select a Metalink': 'Metalink را انتخاب کنید', -// select file modal - 'Choose files to start download for': 'فایل را برای شروع دانلود انتخاب کنید', - 'Select to download': 'برای دانلود انتخاب کنید', -// settings modal - 'Aria2 RPC host and port': 'میزبان و پورت Aria2 RPC', - 'Enter the host': 'میزبان را وارد کنید', - 'Enter the IP or DNS name of the server on which the RPC for Aria2 is running (default: localhost)': - 'نام IP یا DNS سرور که RPC برای Aria2 در حال اجرا است را وارد کنید (به طور پیش فرض: localhost)', - 'Enter the port': 'پورت را وارد کنید', - 'Enter the port of the server on which the RPC for Aria2 is running (default: 6800)': - 'پورت سرور که RPC برای Aria2 اجرا می شود را وارد کنید (به طور پیش فرض: 6800)', - 'Enter the RPC path': 'مسیر RPC را وارد کنید', - 'Enter the path for the Aria2 RPC endpoint (default: /jsonrpc)': 'مسیر نقطه پایانی Aria2 RPC را وارد کنید (default: / jsonrpc)', - 'SSL/TLS encryption': 'SSL / TLS رمزگذاری', - 'Enable SSL/TLS encryption': 'SSL / TLS رمزگذاری را فعال کنید', - 'Enter the secret token (optional)': 'رمز نشانه (اختیاری) را وارد کنید', - 'Enter the Aria2 RPC secret token (leave empty if authentication is not enabled)': - 'کد مخفی Aria2 RPC را وارد کنید (اگر احراز هویت فعال نمی شود خالی بگذارید)', - 'Enter the username (optional)': 'نام کاربری (اختیاری) را وارد کنید', - 'Enter the Aria2 RPC username (empty if authentication not enabled)': - 'نام کاربری Aria2 RPC را وارد کنید (خالی اگر احراز هویت غیر فعال شود)', - 'Enter the password (optional)': 'رمز عبور را وارد کنید (اختیاری)', - 'Enter the Aria2 RPC password (empty if authentication not enabled)': 'گذرواژه Aria2 RPC را وارد کنید (اگر احراز هویت فعال نمی شود خالی بگذارید)', - 'Enter base URL (optional)': 'URL پایه را وارد کنید (اختیاری)', - 'Direct Download': 'دانلود مستقیم', - 'If supplied, links will be created to enable direct download from the Aria2 server.': - 'در صورت عرضه، لینک برای ایجاد مستقیم دانلود از سرور Aria2 ایجاد خواهد شد.', - '(Requires appropriate webserver to be configured.)': '(نیاز به وب سرور مناسب برای پیکربندی.)', - 'Save Connection configuration': 'ذخیره پیکربندی اتصال', - 'Filter': 'فیلتر', -// server info modal - 'Aria2 server info': 'مشخصات سرور Aria2', - 'Aria2 Version': 'نسخه Aria2', - 'Features Enabled': 'ویژگی های فعال', -// about modal - 'To download the latest version of the project, add issues or to contribute back, head on to': - 'برای دانلود آخرين نسخه پروژه، مسائل را اضافه کنيد يا به پشتيبانی بپردازيد بروید به', - 'Or you can open the latest version in the browser through': 'یا شما می توانید آخرین نسخه را از طریق مرورگر باز کنید', - 'Close': 'بستن', -// labels - 'Download status':'وضعیت دانلود', - 'Download Speed':'سرعت دانلود', - 'Upload Speed':'سرعت آپلود', - 'Estimated time':'زمان تخمین زده شده', - 'Download Size':'اندازه دانلود', - 'Downloaded':'دانلود شده', - 'Progress':'پیشرفت', - 'Download Path':'مسیر دانلود', - 'Uploaded':'آپلود شده', - 'Download GID':'دانلود GID', - 'Number of Pieces':'تعداد قطعات', - 'Piece Length':'طول قطعه', + // header + Search: "جستجو", + // Nav menu + Add: "اضافه کردن", + "By URIs": "بر اساس مسیر سایت", + "By Torrents": "بر اساس تورنت", + "By Metalinks": "بر اساس متا لینک", + Manage: "مدیریت", + "Pause All": "توقف همه", + "Resume Paused": "ادامه متوقف شده ها", + "Purge Completed": "حذف تکمیل شده ها", + "Shutdown Server": "خاموش کردن سرور", + Settings: "تنظیمات", + "Connection Settings": "تنظیمات ارتباط", + "Global Settings": "تنظیمات سراسری", + "Server info": "اطلاعات سرور", + "About and contribute": "درباره و مشارکت", + "Toggle navigation": "تغییر ناوبری", + // body + // nav side bar + Miscellaneous: "متفرقه", + "Global Statistics": "آمار سراسری", + About: "درباره", + Displaying: "نمایش", + of: "از", + downloads: "دانلودها", + Language: "زبان", + // download filters + "Download Filters": "دانلود فیلترها", + Running: "در حال اجرا", + Active: "فعال", + Waiting: "در انتظار", + Complete: "تمام شده", + Error: "خطا", + Paused: "متوقف شده", + Removed: "حذف شده", + "Hide linked meta-data": "مخفی کردن متا داده مرتبط", + Toggle: "تغییر وضعیت", + "Reset filters": "حذف فیلترها", + // download status + Verifing: "تأیید کردن", + "Verify Pending": "تأیید کردن در انتظارها", + // starred properties + "Quick Access Settings": "تنظیمات دسترسی سریع", + Save: "ذخیره", + "Save settings": "ذخیره تنظیمات", + "Currently no download in line to display, use the": + "در حال حاضر هیچ دانلودی برای نمایش وجود ندارد، استفاده از", + "download button to start downloading files!": "دکمه دانلود برای شروع دانلود فایل ها!", + Peers: "همتایان", + "More Info": "اطلاعات بیشتر", + Remove: "حذف", + "# of": "از #", + Length: "طول", + // modals + "Add Downloads By URIs": "اضافه کردن دانلود توسط لینک ها", + "- You can add multiple downloads (files) at the same time by putting URIs for each file on a separate line.": + "- شما می توانید چند بار دانلود (فایل ها) را همزمان با قرار دادن URI ها برای هر فایل در یک خط جداگانه اضافه کنید.", + "- You can also add multiple URIs (mirrors) for the *same* file. To do this, separate the URIs by a space.": + "- شما همچنین می توانید URI های متعدد (آینه ها) را برای فایل *همان* اضافه کنید. برای انجام این کار، URI ها را با یک فضای جداگانه جدا کنید.", + "- A URI can be HTTP(S)/FTP/BitTorrent-Magnet.": + "- یک URI می تواند HTTP (S) / FTP / BitTorrent-Magnet باشد.", + "Download settings": "تنظیمات دانلود", + "Advanced settings": "تنظیمات پیشرفته", + Cancel: "لغو", + Start: "شروع", + Choose: "انتخاب", + "Quick Access (shown on the main page)": "دسترسی سریع (نشان داده شده در صفحه اصلی)", + // add torrent modal + "Add Downloads By Torrents": "اضافه کردن دانلود توسط تورنت", + "- Select the torrent from the local filesystem to start the download.": + "- تورنت را از سیستم فایل محلی انتخاب کنید تا دانلود را شروع کنید.", + "- You can select multiple torrents to start multiple downloads.": + "- شما می توانید چندین تورنت را برای شروع بارگیری چندگانه انتخاب کنید.", + "- To add a BitTorrent-Magnet URL, use the Add By URI option and add it there.": + "- برای اضافه کردن URL BitTorrent-Magnet، از گزینه بر اساس مسیر سایت استفاده کنید و آن را در آنجا اضافه کنید.", + "Select Torrents": "تورنت ها را انتخاب کنید", + "Select a Torrent": "تورنتی را انتخاب کنید", + // add metalink modal + "Add Downloads By Metalinks": "متالینک ها را انتخاب کنید", + "Select Metalinks": "Metalinks را انتخاب کنید", + "- Select the Metalink from the local filesystem to start the download.": + "- Metalink را از سیستم فایل محلی انتخاب کنید تا دانلود را شروع کنید.", + "- You can select multiple Metalinks to start multiple downloads.": + "- شما می توانید چندین Metalinks را برای شروع چندین بار انتخاب کنید.", + "Select a Metalink": "Metalink را انتخاب کنید", + // select file modal + "Choose files to start download for": "فایل را برای شروع دانلود انتخاب کنید", + "Select to download": "برای دانلود انتخاب کنید", + // settings modal + "Aria2 RPC host and port": "میزبان و پورت Aria2 RPC", + "Enter the host": "میزبان را وارد کنید", + "Enter the IP or DNS name of the server on which the RPC for Aria2 is running (default: localhost)": + "نام IP یا DNS سرور که RPC برای Aria2 در حال اجرا است را وارد کنید (به طور پیش فرض: localhost)", + "Enter the port": "پورت را وارد کنید", + "Enter the port of the server on which the RPC for Aria2 is running (default: 6800)": + "پورت سرور که RPC برای Aria2 اجرا می شود را وارد کنید (به طور پیش فرض: 6800)", + "Enter the RPC path": "مسیر RPC را وارد کنید", + "Enter the path for the Aria2 RPC endpoint (default: /jsonrpc)": + "مسیر نقطه پایانی Aria2 RPC را وارد کنید (default: / jsonrpc)", + "SSL/TLS encryption": "SSL / TLS رمزگذاری", + "Enable SSL/TLS encryption": "SSL / TLS رمزگذاری را فعال کنید", + "Enter the secret token (optional)": "رمز نشانه (اختیاری) را وارد کنید", + "Enter the Aria2 RPC secret token (leave empty if authentication is not enabled)": + "کد مخفی Aria2 RPC را وارد کنید (اگر احراز هویت فعال نمی شود خالی بگذارید)", + "Enter the username (optional)": "نام کاربری (اختیاری) را وارد کنید", + "Enter the Aria2 RPC username (empty if authentication not enabled)": + "نام کاربری Aria2 RPC را وارد کنید (خالی اگر احراز هویت غیر فعال شود)", + "Enter the password (optional)": "رمز عبور را وارد کنید (اختیاری)", + "Enter the Aria2 RPC password (empty if authentication not enabled)": + "گذرواژه Aria2 RPC را وارد کنید (اگر احراز هویت فعال نمی شود خالی بگذارید)", + "Enter base URL (optional)": "URL پایه را وارد کنید (اختیاری)", + "Direct Download": "دانلود مستقیم", + "If supplied, links will be created to enable direct download from the Aria2 server.": + "در صورت عرضه، لینک برای ایجاد مستقیم دانلود از سرور Aria2 ایجاد خواهد شد.", + "(Requires appropriate webserver to be configured.)": "(نیاز به وب سرور مناسب برای پیکربندی.)", + "Save Connection configuration": "ذخیره پیکربندی اتصال", + Filter: "فیلتر", + // server info modal + "Aria2 server info": "مشخصات سرور Aria2", + "Aria2 Version": "نسخه Aria2", + "Features Enabled": "ویژگی های فعال", + // about modal + "To download the latest version of the project, add issues or to contribute back, head on to": + "برای دانلود آخرين نسخه پروژه، مسائل را اضافه کنيد يا به پشتيبانی بپردازيد بروید به", + "Or you can open the latest version in the browser through": + "یا شما می توانید آخرین نسخه را از طریق مرورگر باز کنید", + Close: "بستن", + // labels + "Download status": "وضعیت دانلود", + "Download Speed": "سرعت دانلود", + "Upload Speed": "سرعت آپلود", + "Estimated time": "زمان تخمین زده شده", + "Download Size": "اندازه دانلود", + Downloaded: "دانلود شده", + Progress: "پیشرفت", + "Download Path": "مسیر دانلود", + Uploaded: "آپلود شده", + "Download GID": "دانلود GID", + "Number of Pieces": "تعداد قطعات", + "Piece Length": "طول قطعه", -//alerts - 'The last connection attempt was unsuccessful. Trying another configuration': - 'آخرین تلاش اتصال ناموفق بود. تلاش برای تنظیم دیگر', - 'Oh Snap!': 'اوه نه!', - 'Could not connect to the aria2 RPC server. Will retry in 10 secs. You might want to check the connection settings by going to Settings > Connection Settings': - 'نمی توان به سرور aria2 RPC متصل شد. در 10 ثانیه دوباره تلاش خواهیم کرد ممکن است بخواهید تنظیمات اتصال را با رفتن به تنظیمات > تنظیمات اتصال بررسی کنید', - 'Authentication failed while connecting to Aria2 RPC server. Will retry in 10 secs. You might want to confirm your authentication details by going to Settings > Connection Settings': - 'در هنگام اتصال به سرور Aria2 RPC تأییدیه شکست خورد. در 10 ثانیه دوباره تلاش خواهیم کرد ممکن است بخواهید جزئیات احراز هویت خود را با رفتن به تنظیمات > تنظیمات اتصال تایید کنید', - 'Successfully connected to Aria2 through its remote RPC …': - 'با موفقیت از طریق RPC از راه دور به Aria2 متصل شد ...', - 'Successfully connected to Aria2 through remote RPC, however the connection is still insecure. For complete security try adding an authorization secret token while starting Aria2 (through the flag --rpc-secret)': - 'با موفقیت به Aria2 از طریق RPC راه دور متصل شد، اما اتصال هنوز ناامن است. برای امنیت کامل سعی کنید مجوز نشانه مجوز را در هنگام شروع Aria2 (از طریق پرچم --rpc-secret)', - 'Trying to connect to aria2 using the new connection configuration': - 'تلاش برای اتصال به aria2 با استفاده از پیکربندی اتصال جدید', - 'Remove {{name}} and associated meta-data?': - 'حذف {{name}} و متا داده های مرتبط' + //alerts + "The last connection attempt was unsuccessful. Trying another configuration": + "آخرین تلاش اتصال ناموفق بود. تلاش برای تنظیم دیگر", + "Oh Snap!": "اوه نه!", + "Could not connect to the aria2 RPC server. Will retry in 10 secs. You might want to check the connection settings by going to Settings > Connection Settings": + "نمی توان به سرور aria2 RPC متصل شد. در 10 ثانیه دوباره تلاش خواهیم کرد ممکن است بخواهید تنظیمات اتصال را با رفتن به تنظیمات > تنظیمات اتصال بررسی کنید", + "Authentication failed while connecting to Aria2 RPC server. Will retry in 10 secs. You might want to confirm your authentication details by going to Settings > Connection Settings": + "در هنگام اتصال به سرور Aria2 RPC تأییدیه شکست خورد. در 10 ثانیه دوباره تلاش خواهیم کرد ممکن است بخواهید جزئیات احراز هویت خود را با رفتن به تنظیمات > تنظیمات اتصال تایید کنید", + "Successfully connected to Aria2 through its remote RPC …": + "با موفقیت از طریق RPC از راه دور به Aria2 متصل شد ...", + "Successfully connected to Aria2 through remote RPC, however the connection is still insecure. For complete security try adding an authorization secret token while starting Aria2 (through the flag --rpc-secret)": + "با موفقیت به Aria2 از طریق RPC راه دور متصل شد، اما اتصال هنوز ناامن است. برای امنیت کامل سعی کنید مجوز نشانه مجوز را در هنگام شروع Aria2 (از طریق پرچم --rpc-secret)", + "Trying to connect to aria2 using the new connection configuration": + "تلاش برای اتصال به aria2 با استفاده از پیکربندی اتصال جدید", + "Remove {{name}} and associated meta-data?": "حذف {{name}} و متا داده های مرتبط" }; diff --git a/js/translate/fr_FR.js b/js/translate/fr_FR.js index e6fca352..1d80b970 100644 --- a/js/translate/fr_FR.js +++ b/js/translate/fr_FR.js @@ -1,146 +1,164 @@ -if(typeof translations == 'undefined'){ - translations = {}; +if (typeof translations == "undefined") { + translations = {}; } translations.fr_FR = { -// header - 'Search': 'Rechercher', - // Nav menu - 'Add': 'Ajouter', - 'By URIs': 'Par URIs', - 'By Torrents': 'Par Torrents', - 'By Metalinks': 'Par Metaliens', - 'Manage': 'Gérer', - 'Pause All': 'Tout suspendre', - 'Resume Paused': 'Reprendre', - 'Purge Completed': 'Nettoyer les fichiers complétés', - 'Settings': 'Paramètres', - 'Connection Settings': 'Paramètres de connexion', - 'Global Settings': 'Paramètres globaux', - 'Server info': 'Informations serveur', - 'About and contribute': 'À propos et contribuer', - 'Toggle navigation': 'Basculer la navigation', -// body -// nav side bar - 'Miscellaneous': 'Autres', - 'Global Statistics': 'Statistiques globales', - 'About': 'À propos', - 'Displaying': 'Affichage de', - 'of': 'parmi', - 'downloads': 'téléchargements', - 'Language': 'Langue', -// download filters - 'Download Filters': 'Filtres de téléchargement', - 'Running': 'En cours', - 'Active': 'Actifs', - 'Waiting': 'En attente', - 'Complete': 'Complétés', - 'Error': 'Erreurs', - 'Paused': 'En pause', - 'Removed': 'Supprimés', - 'Hide linked meta-data': 'Cacher les métadonnées liées', - 'Toggle': 'Basculer', - 'Reset filters': 'Réinitialiser les filtres', -// download status - 'Verifing': 'Vérification', - 'Verify Pending': 'Vérification en attente', -// starred properties - 'Quick Access Settings': 'Paramètres d\'accès rapide', - 'Save': 'Sauvegarder', - 'Save settings': 'Sauvegarder les paramètres', - 'Currently no download in line to display, use the': 'Aucun téléchargement dans la file d\'attente, utilisez le bouton de téléchargement', - 'download button to start downloading files!': 'pour commencer à télécharger des fichiers !', - 'Peers': 'Pairs', - 'More Info': 'Plus d\'infos', - 'Remove': 'Supprimer', - '# of': '# parmi', - 'Length': 'Longueur', -// modals - 'Add Downloads By URIs': 'Ajouter des téléchargements depuis des URIs', - '- You can add multiple downloads (files) at the same time by putting URIs for each file on a separate line.': - 'Vous pouvez ajouter plusieurs téléchargements (fichiers) en même temps, en mettant une URI pour chaque fichier sur une nouvelle ligne', - '- You can also add multiple URIs (mirrors) for the *same* file. To do this, separate the URIs by a space.': - 'Vous pouvez aussi ajouter plusieurs URIs (mirroirs) pour le *même* fichier. Pour ce faire, séparez les URIs par un espace.', - '- A URI can be HTTP(S)/FTP/BitTorrent-Magnet.': 'Une URI peut être HTTP(S)/FTP/BitTorrent-Magnet.', - 'Download settings': 'Paramètres de téléchargement', - 'Advanced settings': 'Paramètres avancés', - 'Cancel': 'Annuler', - 'Start': 'Démarrer', - 'Choose': 'Choisir', - 'Quick Access (shown on the main page)': 'Accès rapide (affiché sur la page principale', -// add torrent modal - 'Add Downloads By Torrents': 'Ajouter des téléchargements à partir de fichiers Torrent', - '- Select the torrent from the local filesystem to start the download.': '- Sélectionnez le torrent depuis votre système de fichier local pour commencer le téléchargement.', - '- You can select multiple torrents to start multiple downloads.': 'Vous pouvez sélectionner plusieurs torrents pour commencer plusieurs téléchargements.', - '- To add a BitTorrent-Magnet URL, use the Add By URI option and add it there.': 'Pour ajouter une URL BitTorrent-Magnet, utilisez l\'option Ajouter par URIs et ajoutez-la à ce niveau.', - 'Select Torrents': 'Sélectionner des Torrents', - 'Select a Torrent': 'Sélectionner un Torrent', -// add metalink modal - 'Add Downloads By Metalinks': 'Ajouter des téléchargements par Metaliens', - 'Select Metalinks': 'Sélectionner des Métaliens', - '- Select the Metalink from the local filesystem to start the download.': 'Sélectionner le Métalien depuis votre système de fichier local pour commencer le téléchargement.', - '- You can select multiple Metalinks to start multiple downloads.': 'Vous pouvez sélectionner plusieurs Métaliens pour commencer plusieurs téléchargements.', - 'Select a Metalink': 'Sélectionner un Métalien', -// select file modal - 'Choose files to start download for': 'Sélectionner les fichiers pour lesquels commencer le téléchargement.', - 'Select to download': 'Sélectionner pour télécharger', -// settings modal - 'Aria2 RPC host and port': 'Hôte et ports Aria2 RPC', - 'Enter the host': 'Entrer l\'hôte', - 'Enter the IP or DNS name of the server on which the RPC for Aria2 is running (default: localhost)': - 'Entrer l\'IP ou le nom DNS du serveur sur lequel est lancé le RPC pour Aria2 (défaut : localhost)', - 'Enter the port': 'Entrer le port', - 'Enter the port of the server on which the RPC for Aria2 is running (default: 6800)': - 'Entrer le port du serveur sur lequel tourne le RPC pour Aria2 (défaut : 6800)', - 'Enter the RPC path': 'Entrer le chemin vers le RPC', - 'Enter the path for the Aria2 RPC endpoint (default: /jsonrpc)': 'Entrer le chemin final pour le RPC Aria2 (défaut : /jsonrpc)', - 'SSL/TLS encryption': 'Chiffrage SSL/TLS', - 'Enable SSL/TLS encryption': 'Activer le chiffrage SSL/TLS', - 'Enter the secret token (optional)': 'Entrer le token secret (optionnel)', - 'Enter the Aria2 RPC secret token (leave empty if authentication is not enabled)': - 'Entrer le token secret pour le RPC Aria2 (laisser vide si l\'authentification n\'est pas activée)', - 'Enter the username (optional)': 'Entrer le nom d\'utilisateur (optionnel)', - 'Enter the Aria2 RPC username (empty if authentication not enabled)': - 'Entrer le nom d\'utilisateur RPC Aria2 (laisser vide si l\'authentification n\'est pas activée)', - 'Enter the password (optional)': 'Entrer le mot de passe (optionnel)', - 'Enter the Aria2 RPC password (empty if authentication not enabled)': 'Entrer le mot de passe RPC Aria2 (laisser vide si l\'authentification n\'est pas activée)', - 'Enter base URL (optional)': 'Entrez l\'URL de base', - 'Direct Download': 'Téléchargement direct', - 'If supplied, links will be created to enable direct download from the Aria2 server.': - 'S\'ils sont fournis, les liens seront créés pour activer le téléchargement direct depuis le serveur Aria2', - '(Requires appropriate webserver to be configured.)': '(Nécessite un serveur web approprié pour être configuré)', - 'Save Connection configuration': 'Sauvegarder la configuration de connexion', - 'Filter': 'Filtre', -// server info modal - 'Aria2 server info': 'Infos serveur Aria2', - 'Aria2 Version': 'Version Aria2', - 'Features Enabled': 'Fonctionnalités activées', -// about modal - 'To download the latest version of the project, add issues or to contribute back, head on to': - 'Pour télécharger la dernière version du projet, signaler des problèmes ou pour contribuer, aller à l\'adresse', - 'Or you can open the latest version in the browser through': 'Ou vous pouvez ouvrir la dernière version dans le navigateur depuis', - 'Close': 'Fermer', -// lables - 'Download status':'Statut de téléchargement', - 'Download Speed':'Vitesse de téléchargement', - 'Upload Speed':'Vitesse d\'envoi', - 'Estimated time':'Temps estimé', - 'Download Size':'Taille du téléchargement', - 'Downloaded':'Téléchargé', - 'Progress':'Avancement', - 'Download Path':'Chemin de téléchargement', - 'Uploaded':'Envoyé', - 'Download GID':'GID du téléchargement', - 'Number of Pieces':'Nombre de pièces', - 'Piece Length':'Taille de la pièce', - 'Shutdown Server': 'Arrêter le serveur', + // header + Search: "Rechercher", + // Nav menu + Add: "Ajouter", + "By URIs": "Par URIs", + "By Torrents": "Par Torrents", + "By Metalinks": "Par Metaliens", + Manage: "Gérer", + "Pause All": "Tout suspendre", + "Resume Paused": "Reprendre", + "Purge Completed": "Nettoyer les fichiers complétés", + Settings: "Paramètres", + "Connection Settings": "Paramètres de connexion", + "Global Settings": "Paramètres globaux", + "Server info": "Informations serveur", + "About and contribute": "À propos et contribuer", + "Toggle navigation": "Basculer la navigation", + // body + // nav side bar + Miscellaneous: "Autres", + "Global Statistics": "Statistiques globales", + About: "À propos", + Displaying: "Affichage de", + of: "parmi", + downloads: "téléchargements", + Language: "Langue", + // download filters + "Download Filters": "Filtres de téléchargement", + Running: "En cours", + Active: "Actifs", + Waiting: "En attente", + Complete: "Complétés", + Error: "Erreurs", + Paused: "En pause", + Removed: "Supprimés", + "Hide linked meta-data": "Cacher les métadonnées liées", + Toggle: "Basculer", + "Reset filters": "Réinitialiser les filtres", + // download status + Verifing: "Vérification", + "Verify Pending": "Vérification en attente", + // starred properties + "Quick Access Settings": "Paramètres d'accès rapide", + Save: "Sauvegarder", + "Save settings": "Sauvegarder les paramètres", + "Currently no download in line to display, use the": + "Aucun téléchargement dans la file d'attente, utilisez le bouton de téléchargement", + "download button to start downloading files!": "pour commencer à télécharger des fichiers !", + Peers: "Pairs", + "More Info": "Plus d'infos", + Remove: "Supprimer", + "# of": "# parmi", + Length: "Longueur", + // modals + "Add Downloads By URIs": "Ajouter des téléchargements depuis des URIs", + "- You can add multiple downloads (files) at the same time by putting URIs for each file on a separate line.": + "Vous pouvez ajouter plusieurs téléchargements (fichiers) en même temps, en mettant une URI pour chaque fichier sur une nouvelle ligne", + "- You can also add multiple URIs (mirrors) for the *same* file. To do this, separate the URIs by a space.": + "Vous pouvez aussi ajouter plusieurs URIs (mirroirs) pour le *même* fichier. Pour ce faire, séparez les URIs par un espace.", + "- A URI can be HTTP(S)/FTP/BitTorrent-Magnet.": + "Une URI peut être HTTP(S)/FTP/BitTorrent-Magnet.", + "Download settings": "Paramètres de téléchargement", + "Advanced settings": "Paramètres avancés", + Cancel: "Annuler", + Start: "Démarrer", + Choose: "Choisir", + "Quick Access (shown on the main page)": "Accès rapide (affiché sur la page principale", + // add torrent modal + "Add Downloads By Torrents": "Ajouter des téléchargements à partir de fichiers Torrent", + "- Select the torrent from the local filesystem to start the download.": + "- Sélectionnez le torrent depuis votre système de fichier local pour commencer le téléchargement.", + "- You can select multiple torrents to start multiple downloads.": + "Vous pouvez sélectionner plusieurs torrents pour commencer plusieurs téléchargements.", + "- To add a BitTorrent-Magnet URL, use the Add By URI option and add it there.": + "Pour ajouter une URL BitTorrent-Magnet, utilisez l'option Ajouter par URIs et ajoutez-la à ce niveau.", + "Select Torrents": "Sélectionner des Torrents", + "Select a Torrent": "Sélectionner un Torrent", + // add metalink modal + "Add Downloads By Metalinks": "Ajouter des téléchargements par Metaliens", + "Select Metalinks": "Sélectionner des Métaliens", + "- Select the Metalink from the local filesystem to start the download.": + "Sélectionner le Métalien depuis votre système de fichier local pour commencer le téléchargement.", + "- You can select multiple Metalinks to start multiple downloads.": + "Vous pouvez sélectionner plusieurs Métaliens pour commencer plusieurs téléchargements.", + "Select a Metalink": "Sélectionner un Métalien", + // select file modal + "Choose files to start download for": + "Sélectionner les fichiers pour lesquels commencer le téléchargement.", + "Select to download": "Sélectionner pour télécharger", + // settings modal + "Aria2 RPC host and port": "Hôte et ports Aria2 RPC", + "Enter the host": "Entrer l'hôte", + "Enter the IP or DNS name of the server on which the RPC for Aria2 is running (default: localhost)": + "Entrer l'IP ou le nom DNS du serveur sur lequel est lancé le RPC pour Aria2 (défaut : localhost)", + "Enter the port": "Entrer le port", + "Enter the port of the server on which the RPC for Aria2 is running (default: 6800)": + "Entrer le port du serveur sur lequel tourne le RPC pour Aria2 (défaut : 6800)", + "Enter the RPC path": "Entrer le chemin vers le RPC", + "Enter the path for the Aria2 RPC endpoint (default: /jsonrpc)": + "Entrer le chemin final pour le RPC Aria2 (défaut : /jsonrpc)", + "SSL/TLS encryption": "Chiffrage SSL/TLS", + "Enable SSL/TLS encryption": "Activer le chiffrage SSL/TLS", + "Enter the secret token (optional)": "Entrer le token secret (optionnel)", + "Enter the Aria2 RPC secret token (leave empty if authentication is not enabled)": + "Entrer le token secret pour le RPC Aria2 (laisser vide si l'authentification n'est pas activée)", + "Enter the username (optional)": "Entrer le nom d'utilisateur (optionnel)", + "Enter the Aria2 RPC username (empty if authentication not enabled)": + "Entrer le nom d'utilisateur RPC Aria2 (laisser vide si l'authentification n'est pas activée)", + "Enter the password (optional)": "Entrer le mot de passe (optionnel)", + "Enter the Aria2 RPC password (empty if authentication not enabled)": + "Entrer le mot de passe RPC Aria2 (laisser vide si l'authentification n'est pas activée)", + "Enter base URL (optional)": "Entrez l'URL de base", + "Direct Download": "Téléchargement direct", + "If supplied, links will be created to enable direct download from the Aria2 server.": + "S'ils sont fournis, les liens seront créés pour activer le téléchargement direct depuis le serveur Aria2", + "(Requires appropriate webserver to be configured.)": + "(Nécessite un serveur web approprié pour être configuré)", + "Save Connection configuration": "Sauvegarder la configuration de connexion", + Filter: "Filtre", + // server info modal + "Aria2 server info": "Infos serveur Aria2", + "Aria2 Version": "Version Aria2", + "Features Enabled": "Fonctionnalités activées", + // about modal + "To download the latest version of the project, add issues or to contribute back, head on to": + "Pour télécharger la dernière version du projet, signaler des problèmes ou pour contribuer, aller à l'adresse", + "Or you can open the latest version in the browser through": + "Ou vous pouvez ouvrir la dernière version dans le navigateur depuis", + Close: "Fermer", + // lables + "Download status": "Statut de téléchargement", + "Download Speed": "Vitesse de téléchargement", + "Upload Speed": "Vitesse d'envoi", + "Estimated time": "Temps estimé", + "Download Size": "Taille du téléchargement", + Downloaded: "Téléchargé", + Progress: "Avancement", + "Download Path": "Chemin de téléchargement", + Uploaded: "Envoyé", + "Download GID": "GID du téléchargement", + "Number of Pieces": "Nombre de pièces", + "Piece Length": "Taille de la pièce", + "Shutdown Server": "Arrêter le serveur", - 'The last connection attempt was unsuccessful. Trying another configuration': 'La dernière tentative de connexion a échoué. Essai d\'une autre configuration', - 'Oh Snap!': 'Oh non !', - 'Could not connect to the aria2 RPC server. Will retry in 10 secs. You might want to check the connection settings by going to Settings > Connection Settings': 'Impossible de se connecter au serveur RPC d\'aria2. Nouvel essai dans 10 secondes. Vous voudrez peut-être vérifier les paramètres de connexion en allant dans Paramètres > Paramètres de connexion', - 'Authentication failed while connecting to Aria2 RPC server. Will retry in 10 secs. You might want to confirm your authentication details by going to Settings > Connection Settings': 'Erreur d\'authentification lors de la connexion au serveur RPC d\'aria2. Nouvel essai dans 10 secondes. Vous voudrez peut-être confirmer les renseignements d\'authentification en allant dans Paramètres > Paramètres de connexion', - 'Successfully connected to Aria2 through its remote RPC …': 'Connexion réussie à aria2 via son interface RPC …', - 'Successfully connected to Aria2 through remote RPC, however the connection is still insecure. For complete security try adding an authorization secret token while starting Aria2 (through the flag --rpc-secret)': 'Connexion réussie à aria2 via l\'interface RPC, cependant la connexion n\'est toujours pas sécurisée. Pour une sécurité complète, essayez d\'ajouter un token secret d\'autorisation en lançant aria2 (à l\'aide de l\'option --rpc-secret)', - 'Trying to connect to aria2 using the new connection configuration': 'Tentative de connexion à aria2 avec la nouvelle configuration', - 'Remove {{name}} and associated meta-data?': 'Supprimer {{name}} et les métadonnées associées' + "The last connection attempt was unsuccessful. Trying another configuration": + "La dernière tentative de connexion a échoué. Essai d'une autre configuration", + "Oh Snap!": "Oh non !", + "Could not connect to the aria2 RPC server. Will retry in 10 secs. You might want to check the connection settings by going to Settings > Connection Settings": + "Impossible de se connecter au serveur RPC d'aria2. Nouvel essai dans 10 secondes. Vous voudrez peut-être vérifier les paramètres de connexion en allant dans Paramètres > Paramètres de connexion", + "Authentication failed while connecting to Aria2 RPC server. Will retry in 10 secs. You might want to confirm your authentication details by going to Settings > Connection Settings": + "Erreur d'authentification lors de la connexion au serveur RPC d'aria2. Nouvel essai dans 10 secondes. Vous voudrez peut-être confirmer les renseignements d'authentification en allant dans Paramètres > Paramètres de connexion", + "Successfully connected to Aria2 through its remote RPC …": + "Connexion réussie à aria2 via son interface RPC …", + "Successfully connected to Aria2 through remote RPC, however the connection is still insecure. For complete security try adding an authorization secret token while starting Aria2 (through the flag --rpc-secret)": + "Connexion réussie à aria2 via l'interface RPC, cependant la connexion n'est toujours pas sécurisée. Pour une sécurité complète, essayez d'ajouter un token secret d'autorisation en lançant aria2 (à l'aide de l'option --rpc-secret)", + "Trying to connect to aria2 using the new connection configuration": + "Tentative de connexion à aria2 avec la nouvelle configuration", + "Remove {{name}} and associated meta-data?": "Supprimer {{name}} et les métadonnées associées" }; diff --git a/js/translate/id_ID.js b/js/translate/id_ID.js index 03c29c08..2bba4138 100644 --- a/js/translate/id_ID.js +++ b/js/translate/id_ID.js @@ -1,154 +1,166 @@ -if(typeof translations == 'undefined'){ - translations = {}; +if (typeof translations == "undefined") { + translations = {}; } -translations.id_ID = { // replace en_US to ll_CC, examples: zh_CN, de_AT. -// header - 'Search': 'Telusuri', - // Nav menu - 'Add': 'Tambah', - 'By URIs': 'Dari URI', - 'By Torrents': 'Dari Torrent', - 'By Metalinks': 'Dari Metalink', - 'Manage': 'Kelola', - 'Pause All': 'Jeda Semua', - 'Resume Paused': 'Lanjut yang Dijeda', - 'Purge Completed': 'Hapus yang Terunduh', - 'Shutdown Server': 'Matikan Peladen', - 'Settings': 'Pengaturan', - 'Connection Settings': 'Pengaturan Koneksi', - 'Global Settings': 'Pengaturan Global', - 'Server info': 'Info peladen', - 'About and contribute': 'Tentang dan kontribusi', - 'Toggle navigation': 'Alihkan navigasi', -// body -// nav side bar - 'Miscellaneous': 'Lain-lain', - 'Global Statistics': 'Statistik Global', - 'About': 'Tentang', - 'Displaying': 'Tampilan', - 'of': 'dari', - 'downloads': 'unduhan', - 'Language': 'Bahasa', -// download filters - 'Download Filters': 'Saring Unduhan', - 'Running': 'Berjalan', - 'Active': 'Aktif', - 'Waiting': 'Menunggu', - 'Complete': 'Selesai', - 'Error': 'Galat', - 'Paused': 'Dijeda', - 'Removed': 'Dihapus', - 'Hide linked meta-data': 'Sembunyikan tautan meta-data', - 'Toggle': 'Tombol alihan', - 'Reset filters': 'Reset penyaring', -// download status - 'Verifing': 'Memverifikasi', - 'Verify Pending': 'Verifikasi Ditunda', -// starred properties - 'Quick Access Settings': 'Pengaturan Akses Cepat', - 'Save': 'Simpan', - 'Save settings': 'Simpan pengaturan', - 'Currently no download in line to display, use the': 'Sekarang tak ada unduhan yang ditampilkan, gunakan', - 'download button to start downloading files!': 'tombol unduh untuk mulai mengunduh berkas!', - 'Peers': 'Peer', - 'More Info': 'Info Lengkap', - 'Remove': 'Hapus', - '# of': '# dari', - 'Length': 'Ukuran', -// modals - 'Add Downloads By URIs': 'Unduh dari URI', - '- You can add multiple downloads (files) at the same time by putting URIs for each file on a separate line.': - '- Anda dapat menambah banyak unduhan (berkas) sekali waktu dg menaruh URI setiap berkas dlm baris terpisah.', - '- You can also add multiple URIs (mirrors) for the *same* file. To do this, separate the URIs by a space.': - '- Anda juga dapat menambah banyak URI (cermin) untuk berkas yang *sama*. Pisahkan URI dengan spasi.', - '- A URI can be HTTP(S)/FTP/BitTorrent-Magnet.': '- URI dapat berbentuk HTTP(S)/FTP/BitTorrent-Magnet.', - 'Download settings': 'Pengaturan unduhan', - 'Advanced settings': 'Pengaturan mahir', - 'Cancel': 'Batal', - 'Start': 'Mulai', - 'Choose': 'Pilih', - 'Quick Access (shown on the main page)': 'Akses Cepat (terlihat di laman utama)', -// add torrent modal - 'Add Downloads By Torrents': 'Unduh dari Torrent', - '- Select the torrent from the local filesystem to start the download.': '- Pilih torrent dari sistem berkas lokal untuk mulai mengunduh.', - '- You can select multiple torrents to start multiple downloads.': 'Anda dapat memilih banyak torrent untuk memulai multi unduh.', - '- To add a BitTorrent-Magnet URL, use the Add By URI option and add it there.': 'Untuk menambah BitTorrent-Magnet URL, pakai opsi Tambah dari URI dan tambahkan di situ.', - 'Select Torrents': 'Pilih Torrent', - 'Select a Torrent': 'Pilih Torrent', -// add metalink modal - 'Add Downloads By Metalinks': 'Unduh dari Metalink', - 'Select Metalinks': 'Pilih Metalink', - '- Select the Metalink from the local filesystem to start the download.': '- Pilih Metalink dari sistem berkas lokal untuk mulai mengunduh.', - '- You can select multiple Metalinks to start multiple downloads.': '- Anda dapat memilih banyak Metalink untuk mulai multi unduh.', - 'Select a Metalink': 'Pilih Metalink', -// select file modal - 'Choose files to start download for': 'Pilih berkas untuk mulai mengunduh', - 'Select to download': 'Pilih untuk mengunduh', -// settings modal - 'Aria2 RPC host and port': 'Port dan host RPC Aria2', - 'Enter the host': 'Masukkan host', - 'Enter the IP or DNS name of the server on which the RPC for Aria2 is running (default: localhost)': - 'Masukkan IP atau nama DNS peladen tempat RPC Aria2 berjalan (asali: localhost)', - 'Enter the port': 'Masukkan porta', - 'Enter the port of the server on which the RPC for Aria2 is running (default: 6800)': - 'Masukkan porta peladen tempat RPC Aria2 berjalan (asali: 6800)', - 'Enter the RPC path': 'Masukkan path RPC', - 'Enter the path for the Aria2 RPC endpoint (default: /jsonrpc)': 'Masukkan path untuk endpoint RPC Aria2 (asali: /jsonrpc)', - 'SSL/TLS encryption': 'Enkripsi SSL/TLS', - 'Enable SSL/TLS encryption': 'Aktifkan enkripsi SSL/TLS', - 'Enter the secret token (optional)': 'Masukkan token rahasia (opsional)', - 'Enter the Aria2 RPC secret token (leave empty if authentication is not enabled)': - 'Masukkan token rahasia RPC Aria2 (kosongkan jika otentifikasi tidak aktif)', - 'Enter the username (optional)': 'Masukkan username (opsional)', - 'Enter the Aria2 RPC username (empty if authentication not enabled)': - 'Masukkan username RPC Aria2 (kosongkan jika otentifikasi tidak aktif)', - 'Enter the password (optional)': 'Masukkan kata sandi (opsional)', - 'Enter the Aria2 RPC password (empty if authentication not enabled)': 'Masukkan kata sandi RPC Aria2 (kosongkan jika otentifikasi tidak aktif)', - 'Enter base URL (optional)': 'Masukkan URL dasar (opsional)', - 'Direct Download': 'Unduh Langsung', - 'If supplied, links will be created to enable direct download from the Aria2 server.': - 'Jika tersedia, tautan akan dibuat untuk mengaktifkan unduhan langsung dari peladen Aria2.', - '(Requires appropriate webserver to be configured.)': '(Mewajibkan webserver yang perlu dikonfigurasi)', - 'Save Connection configuration': 'Simpan konfigurasi Koneksi', - 'Filter': 'Saring', -// server info modal - 'Aria2 server info': 'Info peladen Aria2', - 'Aria2 Version': 'Versi Aria2', - 'Features Enabled': 'Fitur yang Aktif', -// about modal - 'To download the latest version of the project, add issues or to contribute back, head on to': - 'Untuk mengunduh versi terkini proyek, tambahkan isu atau kontribusi balik ke', - 'Or you can open the latest version in the browser through': 'Atau Anda dapat membuka versi terkini via peramban lewat', - 'Close': 'Tutup', -// labels - 'Download status':'Status unduh', - 'Download Speed':'Kecepatan unduh', - 'Upload Speed':'Kecepatan unggah', - 'Estimated time':'Waktu estimasi', - 'Download Size':'Ukuran unduh', - 'Downloaded':'Terunduh', - 'Progress':'Proses', - 'Download Path':'Path unduh', - 'Uploaded':'Terunggah', - 'Download GID':'GID unduh', - 'Number of Pieces':'Jumlah Bagian', - 'Piece Length':'Ukuran Bagian', +translations.id_ID = { + // replace en_US to ll_CC, examples: zh_CN, de_AT. + // header + Search: "Telusuri", + // Nav menu + Add: "Tambah", + "By URIs": "Dari URI", + "By Torrents": "Dari Torrent", + "By Metalinks": "Dari Metalink", + Manage: "Kelola", + "Pause All": "Jeda Semua", + "Resume Paused": "Lanjut yang Dijeda", + "Purge Completed": "Hapus yang Terunduh", + "Shutdown Server": "Matikan Peladen", + Settings: "Pengaturan", + "Connection Settings": "Pengaturan Koneksi", + "Global Settings": "Pengaturan Global", + "Server info": "Info peladen", + "About and contribute": "Tentang dan kontribusi", + "Toggle navigation": "Alihkan navigasi", + // body + // nav side bar + Miscellaneous: "Lain-lain", + "Global Statistics": "Statistik Global", + About: "Tentang", + Displaying: "Tampilan", + of: "dari", + downloads: "unduhan", + Language: "Bahasa", + // download filters + "Download Filters": "Saring Unduhan", + Running: "Berjalan", + Active: "Aktif", + Waiting: "Menunggu", + Complete: "Selesai", + Error: "Galat", + Paused: "Dijeda", + Removed: "Dihapus", + "Hide linked meta-data": "Sembunyikan tautan meta-data", + Toggle: "Tombol alihan", + "Reset filters": "Reset penyaring", + // download status + Verifing: "Memverifikasi", + "Verify Pending": "Verifikasi Ditunda", + // starred properties + "Quick Access Settings": "Pengaturan Akses Cepat", + Save: "Simpan", + "Save settings": "Simpan pengaturan", + "Currently no download in line to display, use the": + "Sekarang tak ada unduhan yang ditampilkan, gunakan", + "download button to start downloading files!": "tombol unduh untuk mulai mengunduh berkas!", + Peers: "Peer", + "More Info": "Info Lengkap", + Remove: "Hapus", + "# of": "# dari", + Length: "Ukuran", + // modals + "Add Downloads By URIs": "Unduh dari URI", + "- You can add multiple downloads (files) at the same time by putting URIs for each file on a separate line.": + "- Anda dapat menambah banyak unduhan (berkas) sekali waktu dg menaruh URI setiap berkas dlm baris terpisah.", + "- You can also add multiple URIs (mirrors) for the *same* file. To do this, separate the URIs by a space.": + "- Anda juga dapat menambah banyak URI (cermin) untuk berkas yang *sama*. Pisahkan URI dengan spasi.", + "- A URI can be HTTP(S)/FTP/BitTorrent-Magnet.": + "- URI dapat berbentuk HTTP(S)/FTP/BitTorrent-Magnet.", + "Download settings": "Pengaturan unduhan", + "Advanced settings": "Pengaturan mahir", + Cancel: "Batal", + Start: "Mulai", + Choose: "Pilih", + "Quick Access (shown on the main page)": "Akses Cepat (terlihat di laman utama)", + // add torrent modal + "Add Downloads By Torrents": "Unduh dari Torrent", + "- Select the torrent from the local filesystem to start the download.": + "- Pilih torrent dari sistem berkas lokal untuk mulai mengunduh.", + "- You can select multiple torrents to start multiple downloads.": + "Anda dapat memilih banyak torrent untuk memulai multi unduh.", + "- To add a BitTorrent-Magnet URL, use the Add By URI option and add it there.": + "Untuk menambah BitTorrent-Magnet URL, pakai opsi Tambah dari URI dan tambahkan di situ.", + "Select Torrents": "Pilih Torrent", + "Select a Torrent": "Pilih Torrent", + // add metalink modal + "Add Downloads By Metalinks": "Unduh dari Metalink", + "Select Metalinks": "Pilih Metalink", + "- Select the Metalink from the local filesystem to start the download.": + "- Pilih Metalink dari sistem berkas lokal untuk mulai mengunduh.", + "- You can select multiple Metalinks to start multiple downloads.": + "- Anda dapat memilih banyak Metalink untuk mulai multi unduh.", + "Select a Metalink": "Pilih Metalink", + // select file modal + "Choose files to start download for": "Pilih berkas untuk mulai mengunduh", + "Select to download": "Pilih untuk mengunduh", + // settings modal + "Aria2 RPC host and port": "Port dan host RPC Aria2", + "Enter the host": "Masukkan host", + "Enter the IP or DNS name of the server on which the RPC for Aria2 is running (default: localhost)": + "Masukkan IP atau nama DNS peladen tempat RPC Aria2 berjalan (asali: localhost)", + "Enter the port": "Masukkan porta", + "Enter the port of the server on which the RPC for Aria2 is running (default: 6800)": + "Masukkan porta peladen tempat RPC Aria2 berjalan (asali: 6800)", + "Enter the RPC path": "Masukkan path RPC", + "Enter the path for the Aria2 RPC endpoint (default: /jsonrpc)": + "Masukkan path untuk endpoint RPC Aria2 (asali: /jsonrpc)", + "SSL/TLS encryption": "Enkripsi SSL/TLS", + "Enable SSL/TLS encryption": "Aktifkan enkripsi SSL/TLS", + "Enter the secret token (optional)": "Masukkan token rahasia (opsional)", + "Enter the Aria2 RPC secret token (leave empty if authentication is not enabled)": + "Masukkan token rahasia RPC Aria2 (kosongkan jika otentifikasi tidak aktif)", + "Enter the username (optional)": "Masukkan username (opsional)", + "Enter the Aria2 RPC username (empty if authentication not enabled)": + "Masukkan username RPC Aria2 (kosongkan jika otentifikasi tidak aktif)", + "Enter the password (optional)": "Masukkan kata sandi (opsional)", + "Enter the Aria2 RPC password (empty if authentication not enabled)": + "Masukkan kata sandi RPC Aria2 (kosongkan jika otentifikasi tidak aktif)", + "Enter base URL (optional)": "Masukkan URL dasar (opsional)", + "Direct Download": "Unduh Langsung", + "If supplied, links will be created to enable direct download from the Aria2 server.": + "Jika tersedia, tautan akan dibuat untuk mengaktifkan unduhan langsung dari peladen Aria2.", + "(Requires appropriate webserver to be configured.)": + "(Mewajibkan webserver yang perlu dikonfigurasi)", + "Save Connection configuration": "Simpan konfigurasi Koneksi", + Filter: "Saring", + // server info modal + "Aria2 server info": "Info peladen Aria2", + "Aria2 Version": "Versi Aria2", + "Features Enabled": "Fitur yang Aktif", + // about modal + "To download the latest version of the project, add issues or to contribute back, head on to": + "Untuk mengunduh versi terkini proyek, tambahkan isu atau kontribusi balik ke", + "Or you can open the latest version in the browser through": + "Atau Anda dapat membuka versi terkini via peramban lewat", + Close: "Tutup", + // labels + "Download status": "Status unduh", + "Download Speed": "Kecepatan unduh", + "Upload Speed": "Kecepatan unggah", + "Estimated time": "Waktu estimasi", + "Download Size": "Ukuran unduh", + Downloaded: "Terunduh", + Progress: "Proses", + "Download Path": "Path unduh", + Uploaded: "Terunggah", + "Download GID": "GID unduh", + "Number of Pieces": "Jumlah Bagian", + "Piece Length": "Ukuran Bagian", -//alerts - 'The last connection attempt was unsuccessful. Trying another configuration': - 'Usaha koneksi terakhir gagal. Coba konfigurasi lain', - 'Oh Snap!': 'Oh Sial!', - 'Could not connect to the aria2 RPC server. Will retry in 10 secs. You might want to check the connection settings by going to Settings > Connection Settings': - 'Tak dapat terkoneksi ke peladen RPC aria2. Akan diulang dalam 10 detik. Anda mungkin ingin menguji pengaturan koneksi melalui Pengaturan > Pengaturan Koneksi', - 'Authentication failed while connecting to Aria2 RPC server. Will retry in 10 secs. You might want to confirm your authentication details by going to Settings > Connection Settings': - 'Otentifikasi gagal saat membuka koneksi ke peladen RPC Aria2. Akan diulang dalam 10 detik. Anda mungkin ingin mengonfirmasi detail otentifikasi di Pengaturan > Pengaturan Koneksi', - 'Successfully connected to Aria2 through its remote RPC …': - 'Sukses terkoneksi ke Aria2 melalui remot RPC …', - 'Successfully connected to Aria2 through remote RPC, however the connection is still insecure. For complete security try adding an authorization secret token while starting Aria2 (through the flag --rpc-secret)': - 'Sukses terkoneksi ke Aria2 melalui remot RPC, bagaimanapun koneksi masih tidak aman. Untuk melengkapi keamanan coba tambahkan token rahasia otorisasi saat memulai Aria2 (lewat flag --rpc-secret)', - 'Trying to connect to aria2 using the new connection configuration': - 'Mencoba koneksi ke aria2 menggunakan konfigurasi koneksi baru', - 'Remove {{name}} and associated meta-data?': // {{name}} refers to the download name, do not modify. - 'Hapus {{name}} dan meta-data yang berhubungan?' + //alerts + "The last connection attempt was unsuccessful. Trying another configuration": + "Usaha koneksi terakhir gagal. Coba konfigurasi lain", + "Oh Snap!": "Oh Sial!", + "Could not connect to the aria2 RPC server. Will retry in 10 secs. You might want to check the connection settings by going to Settings > Connection Settings": + "Tak dapat terkoneksi ke peladen RPC aria2. Akan diulang dalam 10 detik. Anda mungkin ingin menguji pengaturan koneksi melalui Pengaturan > Pengaturan Koneksi", + "Authentication failed while connecting to Aria2 RPC server. Will retry in 10 secs. You might want to confirm your authentication details by going to Settings > Connection Settings": + "Otentifikasi gagal saat membuka koneksi ke peladen RPC Aria2. Akan diulang dalam 10 detik. Anda mungkin ingin mengonfirmasi detail otentifikasi di Pengaturan > Pengaturan Koneksi", + "Successfully connected to Aria2 through its remote RPC …": + "Sukses terkoneksi ke Aria2 melalui remot RPC …", + "Successfully connected to Aria2 through remote RPC, however the connection is still insecure. For complete security try adding an authorization secret token while starting Aria2 (through the flag --rpc-secret)": + "Sukses terkoneksi ke Aria2 melalui remot RPC, bagaimanapun koneksi masih tidak aman. Untuk melengkapi keamanan coba tambahkan token rahasia otorisasi saat memulai Aria2 (lewat flag --rpc-secret)", + "Trying to connect to aria2 using the new connection configuration": + "Mencoba koneksi ke aria2 menggunakan konfigurasi koneksi baru", + // {{name}} refers to the download name, do not modify. + "Remove {{name}} and associated meta-data?": "Hapus {{name}} dan meta-data yang berhubungan?" }; diff --git a/js/translate/it_IT.js b/js/translate/it_IT.js index d2a4584f..ad70198d 100644 --- a/js/translate/it_IT.js +++ b/js/translate/it_IT.js @@ -1,140 +1,156 @@ -if(typeof translations == 'undefined'){ - translations = {}; +if (typeof translations == "undefined") { + translations = {}; } translations.it_IT = { -// header - 'Search': 'Cerca', - // Nav menu - 'Add': 'Aggiungi', - 'By URIs': 'Da URIs', - 'By Torrents': 'Da Torrent', - 'By Metalinks': 'Da Metalink', - 'Manage': 'Gestione', - 'Pause All': 'Ferma tutto', - 'Resume Paused': 'Riprendi fermati', - 'Purge Completed': 'Togli i completi', - 'Settings': 'Impostazioni', - 'Connection Settings': 'Impostazioni di connessione', - 'Global Settings': 'Impostazioni globali', - 'Server info': 'Informazioni sul server', - 'About and contribute': 'Crediti e informazioni', - 'Toggle navigation': 'Cambia navigazione', -// body -// nav side bar - 'Miscellaneous': 'Varie', - 'Global Statistics': 'Statistiche globali', - 'About': 'Info', - 'Displaying': 'Mostra', - 'of': 'di', - 'downloads': 'downloads', - 'Language': 'Lingua', -// download filters - 'Download Filters': 'Filtri download', - 'Running': 'In corso', - 'Active': 'Attivi', - 'Waiting': 'In attesa', - 'Complete': 'Completi', - 'Error': 'Errore', - 'Paused': 'In pausa', - 'Removed': 'Rimossi', - 'Hide linked meta-data': 'Nascondi i meta-data collegati', - 'Toggle': 'Cambia', - 'Reset filters': 'Reimposta filtri', -// starred properties - 'Quick Access Settings': 'Accesso rapido', - 'Save settings': 'Salva impostazioni', - 'Currently no download in line to display, use the': 'Attualmente non c\'è nessun download da mostrare, usa il pulsante ', - 'download button to start downloading files!': 'dowload per cominciare a scaricare!', - 'Peers': 'Peers', - 'More Info': 'Altre informazioni', - 'Remove': 'Rimuovi', - '# of': '# di', - 'Length': 'Lunghezza', -// modals - 'Add Downloads By URIs': 'Aggiungi Downloads da URIs', - '- You can add multiple downloads (files) at the same time by putting URIs for each file on a separate line.': - '- Puoi aggungere più download(files) allo stesso tempo mettendo un\'URI per riga.', - '- You can also add multiple URIs (mirrors) for the *same* file. To do this, separate the URIs by a space.': - '- Puoi anche aggiungere più URI di download(mirror) per uno *stesso* file separando i vari mirror da uno spazio.', - '- A URI can be HTTP(S)/FTP/BitTorrent-Magnet.': '- Un URI può essere un indirizzo HTTP(S)/FTP o un BitTorrent Magnet link.', - 'Download settings': 'Impostazioni download', - 'Advanced settings': 'Impostazioni avanzate', - 'Cancel': 'Cancella', - 'Start': 'Aggiungi', - 'Choose': 'Scegli', - 'Quick Access (shown on the main page)': 'Accesso rapido (mostrato nella pagina principale)', -// add torrent modal - 'Add Downloads By Torrents': 'Aggiungi Torrent', - '- Select the torrent from the local filesystem to start the download.': '- Seleziona il file torrent dal tuo computer per iniziare a scaricare.', - '- You can select multiple torrents to start multiple downloads.': '- Puoi aggiungere anche più file contemporaneamente per iniziare più dowload insieme.', - '- To add a BitTorrent-Magnet URL, use the Add By URI option and add it there.': '- Per aggiungere un Magnet Link BitTorrent utilizza l\'opzione Aggiungi da URI.', - 'Select Torrents': 'Seleziona Torrents', - 'Select a Torrent': 'Seleziona un Torrent', -// add metalink modal - 'Add Downloads By Metalinks': 'Aggiungi Torrent da Metalink', - 'Select Metalinks': 'Seleziona Metalink', - '- Select the Metalink from the local filesystem to start the download.': '- Seleziona un Metalink dal tuo computer per iniziare il download.', - '- You can select multiple Metalinks to start multiple downloads.': '- Puoi iniziare anche più download selezionando più Metalink.', - 'Select a Metalink': 'Seleziona un Metalink', -// select file modal - 'Choose files to start download for': 'Scegli i file da scaricare', - 'Select to download': 'Seleziona per scaricare', -// settings modal - 'Aria2 RPC host and port': 'Host e porta del server RPC di Aria2', - 'Enter the host': 'Inserisci l\'host', - 'Enter the IP or DNS name of the server on which the RPC for Aria2 is running (default: localhost)': - 'Inserisci l\'IP o il nome DNS del server dov\'è in esecuzione l\'RPC per Aria2 (default: localhost)', - 'Enter the port': 'Inserisci la porta', - 'Enter the port of the server on which the RPC for Aria2 is running (default: 6800)': - 'Inserisci la porta del server dov\'è in esecuzione l\'RPC per Aria2 (default: 6800)', - 'Enter the RPC path': 'Inserisci la path RPC', - 'Enter the path for the Aria2 RPC endpoint (default: /jsonrpc)': 'Inserisci la path per l\'endpoint RPC di Aria2 (default: /jsonrpc)', - 'SSL/TLS encryption': 'Cifratura SSL/TLS', - 'Enable SSL/TLS encryption': 'Abilita la cifratura SSL/TLS', - 'Enter the secret token (optional)': 'Inserisci il token segreto (opzionale)', - 'Enter the Aria2 RPC secret token (leave empty if authentication is not enabled)': - 'Inserisci il token segreto per Aria2 (lascia vuoto se non è abilitato)', - 'Enter the username (optional)': 'Inserisci l\'username (opzionale)', - 'Enter the Aria2 RPC username (empty if authentication not enabled)': - 'Inserisci l\'username per l\'RPC di Aria2 (lascia vuoto se non è abilitato)', - 'Enter the password (optional)': 'Inserisci la password (opzionale)', - 'Enter the Aria2 RPC password (empty if authentication not enabled)': 'Inserisci la password per l\'RPC di Aria2 (vuota se l\'autenticazione non è abilitata)', - 'Enter base URL (optional)': 'Inserisci l\'URL di base(opzionale)', - 'Direct Download': 'Downaload diretto', - 'If supplied, links will be created to enable direct download from the Aria2 server.': - 'Se inserito, verrano creati dei link per scaricare direttamente i file dal server Aria2.', - '(Requires appropriate webserver to be configured.)': '(Richiede un webserver correttamente configurato)', - 'Save Connection configuration': 'Salva la configurazione di connessione', - 'Filter': 'Filtro', -// server info modal - 'Aria2 server info': 'Informazioni sul server Aria2', - 'Aria2 Version': 'Versione di Aria2', - 'Features Enabled': 'Funzionalità abilitate', -// about modal - 'To download the latest version of the project, add issues or to contribute back, head on to': - 'Per scaricare l\'ultima versione del progetto, aggiungere problemi o contribuire, visita ', - 'Or you can open the latest version in the browser through': 'Oppure puoi aprire l\'ultima versione direttamente nel browser', - 'Close': 'Chiudi', -// lables - 'Download status':'Stato download', - 'Download Speed':'Velocità download', - 'Upload Speed':'Velocità upload', - 'Estimated time':'Tempo stimato', - 'Download Size':'Dimensione del download', - 'Downloaded':'Scaricato', - 'Progress':'Progresso', - 'Download Path':'Percorso di download', - 'Uploaded':'Caricato', - 'Download GID':'GID Download', - 'Number of Pieces':'Numero di segmenti', - 'Piece Length': 'Lunghezza segmenti', - 'Shutdown Server': 'Spegni Server', + // header + Search: "Cerca", + // Nav menu + Add: "Aggiungi", + "By URIs": "Da URIs", + "By Torrents": "Da Torrent", + "By Metalinks": "Da Metalink", + Manage: "Gestione", + "Pause All": "Ferma tutto", + "Resume Paused": "Riprendi fermati", + "Purge Completed": "Togli i completi", + Settings: "Impostazioni", + "Connection Settings": "Impostazioni di connessione", + "Global Settings": "Impostazioni globali", + "Server info": "Informazioni sul server", + "About and contribute": "Crediti e informazioni", + "Toggle navigation": "Cambia navigazione", + // body + // nav side bar + Miscellaneous: "Varie", + "Global Statistics": "Statistiche globali", + About: "Info", + Displaying: "Mostra", + of: "di", + downloads: "downloads", + Language: "Lingua", + // download filters + "Download Filters": "Filtri download", + Running: "In corso", + Active: "Attivi", + Waiting: "In attesa", + Complete: "Completi", + Error: "Errore", + Paused: "In pausa", + Removed: "Rimossi", + "Hide linked meta-data": "Nascondi i meta-data collegati", + Toggle: "Cambia", + "Reset filters": "Reimposta filtri", + // starred properties + "Quick Access Settings": "Accesso rapido", + "Save settings": "Salva impostazioni", + "Currently no download in line to display, use the": + "Attualmente non c'è nessun download da mostrare, usa il pulsante ", + "download button to start downloading files!": "dowload per cominciare a scaricare!", + Peers: "Peers", + "More Info": "Altre informazioni", + Remove: "Rimuovi", + "# of": "# di", + Length: "Lunghezza", + // modals + "Add Downloads By URIs": "Aggiungi Downloads da URIs", + "- You can add multiple downloads (files) at the same time by putting URIs for each file on a separate line.": + "- Puoi aggungere più download(files) allo stesso tempo mettendo un'URI per riga.", + "- You can also add multiple URIs (mirrors) for the *same* file. To do this, separate the URIs by a space.": + "- Puoi anche aggiungere più URI di download(mirror) per uno *stesso* file separando i vari mirror da uno spazio.", + "- A URI can be HTTP(S)/FTP/BitTorrent-Magnet.": + "- Un URI può essere un indirizzo HTTP(S)/FTP o un BitTorrent Magnet link.", + "Download settings": "Impostazioni download", + "Advanced settings": "Impostazioni avanzate", + Cancel: "Cancella", + Start: "Aggiungi", + Choose: "Scegli", + "Quick Access (shown on the main page)": "Accesso rapido (mostrato nella pagina principale)", + // add torrent modal + "Add Downloads By Torrents": "Aggiungi Torrent", + "- Select the torrent from the local filesystem to start the download.": + "- Seleziona il file torrent dal tuo computer per iniziare a scaricare.", + "- You can select multiple torrents to start multiple downloads.": + "- Puoi aggiungere anche più file contemporaneamente per iniziare più dowload insieme.", + "- To add a BitTorrent-Magnet URL, use the Add By URI option and add it there.": + "- Per aggiungere un Magnet Link BitTorrent utilizza l'opzione Aggiungi da URI.", + "Select Torrents": "Seleziona Torrents", + "Select a Torrent": "Seleziona un Torrent", + // add metalink modal + "Add Downloads By Metalinks": "Aggiungi Torrent da Metalink", + "Select Metalinks": "Seleziona Metalink", + "- Select the Metalink from the local filesystem to start the download.": + "- Seleziona un Metalink dal tuo computer per iniziare il download.", + "- You can select multiple Metalinks to start multiple downloads.": + "- Puoi iniziare anche più download selezionando più Metalink.", + "Select a Metalink": "Seleziona un Metalink", + // select file modal + "Choose files to start download for": "Scegli i file da scaricare", + "Select to download": "Seleziona per scaricare", + // settings modal + "Aria2 RPC host and port": "Host e porta del server RPC di Aria2", + "Enter the host": "Inserisci l'host", + "Enter the IP or DNS name of the server on which the RPC for Aria2 is running (default: localhost)": + "Inserisci l'IP o il nome DNS del server dov'è in esecuzione l'RPC per Aria2 (default: localhost)", + "Enter the port": "Inserisci la porta", + "Enter the port of the server on which the RPC for Aria2 is running (default: 6800)": + "Inserisci la porta del server dov'è in esecuzione l'RPC per Aria2 (default: 6800)", + "Enter the RPC path": "Inserisci la path RPC", + "Enter the path for the Aria2 RPC endpoint (default: /jsonrpc)": + "Inserisci la path per l'endpoint RPC di Aria2 (default: /jsonrpc)", + "SSL/TLS encryption": "Cifratura SSL/TLS", + "Enable SSL/TLS encryption": "Abilita la cifratura SSL/TLS", + "Enter the secret token (optional)": "Inserisci il token segreto (opzionale)", + "Enter the Aria2 RPC secret token (leave empty if authentication is not enabled)": + "Inserisci il token segreto per Aria2 (lascia vuoto se non è abilitato)", + "Enter the username (optional)": "Inserisci l'username (opzionale)", + "Enter the Aria2 RPC username (empty if authentication not enabled)": + "Inserisci l'username per l'RPC di Aria2 (lascia vuoto se non è abilitato)", + "Enter the password (optional)": "Inserisci la password (opzionale)", + "Enter the Aria2 RPC password (empty if authentication not enabled)": + "Inserisci la password per l'RPC di Aria2 (vuota se l'autenticazione non è abilitata)", + "Enter base URL (optional)": "Inserisci l'URL di base(opzionale)", + "Direct Download": "Downaload diretto", + "If supplied, links will be created to enable direct download from the Aria2 server.": + "Se inserito, verrano creati dei link per scaricare direttamente i file dal server Aria2.", + "(Requires appropriate webserver to be configured.)": + "(Richiede un webserver correttamente configurato)", + "Save Connection configuration": "Salva la configurazione di connessione", + Filter: "Filtro", + // server info modal + "Aria2 server info": "Informazioni sul server Aria2", + "Aria2 Version": "Versione di Aria2", + "Features Enabled": "Funzionalità abilitate", + // about modal + "To download the latest version of the project, add issues or to contribute back, head on to": + "Per scaricare l'ultima versione del progetto, aggiungere problemi o contribuire, visita ", + "Or you can open the latest version in the browser through": + "Oppure puoi aprire l'ultima versione direttamente nel browser", + Close: "Chiudi", + // lables + "Download status": "Stato download", + "Download Speed": "Velocità download", + "Upload Speed": "Velocità upload", + "Estimated time": "Tempo stimato", + "Download Size": "Dimensione del download", + Downloaded: "Scaricato", + Progress: "Progresso", + "Download Path": "Percorso di download", + Uploaded: "Caricato", + "Download GID": "GID Download", + "Number of Pieces": "Numero di segmenti", + "Piece Length": "Lunghezza segmenti", + "Shutdown Server": "Spegni Server", - 'The last connection attempt was unsuccessful. Trying another configuration': 'L\'ultimo tentativo di connessione non è riuscito. Provo un\'altra connessione', - 'Oh Snap!': 'Mannaggia!', - 'Could not connect to the aria2 RPC server. Will retry in 10 secs. You might want to check the connection settings by going to Settings > Connection Settings': 'Non riesco a connettermi al server RPC di Aria2. Riprovo tra 10 secondi. Forse vuoi controllare le impostazioni di connessione in Impostazioni > Impostazioni di connessione', - 'Successfully connected to Aria2 through its remote RPC …': 'Connesso con successo a Aria2 mediante RPC remoto …', - 'Successfully connected to Aria2 through remote RPC, however the connection is still insecure. For complete security try adding an authorization secret token while starting Aria2 (through the flag --rpc-secret)': 'Correttamente connesso al server Aria2 mediante RPC, ma in modo non sicuro. Per una completa sicurezza prova ad aggiungere un token di autorizzazione segreto all\'avvio di Aria2 (mediante il flag --rpc-secret)', - 'Trying to connect to aria2 using the new connection configuration': 'Provo a connettermi a Aria2 attraverso le nuove impostazioni', + "The last connection attempt was unsuccessful. Trying another configuration": + "L'ultimo tentativo di connessione non è riuscito. Provo un'altra connessione", + "Oh Snap!": "Mannaggia!", + "Could not connect to the aria2 RPC server. Will retry in 10 secs. You might want to check the connection settings by going to Settings > Connection Settings": + "Non riesco a connettermi al server RPC di Aria2. Riprovo tra 10 secondi. Forse vuoi controllare le impostazioni di connessione in Impostazioni > Impostazioni di connessione", + "Successfully connected to Aria2 through its remote RPC …": + "Connesso con successo a Aria2 mediante RPC remoto …", + "Successfully connected to Aria2 through remote RPC, however the connection is still insecure. For complete security try adding an authorization secret token while starting Aria2 (through the flag --rpc-secret)": + "Correttamente connesso al server Aria2 mediante RPC, ma in modo non sicuro. Per una completa sicurezza prova ad aggiungere un token di autorizzazione segreto all'avvio di Aria2 (mediante il flag --rpc-secret)", + "Trying to connect to aria2 using the new connection configuration": + "Provo a connettermi a Aria2 attraverso le nuove impostazioni" }; diff --git a/js/translate/nl_NL.js b/js/translate/nl_NL.js index 7b14985f..e3ae86f1 100644 --- a/js/translate/nl_NL.js +++ b/js/translate/nl_NL.js @@ -1,119 +1,130 @@ -if(typeof translations == 'undefined'){ - translations = {}; +if (typeof translations == "undefined") { + translations = {}; } translations.nl_NL = { -// header - 'Search': 'Zoeken', - // Nav menu - 'Add': 'Toevoegen', - 'By URIs': 'met URI', - 'By Torrents': 'met Torrents', - 'By Metalinks': 'met Metalinks', - 'Manage': 'Beheren', - 'Pause All': 'Alles pauzeren', - 'Resume Paused': 'Hervatten', - 'Purge Completed': 'Verwijder de voleindigden', - 'Settings': 'Instellingen', - 'Connection Settings': 'Verbindingsinstellingen', - 'Global Settings': 'Globale instellingen', - 'Server info': 'Informatie over de server', - 'About and contribute': 'Over het project en bijdragen', - 'Toggle navigation': 'Navigatie omschakelen', - 'Language': 'Taal', -// body -// nav side bar - 'Miscellaneous': 'Overig', - 'Global Statistics': 'Globale statistieken', - 'About': 'Over het project', - 'Displaying': ' ', // empty because of grammar in the following 2 elements - 'of': 'van', - 'downloads': 'downloads weergegeven', -// download filters - 'Download Filters': 'Download filters', - 'Running': 'Bezig', - 'Active': 'Actief', - 'Waiting': 'Wachtend', - 'Complete': 'Voleindigd', - 'Error': 'Foutief', - 'Paused': 'Gepauzeerd', - 'Removed': 'Verwijderd', - 'Hide linked meta-data': 'Gekoppelde metadata verbergen', - 'Toggle': 'Omschakelen', - 'Reset filters': 'Filters terugzetten', -// starred properties - 'Quick Access Settings': 'Snelle-toegang instellingen', - 'Save settings': 'Instellingen opslaan', - 'Currently no download in line to display, use the': 'Momenteel geen downloads weer te geven, gebruik de ', - 'download button to start downloading files!': 'knop om bestanden te gaan downloaden!', - 'Peers': 'Peers', - 'More Info': 'Meer informatie', - 'Remove': 'Verwijderen', - '# of': 'Aantal', - 'Length': 'Lengte', -// modals - 'Add Downloads By URIs': 'Downloads toevoegen met URI', - '- You can add multiple downloads (files) at the same time by putting URIs for each file on a separate line.': - '- Je kunt meerdere downloads (bestanden) tezelfdertijd toevoegen door de URIs voor elk bestand op een aparte regel te zetten.', - '- You can also add multiple URIs (mirrors) for the *same* file. To do this, separate the URIs by a space.': - '- Je kunt ook meerdere URIs (mirrors) voor *hetzelfde* bestand toevoegen. Scheidt hiervoor de URIs met een spatie.', - '- A URI can be HTTP(S)/FTP/BitTorrent-Magnet.': '- Een URI kan HTTP(S)/FTP/BitTorrent-Magnet zijn.', - 'Download settings': 'Download instellingen', - 'Advanced settings': 'Geavanceerde instellingen', - 'Cancel': 'Annuleren', - 'Start': 'Starten', - 'Choose': 'Kiezen', - 'Quick Access (shown on the main page)': 'Snelle toegang (op de hoofdpagina)', -// add torrent modal - 'Add Downloads By Torrents': 'Downloads toevoegen met torrents', - '- Select the torrent from the local filesystem to start the download.': '- Selecteer de torrent van het locale bestandssysteem om de download te starten.', - '- You can select multiple torrents to start multiple downloads.': '- Je kunt meerdere torrents selecteren voor meerdere downloads.', - '- To add a BitTorrent-Magnet URL, use the Add By URI option and add it there.': '- Om een BitTorrent-Magnet URL toe te voegen, gebruik de Toevoegen met URI optie, en voeg het daar toe.', - 'Select Torrents': 'Selecteer torrents', - 'Select a Torrent': 'Selecteer een torrent', -// add metalink modal - 'Add Downloads By Metalinks': 'Download toevoegen met Metalinks', - 'Select Metalinks': 'Selecteer Metalinks', - '- Select the Metalink from the local filesystem to start the download.': '- Selecteer de Metalink van het locale bestandssysteem om de download te starten.', - '- You can select multiple Metalinks to start multiple downloads.': '- Selecter meerdere Metalinks om meerdere downloads te starten.', - 'Select a Metalink': 'Selecteer een Metalink', -// select file modal - 'Choose files to start download for': 'Bestanden kiezen waarvoor het downloaden beginnen moet', - 'Select to download': 'Selecteer om te downloaden', -// settings modal - 'Aria2 RPC host and port': 'Aria2 RPC server en poort', - 'Enter the host': 'Server invoeren', - 'Enter the IP or DNS name of the server on which the RPC for Aria2 is running (default: localhost)': - 'Voer de IP of DNS naam van de server waarop de RPC van Aria2 loopt (standaard: localhost)', - 'Enter the port': 'Poort invoeren', - 'Enter the port of the server on which the RPC for Aria2 is running (default: 6800)': - 'Invoeren van de serverpoort waarop de RPC van Aria2 loopt (standaard: 6800)', - 'Enter the RPC path': 'Invoeren van het RPC pad', - 'Enter the path for the Aria2 RPC endpoint (default: /jsonrpc)': 'Invoeren van het eindpunt van het Aria2 RPC pad (standaard: /jsonrpc)', - 'SSL/TLS encryption': 'SSL/TLS versleuteling', - 'Enable SSL/TLS encryption': 'SSL/TLS versleuteling inschakelen', - 'Enter the secret token (optional)': 'Invoeren van het wachtwoord (facultatief)', - 'Enter the Aria2 RPC secret token (leave empty if authentication is not enabled)': - 'Invoeren van het Aria2 RPC wachtwoord (niet invullen als authenticatie niet is ingeschakeld)', - 'Enter the username (optional)': 'Invoeren van de gebruikersnaam (facultatief)', - 'Enter the Aria2 RPC username (empty if authentication not enabled)': - 'Invoeren van de Aria2 RPC gebruikersnaam (niet invullen als authenticatie niet is ingeschakeld)', - 'Enter the password (optional)': 'Invoeren van het wachtwoord (facultatief)', - 'Enter the Aria2 RPC password (empty if authentication not enabled)': 'Invoeren van het Aria2 RPC wachtwoord (niet invullen als authenticatie niet is ingeschakeld)', - 'Enter base URL (optional)': 'Invoeren van de basis URL (facultatief)', - 'Direct Download': 'Direct downloaden', - 'If supplied, links will be created to enable direct download from the Aria2 server.': - 'Als ingevoerd dan worden links aangemaakt die het direct downloaden van de Aria2 server toestaan.', - '(Requires appropriate webserver to be configurured.)': 'Hiervoor moet een geschikte webserver worden ingericht.)', - 'Save Connection configuration': 'Verbindingsconfiguratie opslaan', - 'Filter': 'Filter', -// server info modal - 'Aria2 server info': 'Aria2 server informatie', - 'Aria2 Version': 'Aria2 versie', - 'Features Enabled': 'Geactiveerde kenmerken', -// about modal - 'To download the latest version of the project, add issues or to contribute back, head on to': - 'Om de nieuwste versie van het project te downloaden, problemen te rapporteren of bij te dragen, ga naar', - 'Or you can open the latest version in the browser through': 'Of je kunt hier de nieuwste versie in je browser openen', - 'Close': 'Afsluiten', + // header + Search: "Zoeken", + // Nav menu + Add: "Toevoegen", + "By URIs": "met URI", + "By Torrents": "met Torrents", + "By Metalinks": "met Metalinks", + Manage: "Beheren", + "Pause All": "Alles pauzeren", + "Resume Paused": "Hervatten", + "Purge Completed": "Verwijder de voleindigden", + Settings: "Instellingen", + "Connection Settings": "Verbindingsinstellingen", + "Global Settings": "Globale instellingen", + "Server info": "Informatie over de server", + "About and contribute": "Over het project en bijdragen", + "Toggle navigation": "Navigatie omschakelen", + Language: "Taal", + // body + // nav side bar + Miscellaneous: "Overig", + "Global Statistics": "Globale statistieken", + About: "Over het project", + Displaying: " ", // empty because of grammar in the following 2 elements + of: "van", + downloads: "downloads weergegeven", + // download filters + "Download Filters": "Download filters", + Running: "Bezig", + Active: "Actief", + Waiting: "Wachtend", + Complete: "Voleindigd", + Error: "Foutief", + Paused: "Gepauzeerd", + Removed: "Verwijderd", + "Hide linked meta-data": "Gekoppelde metadata verbergen", + Toggle: "Omschakelen", + "Reset filters": "Filters terugzetten", + // starred properties + "Quick Access Settings": "Snelle-toegang instellingen", + "Save settings": "Instellingen opslaan", + "Currently no download in line to display, use the": + "Momenteel geen downloads weer te geven, gebruik de ", + "download button to start downloading files!": "knop om bestanden te gaan downloaden!", + Peers: "Peers", + "More Info": "Meer informatie", + Remove: "Verwijderen", + "# of": "Aantal", + Length: "Lengte", + // modals + "Add Downloads By URIs": "Downloads toevoegen met URI", + "- You can add multiple downloads (files) at the same time by putting URIs for each file on a separate line.": + "- Je kunt meerdere downloads (bestanden) tezelfdertijd toevoegen door de URIs voor elk bestand op een aparte regel te zetten.", + "- You can also add multiple URIs (mirrors) for the *same* file. To do this, separate the URIs by a space.": + "- Je kunt ook meerdere URIs (mirrors) voor *hetzelfde* bestand toevoegen. Scheidt hiervoor de URIs met een spatie.", + "- A URI can be HTTP(S)/FTP/BitTorrent-Magnet.": + "- Een URI kan HTTP(S)/FTP/BitTorrent-Magnet zijn.", + "Download settings": "Download instellingen", + "Advanced settings": "Geavanceerde instellingen", + Cancel: "Annuleren", + Start: "Starten", + Choose: "Kiezen", + "Quick Access (shown on the main page)": "Snelle toegang (op de hoofdpagina)", + // add torrent modal + "Add Downloads By Torrents": "Downloads toevoegen met torrents", + "- Select the torrent from the local filesystem to start the download.": + "- Selecteer de torrent van het locale bestandssysteem om de download te starten.", + "- You can select multiple torrents to start multiple downloads.": + "- Je kunt meerdere torrents selecteren voor meerdere downloads.", + "- To add a BitTorrent-Magnet URL, use the Add By URI option and add it there.": + "- Om een BitTorrent-Magnet URL toe te voegen, gebruik de Toevoegen met URI optie, en voeg het daar toe.", + "Select Torrents": "Selecteer torrents", + "Select a Torrent": "Selecteer een torrent", + // add metalink modal + "Add Downloads By Metalinks": "Download toevoegen met Metalinks", + "Select Metalinks": "Selecteer Metalinks", + "- Select the Metalink from the local filesystem to start the download.": + "- Selecteer de Metalink van het locale bestandssysteem om de download te starten.", + "- You can select multiple Metalinks to start multiple downloads.": + "- Selecter meerdere Metalinks om meerdere downloads te starten.", + "Select a Metalink": "Selecteer een Metalink", + // select file modal + "Choose files to start download for": "Bestanden kiezen waarvoor het downloaden beginnen moet", + "Select to download": "Selecteer om te downloaden", + // settings modal + "Aria2 RPC host and port": "Aria2 RPC server en poort", + "Enter the host": "Server invoeren", + "Enter the IP or DNS name of the server on which the RPC for Aria2 is running (default: localhost)": + "Voer de IP of DNS naam van de server waarop de RPC van Aria2 loopt (standaard: localhost)", + "Enter the port": "Poort invoeren", + "Enter the port of the server on which the RPC for Aria2 is running (default: 6800)": + "Invoeren van de serverpoort waarop de RPC van Aria2 loopt (standaard: 6800)", + "Enter the RPC path": "Invoeren van het RPC pad", + "Enter the path for the Aria2 RPC endpoint (default: /jsonrpc)": + "Invoeren van het eindpunt van het Aria2 RPC pad (standaard: /jsonrpc)", + "SSL/TLS encryption": "SSL/TLS versleuteling", + "Enable SSL/TLS encryption": "SSL/TLS versleuteling inschakelen", + "Enter the secret token (optional)": "Invoeren van het wachtwoord (facultatief)", + "Enter the Aria2 RPC secret token (leave empty if authentication is not enabled)": + "Invoeren van het Aria2 RPC wachtwoord (niet invullen als authenticatie niet is ingeschakeld)", + "Enter the username (optional)": "Invoeren van de gebruikersnaam (facultatief)", + "Enter the Aria2 RPC username (empty if authentication not enabled)": + "Invoeren van de Aria2 RPC gebruikersnaam (niet invullen als authenticatie niet is ingeschakeld)", + "Enter the password (optional)": "Invoeren van het wachtwoord (facultatief)", + "Enter the Aria2 RPC password (empty if authentication not enabled)": + "Invoeren van het Aria2 RPC wachtwoord (niet invullen als authenticatie niet is ingeschakeld)", + "Enter base URL (optional)": "Invoeren van de basis URL (facultatief)", + "Direct Download": "Direct downloaden", + "If supplied, links will be created to enable direct download from the Aria2 server.": + "Als ingevoerd dan worden links aangemaakt die het direct downloaden van de Aria2 server toestaan.", + "(Requires appropriate webserver to be configurured.)": + "Hiervoor moet een geschikte webserver worden ingericht.)", + "Save Connection configuration": "Verbindingsconfiguratie opslaan", + Filter: "Filter", + // server info modal + "Aria2 server info": "Aria2 server informatie", + "Aria2 Version": "Aria2 versie", + "Features Enabled": "Geactiveerde kenmerken", + // about modal + "To download the latest version of the project, add issues or to contribute back, head on to": + "Om de nieuwste versie van het project te downloaden, problemen te rapporteren of bij te dragen, ga naar", + "Or you can open the latest version in the browser through": + "Of je kunt hier de nieuwste versie in je browser openen", + Close: "Afsluiten" }; diff --git a/js/translate/pl_PL.js b/js/translate/pl_PL.js index 2105d073..b9338399 100644 --- a/js/translate/pl_PL.js +++ b/js/translate/pl_PL.js @@ -1,131 +1,154 @@ -if (typeof translations == 'undefined'){ - translations = {}; +if (typeof translations == "undefined") { + translations = {}; } translations.pl_PL = { -// header - 'Search': 'Szukaj', - // Nav menu - 'Add': 'Dodaj', - 'By URIs': 'Przez URL', - 'By Torrents': 'Przez Torrenty', - 'By Metalinks': 'Przez Metalinki', - 'Manage': 'Zarządzaj', - 'Pause All': 'Zatrzymaj wszystkie', - 'Resume Paused': 'Wznów zatrzymane', - 'Purge Completed': 'Czyść zakończone', - 'Settings': 'Ustawienia', - 'Connection Settings': 'Ustawienia połączenia', - 'Global Settings': 'Ustawienia globalne', - 'Server info': 'Informacje o serwerze', - 'About and contribute': 'O projekcie', - 'Toggle navigation': 'Przełącz nawigację', -// body -// nav side bar - 'Miscellaneous': 'Różne', - 'Global Statistics': 'Statystyki globalne', - 'About': 'O', - 'Displaying': 'Wyświetlanie', - 'of': 'z', - 'downloads': 'pobranych plików', - 'Language': 'Język', -// download filters - 'Download Filters': 'Filtry ściągania', - 'Running': 'Uruchomione', - 'Active': 'Aktywne', - 'Waiting': 'Oczekujące', - 'Complete': 'Zakończone', - 'Error': 'Błąd', - 'Paused': 'Zatrzymane', - 'Removed': 'Usunięte', - 'Hide linked meta-data': 'Ukryj zalinkowane meta-dane', - 'Toggle': 'Przełącz', - 'Reset filters': 'Reset filtrów', -// starred properties - 'Quick Access Settings': 'Ustawienia szybkiego dostępu', - 'Save settings': 'Zapisz ustawienia', - 'Currently no download in line to display, use the': 'Obecnie nie można wyświetlić żadnych pobieranych plików. Użyj przycisku', - 'download button to start downloading files!': 'aby rozpocząć ściąganie plików!', - 'Peers': 'Peerów', - 'More Info': 'Więcej info', - 'Remove': 'Usuń', - '# of': '# z', - 'Length': 'Długość', -// modals - 'Add Downloads By URIs': 'Dodaj pobieranie przez URI', - '- You can add multiple downloads (files) at the same time by putting URIs for each file on a separate line.': '- Możesz dodać wiele pobrań (plików) w tym samym czasie przez wprowadzenie URI dla każdego w oddzielnej linii.', - '- You can also add multiple URIs (mirrors) for the *same* file. To do this, separate the URIs by a space.': '- Możesz także dodać wiele URI (luster) dla tego *samego* pliku. Zrób to, poprzez oddzielenie URI od siebie spacją.', - '- A URI can be HTTP(S)/FTP/BitTorrent-Magnet.': '- URI może być HTTP(S)/FTP/BitTorrent-Magnet.', - 'Download settings': 'Ustawienia pobierania', - 'Advanced settings': 'Zaawansowane ustawienia', - 'Cancel': 'Anuluj', - 'Start': 'Rozpocznij', - 'Choose': 'Wybierz', - 'Quick Access (shown on the main page)': 'Szybki dostęp (pokazywane na głównej stronie)', -// add torrent modal - 'Add Downloads By Torrents': 'Dodaj pobierania przez Torrenty', - '- Select the torrent from the local filesystem to start the download.': '- Wybierz torrent z lokalnego systemu plików, aby rozpocząć pobieranie.', - '- You can select multiple torrents to start multiple downloads.': '- Możesz wybrać wiele torrentów do rozpoczęcia wiele pobrań.', - '- To add a BitTorrent-Magnet URL, use the Add By URI option and add it there.': '- Aby dodać BitTorrent-URL Magnetyczny, użyj opcji dodawania przez URI i dodaj to tutaj.', - 'Select Torrents': 'Wybierz Torrenty', - 'Select a Torrent': 'Wybierz Torrent', -// add metalink modal - 'Add Downloads By Metalinks': 'Dodaj pobierania przez Metalinki', - 'Select Metalinks': 'Wybierz Metalinki', - '- Select the Metalink from the local filesystem to start the download.': '- Wybierz Metalinki z lokalnego systemu plików, aby rozpocząć pobieranie.', - '- You can select multiple Metalinks to start multiple downloads.': '- Możesz wybrać wiele Metalinków, aby rozpocząć wiele pobrań.', - 'Select a Metalink': 'Wybierz Metalink', -// select file modal - 'Choose files to start download for': 'Wybierz pliki, aby rozpocząć pobieranie dla', - 'Select to download': 'Wybierz do pobierania', -// settings modal - 'Aria2 RPC host and port': 'Aria2 RPC host i port', - 'Enter the host': 'Wprowadź host', - 'Enter the IP or DNS name of the server on which the RPC for Aria2 is running (default: localhost)': 'Wprowadź IP lub nazwę DNS serwera, na którym jest uruchomiona Aria2 z RPC (domyślnie: localhost)', - 'Enter the port': 'Wprowadź port', - 'Enter the port of the server on which the RPC for Aria2 is running (default: 6800)': 'Wprowadź port serwera, na którym Aria2 z RPC jest uruchomiona (domyślnie 6800)', - 'Enter the RPC path': 'Wprowadź ścieżkę RPC', - 'Enter the path for the Aria2 RPC endpoint (default: /jsonrpc)': 'Wprowadź ścieżkę dla punktu końcowego Aria2 RPC (domyślnie: /jsonrpc)', - 'SSL/TLS encryption': 'szyfrowanie SSL/TLS', - 'Enable SSL/TLS encryption': 'Włącz szyfrowanie SSL/TLS', - 'Enter the secret token (optional)': 'Wprowadź sekretny token (opcja dodatkowa)', - 'Enter the Aria2 RPC secret token (leave empty if authentication is not enabled)': 'Wprowadź sekretny token Aria2 RPC (pozostaw puste, jeżeli uwierzytelnienie nie jest włączone)', - 'Enter the username (optional)': 'Wprowadź nazwę użytkownika (opcja dodatkowa)', - 'Enter the Aria2 RPC username (empty if authentication not enabled)': 'Wprowadź nazwę użytkownika Aria2 RPC (pozostaw puste, jeżeli uwierzytelnienie nie jest włączone)', - 'Enter the password (optional)': 'Wprowadź hasło (opcja dodatkowa)', - 'Enter the Aria2 RPC password (empty if authentication not enabled)': 'Wprowadź hasło Aria2 RPC (pozostaw puste, jeżeli uwierzytelnienie nie jest włączone)', - 'Enter base URL (optional)': 'Wprowadź podstawowy URL (opcja dodatkowa)', - 'Direct Download': 'Bezpośrednie pobieranie', - 'If supplied, links will be created to enable direct download from the Aria2 server.': 'Jeżeli zaznaczone, linki mogą być utworzone do włączenia bezpośredniego pobierania z serwera Aria2', - '(Requires appropriate webserver to be configured.)': '(Wymaga właściwej konfiguracji serwera WWW)', - 'Save Connection configuration': 'Zapisz konfigurację połączenia', - 'Filter': 'Filtr', -// server info modal - 'Aria2 server info': 'Info o serwerze Aria2', - 'Aria2 Version': 'Wersja Aria2', - 'Features Enabled': 'Włączone funkcje', -// about modal - 'To download the latest version of the project, add issues or to contribute back, head on to': 'Aby ściągnąć najnowszą wersję projektu, dodać zgłodzenia lub wspomagać projekt, udaj się do', - 'Or you can open the latest version in the browser through': 'Lub otwórz najnowszą wersję przez przeglądarkę', - 'Close': 'Zamknij', -// lables - 'Download status':'Status pobierania', - 'Download Speed':'Szybkość pobierania', - 'Upload Speed':'Szybkość wysyłania', - 'Estimated time':'Pozostały czas', - 'Download Size':'Rozmiar pobierania', - 'Downloaded':'Pobrane', - 'Progress':'Postęp', - 'Download Path':'Ścieżka pobierania', - 'Uploaded':'Załadowany', - 'Download GID':'GID pobierania', - 'Number of Pieces':'Liczba kawałków', - 'Piece Length':'Rozmiar kawałka', - 'Shutdown Server': 'Wyłącz serwer', - 'The last connection attempt was unsuccessful. Trying another configuration': 'Ostatnia próba połączenia nie powiodła się. Spróbuj innej konfiguracji', - 'Oh Snap!': 'O kurczę!', - 'Could not connect to the aria2 RPC server. Will retry in 10 secs. You might want to check the connection settings by going to Settings > Connection Settings': 'Nie można połączyć się z serwerem aria2 przez RPC. Kolejna próba za 10 sekund. Być może potrzebujesz sprawdzić ustawienie połączenia poprzez Ustawienia > Ustawienia połączenia', - 'Successfully connected to Aria2 through its remote RPC …': 'Pomyślnie połączono się z Aria2 przez RPC ...', - 'Successfully connected to Aria2 through remote RPC, however the connection is still insecure. For complete security try adding an authorization secret token while starting Aria2 (through the flag --rpc-secret)': 'Pomyślnie połączono się z Aria2 przez RPC, jednakże połączenie nie jest bezpieczne. Aby zabezpieczyć dodaj sekretny token autoryzacji podczas startu Aria2 (przez użycie flagi --rpc-secret)', - 'Trying to connect to aria2 using the new connection configuration': 'Próba połączenia się z Aria2 poprzez użycie nowej konfiguracji połączenia' + // header + Search: "Szukaj", + // Nav menu + Add: "Dodaj", + "By URIs": "Przez URL", + "By Torrents": "Przez Torrenty", + "By Metalinks": "Przez Metalinki", + Manage: "Zarządzaj", + "Pause All": "Zatrzymaj wszystkie", + "Resume Paused": "Wznów zatrzymane", + "Purge Completed": "Czyść zakończone", + Settings: "Ustawienia", + "Connection Settings": "Ustawienia połączenia", + "Global Settings": "Ustawienia globalne", + "Server info": "Informacje o serwerze", + "About and contribute": "O projekcie", + "Toggle navigation": "Przełącz nawigację", + // body + // nav side bar + Miscellaneous: "Różne", + "Global Statistics": "Statystyki globalne", + About: "O", + Displaying: "Wyświetlanie", + of: "z", + downloads: "pobranych plików", + Language: "Język", + // download filters + "Download Filters": "Filtry ściągania", + Running: "Uruchomione", + Active: "Aktywne", + Waiting: "Oczekujące", + Complete: "Zakończone", + Error: "Błąd", + Paused: "Zatrzymane", + Removed: "Usunięte", + "Hide linked meta-data": "Ukryj zalinkowane meta-dane", + Toggle: "Przełącz", + "Reset filters": "Reset filtrów", + // starred properties + "Quick Access Settings": "Ustawienia szybkiego dostępu", + "Save settings": "Zapisz ustawienia", + "Currently no download in line to display, use the": + "Obecnie nie można wyświetlić żadnych pobieranych plików. Użyj przycisku", + "download button to start downloading files!": "aby rozpocząć ściąganie plików!", + Peers: "Peerów", + "More Info": "Więcej info", + Remove: "Usuń", + "# of": "# z", + Length: "Długość", + // modals + "Add Downloads By URIs": "Dodaj pobieranie przez URI", + "- You can add multiple downloads (files) at the same time by putting URIs for each file on a separate line.": + "- Możesz dodać wiele pobrań (plików) w tym samym czasie przez wprowadzenie URI dla każdego w oddzielnej linii.", + "- You can also add multiple URIs (mirrors) for the *same* file. To do this, separate the URIs by a space.": + "- Możesz także dodać wiele URI (luster) dla tego *samego* pliku. Zrób to, poprzez oddzielenie URI od siebie spacją.", + "- A URI can be HTTP(S)/FTP/BitTorrent-Magnet.": "- URI może być HTTP(S)/FTP/BitTorrent-Magnet.", + "Download settings": "Ustawienia pobierania", + "Advanced settings": "Zaawansowane ustawienia", + Cancel: "Anuluj", + Start: "Rozpocznij", + Choose: "Wybierz", + "Quick Access (shown on the main page)": "Szybki dostęp (pokazywane na głównej stronie)", + // add torrent modal + "Add Downloads By Torrents": "Dodaj pobierania przez Torrenty", + "- Select the torrent from the local filesystem to start the download.": + "- Wybierz torrent z lokalnego systemu plików, aby rozpocząć pobieranie.", + "- You can select multiple torrents to start multiple downloads.": + "- Możesz wybrać wiele torrentów do rozpoczęcia wiele pobrań.", + "- To add a BitTorrent-Magnet URL, use the Add By URI option and add it there.": + "- Aby dodać BitTorrent-URL Magnetyczny, użyj opcji dodawania przez URI i dodaj to tutaj.", + "Select Torrents": "Wybierz Torrenty", + "Select a Torrent": "Wybierz Torrent", + // add metalink modal + "Add Downloads By Metalinks": "Dodaj pobierania przez Metalinki", + "Select Metalinks": "Wybierz Metalinki", + "- Select the Metalink from the local filesystem to start the download.": + "- Wybierz Metalinki z lokalnego systemu plików, aby rozpocząć pobieranie.", + "- You can select multiple Metalinks to start multiple downloads.": + "- Możesz wybrać wiele Metalinków, aby rozpocząć wiele pobrań.", + "Select a Metalink": "Wybierz Metalink", + // select file modal + "Choose files to start download for": "Wybierz pliki, aby rozpocząć pobieranie dla", + "Select to download": "Wybierz do pobierania", + // settings modal + "Aria2 RPC host and port": "Aria2 RPC host i port", + "Enter the host": "Wprowadź host", + "Enter the IP or DNS name of the server on which the RPC for Aria2 is running (default: localhost)": + "Wprowadź IP lub nazwę DNS serwera, na którym jest uruchomiona Aria2 z RPC (domyślnie: localhost)", + "Enter the port": "Wprowadź port", + "Enter the port of the server on which the RPC for Aria2 is running (default: 6800)": + "Wprowadź port serwera, na którym Aria2 z RPC jest uruchomiona (domyślnie 6800)", + "Enter the RPC path": "Wprowadź ścieżkę RPC", + "Enter the path for the Aria2 RPC endpoint (default: /jsonrpc)": + "Wprowadź ścieżkę dla punktu końcowego Aria2 RPC (domyślnie: /jsonrpc)", + "SSL/TLS encryption": "szyfrowanie SSL/TLS", + "Enable SSL/TLS encryption": "Włącz szyfrowanie SSL/TLS", + "Enter the secret token (optional)": "Wprowadź sekretny token (opcja dodatkowa)", + "Enter the Aria2 RPC secret token (leave empty if authentication is not enabled)": + "Wprowadź sekretny token Aria2 RPC (pozostaw puste, jeżeli uwierzytelnienie nie jest włączone)", + "Enter the username (optional)": "Wprowadź nazwę użytkownika (opcja dodatkowa)", + "Enter the Aria2 RPC username (empty if authentication not enabled)": + "Wprowadź nazwę użytkownika Aria2 RPC (pozostaw puste, jeżeli uwierzytelnienie nie jest włączone)", + "Enter the password (optional)": "Wprowadź hasło (opcja dodatkowa)", + "Enter the Aria2 RPC password (empty if authentication not enabled)": + "Wprowadź hasło Aria2 RPC (pozostaw puste, jeżeli uwierzytelnienie nie jest włączone)", + "Enter base URL (optional)": "Wprowadź podstawowy URL (opcja dodatkowa)", + "Direct Download": "Bezpośrednie pobieranie", + "If supplied, links will be created to enable direct download from the Aria2 server.": + "Jeżeli zaznaczone, linki mogą być utworzone do włączenia bezpośredniego pobierania z serwera Aria2", + "(Requires appropriate webserver to be configured.)": + "(Wymaga właściwej konfiguracji serwera WWW)", + "Save Connection configuration": "Zapisz konfigurację połączenia", + Filter: "Filtr", + // server info modal + "Aria2 server info": "Info o serwerze Aria2", + "Aria2 Version": "Wersja Aria2", + "Features Enabled": "Włączone funkcje", + // about modal + "To download the latest version of the project, add issues or to contribute back, head on to": + "Aby ściągnąć najnowszą wersję projektu, dodać zgłodzenia lub wspomagać projekt, udaj się do", + "Or you can open the latest version in the browser through": + "Lub otwórz najnowszą wersję przez przeglądarkę", + Close: "Zamknij", + // lables + "Download status": "Status pobierania", + "Download Speed": "Szybkość pobierania", + "Upload Speed": "Szybkość wysyłania", + "Estimated time": "Pozostały czas", + "Download Size": "Rozmiar pobierania", + Downloaded: "Pobrane", + Progress: "Postęp", + "Download Path": "Ścieżka pobierania", + Uploaded: "Załadowany", + "Download GID": "GID pobierania", + "Number of Pieces": "Liczba kawałków", + "Piece Length": "Rozmiar kawałka", + "Shutdown Server": "Wyłącz serwer", + "The last connection attempt was unsuccessful. Trying another configuration": + "Ostatnia próba połączenia nie powiodła się. Spróbuj innej konfiguracji", + "Oh Snap!": "O kurczę!", + "Could not connect to the aria2 RPC server. Will retry in 10 secs. You might want to check the connection settings by going to Settings > Connection Settings": + "Nie można połączyć się z serwerem aria2 przez RPC. Kolejna próba za 10 sekund. Być może potrzebujesz sprawdzić ustawienie połączenia poprzez Ustawienia > Ustawienia połączenia", + "Successfully connected to Aria2 through its remote RPC …": + "Pomyślnie połączono się z Aria2 przez RPC ...", + "Successfully connected to Aria2 through remote RPC, however the connection is still insecure. For complete security try adding an authorization secret token while starting Aria2 (through the flag --rpc-secret)": + "Pomyślnie połączono się z Aria2 przez RPC, jednakże połączenie nie jest bezpieczne. Aby zabezpieczyć dodaj sekretny token autoryzacji podczas startu Aria2 (przez użycie flagi --rpc-secret)", + "Trying to connect to aria2 using the new connection configuration": + "Próba połączenia się z Aria2 poprzez użycie nowej konfiguracji połączenia" }; diff --git a/js/translate/pt_BR.js b/js/translate/pt_BR.js index 15b9227f..cc99d919 100644 --- a/js/translate/pt_BR.js +++ b/js/translate/pt_BR.js @@ -1,154 +1,166 @@ -if(typeof translations == 'undefined'){ - translations = {}; +if (typeof translations == "undefined") { + translations = {}; } -translations.pt_BR = { // replace en_US to ll_CC, examples: zh_CN, de_AT. -// header - 'Search': 'Buscar', - // Nav menu - 'Add': 'Adicionar', - 'By URIs': 'Por URIs', - 'By Torrents': 'Por Torrents', - 'By Metalinks': 'Por Metalinks', - 'Manage': 'Gerenciar', - 'Pause All': 'Pausar Todos', - 'Resume Paused': 'Retomar Pausados', - 'Purge Completed': 'Remover Completados', - 'Shutdown Server': 'Desligar Servidor', - 'Settings': 'Configurações', - 'Connection Settings': 'Configurações de Conexão', - 'Global Settings': 'Configurações Globais', - 'Server info': 'Informações do Servidor', - 'About and contribute': 'Sobre e contribuições', - 'Toggle navigation': 'Alternar navegação', -// body -// nav side bar - 'Miscellaneous': 'Miscelânia', - 'Global Statistics': 'Estatísticas Globais', - 'About': 'Sobre', - 'Displaying': 'Mostrando', - 'of': 'de', - 'downloads': 'downloads', - 'Language': 'Linguagem', -// download filters - 'Download Filters': 'Filtros de Download', - 'Running': 'Rodando', - 'Active': 'Ativo', - 'Waiting': 'Esperando', - 'Complete': 'Completo', - 'Error': 'Erro', - 'Paused': 'Pausado', - 'Removed': 'Removido', - 'Hide linked meta-data': 'Esconder metadados ligados', - 'Toggle': 'Alternar', - 'Reset filters': 'Limpar filtros', -// download status - 'Verifing': 'Verificando', - 'Verify Pending': 'Verificação Pendente', -// starred properties - 'Quick Access Settings': 'Acesso Rápido às Configurações', - 'Save': 'Salvar', - 'Save settings': 'Salvar configurações', - 'Currently no download in line to display, use the': 'No momento não existem downloads para mostrar, utilize botão', - 'download button to start downloading files!': 'pra iniciar a transferência de arquivos!', - 'Peers': 'Peers', - 'More Info': 'Mais informações', - 'Remove': 'Remover', - '# of': ' de', - 'Length': 'Tamanho', -// modals - 'Add Downloads By URIs': 'Adicionar Downloads por URIs', - '- You can add multiple downloads (files) at the same time by putting URIs for each file on a separate line.': - '- Você pode adicionar múltiplos downloads (arquivos) ao mesmo tempo inserindo a URI de cada arquivo em uma linha separada.', - '- You can also add multiple URIs (mirrors) for the *same* file. To do this, separate the URIs by a space.': - '- Você também pode adicionar múltiplas URIs (mirrors) para o *mesmo* arquivo. Para fazer isto, separe as URIs por um espaço.', - '- A URI can be HTTP(S)/FTP/BitTorrent-Magnet.': '- Uma URI pode ser HTTP(S)/FTP/BitTorrent-Magnet.', - 'Download settings': 'Configurações de download', - 'Advanced settings': 'Configurações avançadas', - 'Cancel': 'Cancelar', - 'Start': 'Iniciar', - 'Choose': 'Escolher', - 'Quick Access (shown on the main page)': 'Acesso Rápido (exibido na página principal)', -// add torrent modal - 'Add Downloads By Torrents': 'Adicionar Downloads por Torrents', - '- Select the torrent from the local filesystem to start the download.': '- Selecione o torrent de seu sistema de arquivos local para iniciar o download.', - '- You can select multiple torrents to start multiple downloads.': '- Você pode selecionar múltiplos torrents para iniciar múltiplos downloads.', - '- To add a BitTorrent-Magnet URL, use the Add By URI option and add it there.': '- Para adicionar uma URL BitTorrent-Magnet, utilize a opção Adicionar por URI.', - 'Select Torrents': 'Selecione Torrents', - 'Select a Torrent': 'Selecione um Torrent', -// add metalink modal - 'Add Downloads By Metalinks': 'Adicionar Downloads por Metalinks', - 'Select Metalinks': 'Selecione Metalinks', - '- Select the Metalink from the local filesystem to start the download.': '- Selecione o Metalink do seu sistema de arquivos local para iniciar o download.', - '- You can select multiple Metalinks to start multiple downloads.': '- Você pode selecionar múltiplos Metalinks para iniciar múltiplos downloads.', - 'Select a Metalink': 'Selecione um Metalink', -// select file modal - 'Choose files to start download for': 'Selecione os arquvos para serem baixados', - 'Select to download': 'Selecione para baixar', -// settings modal - 'Aria2 RPC host and port': 'Host e porta do RPC Aria2', - 'Enter the host': 'Informe o host', - 'Enter the IP or DNS name of the server on which the RPC for Aria2 is running (default: localhost)': - 'Informe o IP ou nome DNS do servidor no qual o RPC do Aria2 está rodando (default: localhost)', - 'Enter the port': 'Informe a porta', - 'Enter the port of the server on which the RPC for Aria2 is running (default: 6800)': - 'Informe a porta do servidor no qual o RPC do Aria2 está rodando (default: 6800)', - 'Enter the RPC path': 'Informe o caminho RPC', - 'Enter the path for the Aria2 RPC endpoint (default: /jsonrpc)': 'Informe o caminho para o endpoint RPC do Aria2 (default: /jasonrpc)', - 'SSL/TLS encryption': 'Criptografia SSL/TLS', - 'Enable SSL/TLS encryption': 'Habilita criptografia SSL/TLS', - 'Enter the secret token (optional)': 'Informe o token secreto (opcional)', - 'Enter the Aria2 RPC secret token (leave empty if authentication is not enabled)': - 'Informe o token secreto do RPC Aria2 (deixe vazio se a autenticação não estiver habilitada)', - 'Enter the username (optional)': 'Informe o usuário (opcional)', - 'Enter the Aria2 RPC username (empty if authentication not enabled)': - 'Informe o usuário RPC do Aria2 (vazio se a autenticação não estiver habilitada)', - 'Enter the password (optional)': 'Informe a senha (opcional)', - 'Enter the Aria2 RPC password (empty if authentication not enabled)': 'Informe a senha RPC do Aria2 (vazio se a autenticação não estiver habilitada)', - 'Enter base URL (optional)': 'Informe a URL base (opcional)', - 'Direct Download': 'Download Direto', - 'If supplied, links will be created to enable direct download from the Aria2 server.': - 'Se fornecido, links serão criados para permitir download direto do servidor Aria2.', - '(Requires appropriate webserver to be configured.)': '(Requer servidor web apropriado a ser configurado.)', - 'Save Connection configuration': 'Salvar Configuração de conexão', - 'Filter': 'Filtrar', -// server info modal - 'Aria2 server info': 'Informações do servidor Aria2', - 'Aria2 Version': 'Verão do Aria2', - 'Features Enabled': 'Opções Habilitadas', -// about modal - 'To download the latest version of the project, add issues or to contribute back, head on to': - 'Para baixar a última versão do projeto, reportar problemas ou contribuir, acesse', - 'Or you can open the latest version in the browser through': 'Ou você pode acessar a última versão pelo navegador através', - 'Close': 'Fechar', -// labels - 'Download status':'Status do download', - 'Download Speed':'Velocidade de download', - 'Upload Speed':'Velocidade de upload', - 'Estimated time':'Tempo estimado', - 'Download Size':'Tamanho do download', - 'Downloaded':'Baixado', - 'Progress':'Progresso', - 'Download Path':'Caminho do download', - 'Uploaded':'Enviado', - 'Download GID':'GID do download', - 'Number of Pieces':'Número de partes', - 'Piece Length':'Tamanho das partes', +translations.pt_BR = { + // replace en_US to ll_CC, examples: zh_CN, de_AT. + // header + Search: "Buscar", + // Nav menu + Add: "Adicionar", + "By URIs": "Por URIs", + "By Torrents": "Por Torrents", + "By Metalinks": "Por Metalinks", + Manage: "Gerenciar", + "Pause All": "Pausar Todos", + "Resume Paused": "Retomar Pausados", + "Purge Completed": "Remover Completados", + "Shutdown Server": "Desligar Servidor", + Settings: "Configurações", + "Connection Settings": "Configurações de Conexão", + "Global Settings": "Configurações Globais", + "Server info": "Informações do Servidor", + "About and contribute": "Sobre e contribuições", + "Toggle navigation": "Alternar navegação", + // body + // nav side bar + Miscellaneous: "Miscelânia", + "Global Statistics": "Estatísticas Globais", + About: "Sobre", + Displaying: "Mostrando", + of: "de", + downloads: "downloads", + Language: "Linguagem", + // download filters + "Download Filters": "Filtros de Download", + Running: "Rodando", + Active: "Ativo", + Waiting: "Esperando", + Complete: "Completo", + Error: "Erro", + Paused: "Pausado", + Removed: "Removido", + "Hide linked meta-data": "Esconder metadados ligados", + Toggle: "Alternar", + "Reset filters": "Limpar filtros", + // download status + Verifing: "Verificando", + "Verify Pending": "Verificação Pendente", + // starred properties + "Quick Access Settings": "Acesso Rápido às Configurações", + Save: "Salvar", + "Save settings": "Salvar configurações", + "Currently no download in line to display, use the": + "No momento não existem downloads para mostrar, utilize botão", + "download button to start downloading files!": "pra iniciar a transferência de arquivos!", + Peers: "Peers", + "More Info": "Mais informações", + Remove: "Remover", + "# of": " de", + Length: "Tamanho", + // modals + "Add Downloads By URIs": "Adicionar Downloads por URIs", + "- You can add multiple downloads (files) at the same time by putting URIs for each file on a separate line.": + "- Você pode adicionar múltiplos downloads (arquivos) ao mesmo tempo inserindo a URI de cada arquivo em uma linha separada.", + "- You can also add multiple URIs (mirrors) for the *same* file. To do this, separate the URIs by a space.": + "- Você também pode adicionar múltiplas URIs (mirrors) para o *mesmo* arquivo. Para fazer isto, separe as URIs por um espaço.", + "- A URI can be HTTP(S)/FTP/BitTorrent-Magnet.": + "- Uma URI pode ser HTTP(S)/FTP/BitTorrent-Magnet.", + "Download settings": "Configurações de download", + "Advanced settings": "Configurações avançadas", + Cancel: "Cancelar", + Start: "Iniciar", + Choose: "Escolher", + "Quick Access (shown on the main page)": "Acesso Rápido (exibido na página principal)", + // add torrent modal + "Add Downloads By Torrents": "Adicionar Downloads por Torrents", + "- Select the torrent from the local filesystem to start the download.": + "- Selecione o torrent de seu sistema de arquivos local para iniciar o download.", + "- You can select multiple torrents to start multiple downloads.": + "- Você pode selecionar múltiplos torrents para iniciar múltiplos downloads.", + "- To add a BitTorrent-Magnet URL, use the Add By URI option and add it there.": + "- Para adicionar uma URL BitTorrent-Magnet, utilize a opção Adicionar por URI.", + "Select Torrents": "Selecione Torrents", + "Select a Torrent": "Selecione um Torrent", + // add metalink modal + "Add Downloads By Metalinks": "Adicionar Downloads por Metalinks", + "Select Metalinks": "Selecione Metalinks", + "- Select the Metalink from the local filesystem to start the download.": + "- Selecione o Metalink do seu sistema de arquivos local para iniciar o download.", + "- You can select multiple Metalinks to start multiple downloads.": + "- Você pode selecionar múltiplos Metalinks para iniciar múltiplos downloads.", + "Select a Metalink": "Selecione um Metalink", + // select file modal + "Choose files to start download for": "Selecione os arquvos para serem baixados", + "Select to download": "Selecione para baixar", + // settings modal + "Aria2 RPC host and port": "Host e porta do RPC Aria2", + "Enter the host": "Informe o host", + "Enter the IP or DNS name of the server on which the RPC for Aria2 is running (default: localhost)": + "Informe o IP ou nome DNS do servidor no qual o RPC do Aria2 está rodando (default: localhost)", + "Enter the port": "Informe a porta", + "Enter the port of the server on which the RPC for Aria2 is running (default: 6800)": + "Informe a porta do servidor no qual o RPC do Aria2 está rodando (default: 6800)", + "Enter the RPC path": "Informe o caminho RPC", + "Enter the path for the Aria2 RPC endpoint (default: /jsonrpc)": + "Informe o caminho para o endpoint RPC do Aria2 (default: /jasonrpc)", + "SSL/TLS encryption": "Criptografia SSL/TLS", + "Enable SSL/TLS encryption": "Habilita criptografia SSL/TLS", + "Enter the secret token (optional)": "Informe o token secreto (opcional)", + "Enter the Aria2 RPC secret token (leave empty if authentication is not enabled)": + "Informe o token secreto do RPC Aria2 (deixe vazio se a autenticação não estiver habilitada)", + "Enter the username (optional)": "Informe o usuário (opcional)", + "Enter the Aria2 RPC username (empty if authentication not enabled)": + "Informe o usuário RPC do Aria2 (vazio se a autenticação não estiver habilitada)", + "Enter the password (optional)": "Informe a senha (opcional)", + "Enter the Aria2 RPC password (empty if authentication not enabled)": + "Informe a senha RPC do Aria2 (vazio se a autenticação não estiver habilitada)", + "Enter base URL (optional)": "Informe a URL base (opcional)", + "Direct Download": "Download Direto", + "If supplied, links will be created to enable direct download from the Aria2 server.": + "Se fornecido, links serão criados para permitir download direto do servidor Aria2.", + "(Requires appropriate webserver to be configured.)": + "(Requer servidor web apropriado a ser configurado.)", + "Save Connection configuration": "Salvar Configuração de conexão", + Filter: "Filtrar", + // server info modal + "Aria2 server info": "Informações do servidor Aria2", + "Aria2 Version": "Verão do Aria2", + "Features Enabled": "Opções Habilitadas", + // about modal + "To download the latest version of the project, add issues or to contribute back, head on to": + "Para baixar a última versão do projeto, reportar problemas ou contribuir, acesse", + "Or you can open the latest version in the browser through": + "Ou você pode acessar a última versão pelo navegador através", + Close: "Fechar", + // labels + "Download status": "Status do download", + "Download Speed": "Velocidade de download", + "Upload Speed": "Velocidade de upload", + "Estimated time": "Tempo estimado", + "Download Size": "Tamanho do download", + Downloaded: "Baixado", + Progress: "Progresso", + "Download Path": "Caminho do download", + Uploaded: "Enviado", + "Download GID": "GID do download", + "Number of Pieces": "Número de partes", + "Piece Length": "Tamanho das partes", -//alerts - 'The last connection attempt was unsuccessful. Trying another configuration': - 'A última tentativa de conexão não teve sucesso. Tentando outra configuração', - 'Oh Snap!': 'Ah Droga!', - 'Could not connect to the aria2 RPC server. Will retry in 10 secs. You might want to check the connection settings by going to Settings > Connection Settings': - 'Não foi possível conectar no servidor RPC aria2. Tententando em 10 seg. Você pode querer verificar as configurações da conexão em Configurações > Configurações de Conexão', - 'Authentication failed while connecting to Aria2 RPC server. Will retry in 10 secs. You might want to confirm your authentication details by going to Settings > Connection Settings': - 'Autenticação falhou enquanto conectando ao servidor RPC Aria2. Tentando em 10 seg. Você pode querer confirmar os detalhes de autenticação acessando Configurações > Configurações de Conexão', - 'Successfully connected to Aria2 through its remote RPC …': - 'Conectado com sucesso ao Aria2 através de seu RPC remoto …', - 'Successfully connected to Aria2 through remote RPC, however the connection is still insecure. For complete security try adding an authorization secret token while starting Aria2 (through the flag --rpc-secret)': - 'Conectado com sucesso ao Aria2 através de seu RPC remoto, contudo a conexão é insegura. Para uma completa segurança tente adicionar um token secreto de autorização quando iniciar o Aria2 (através da opção --rpc-secret)', - 'Trying to connect to aria2 using the new connection configuration': - 'Tentando conectar-se ao aria2 utilizando a nova configuração de conexão', - 'Remove {{name}} and associated meta-data?': // {{name}} refers to the download name, do not modify. - 'Remover {{name}} e os metadados associados?' + //alerts + "The last connection attempt was unsuccessful. Trying another configuration": + "A última tentativa de conexão não teve sucesso. Tentando outra configuração", + "Oh Snap!": "Ah Droga!", + "Could not connect to the aria2 RPC server. Will retry in 10 secs. You might want to check the connection settings by going to Settings > Connection Settings": + "Não foi possível conectar no servidor RPC aria2. Tententando em 10 seg. Você pode querer verificar as configurações da conexão em Configurações > Configurações de Conexão", + "Authentication failed while connecting to Aria2 RPC server. Will retry in 10 secs. You might want to confirm your authentication details by going to Settings > Connection Settings": + "Autenticação falhou enquanto conectando ao servidor RPC Aria2. Tentando em 10 seg. Você pode querer confirmar os detalhes de autenticação acessando Configurações > Configurações de Conexão", + "Successfully connected to Aria2 through its remote RPC …": + "Conectado com sucesso ao Aria2 através de seu RPC remoto …", + "Successfully connected to Aria2 through remote RPC, however the connection is still insecure. For complete security try adding an authorization secret token while starting Aria2 (through the flag --rpc-secret)": + "Conectado com sucesso ao Aria2 através de seu RPC remoto, contudo a conexão é insegura. Para uma completa segurança tente adicionar um token secreto de autorização quando iniciar o Aria2 (através da opção --rpc-secret)", + "Trying to connect to aria2 using the new connection configuration": + "Tentando conectar-se ao aria2 utilizando a nova configuração de conexão", + // {{name}} refers to the download name, do not modify. + "Remove {{name}} and associated meta-data?": "Remover {{name}} e os metadados associados?" }; diff --git a/js/translate/ru_RU.js b/js/translate/ru_RU.js index f07eed89..40220ea2 100644 --- a/js/translate/ru_RU.js +++ b/js/translate/ru_RU.js @@ -1,143 +1,156 @@ -if(typeof translations == 'undefined'){ - translations = {}; +if (typeof translations == "undefined") { + translations = {}; } translations.ru_RU = { -// header - 'Search': 'Поиск', - // Nav menu - 'Add': 'Добавить', - 'By URIs': 'URL-адреса', - 'By Torrents': 'Torrent-файлы', - 'By Metalinks': 'Metalink-файлы', - 'Manage': 'Управление', - 'Pause All': 'Приостановить всё', - 'Resume Paused': 'Возобновить всё', - 'Purge Completed': 'Удалить завершенные', - 'Settings': 'Настройки', - 'Connection Settings': 'Настройки соединения', - 'Global Settings': 'Глобальные настройки', - 'Server info': 'Информация о сервере', - 'About and contribute': 'Информация и сотрудничество', - 'Toggle navigation': 'Переключение навигации', -// body -// nav side bar - 'Miscellaneous': 'Разное', - 'Global Statistics': 'Глобальная статистика', - 'About': 'Об', - 'Displaying': 'Показано', - 'of': 'из', - 'downloads': 'загрузок', - 'Language': 'Язык', -// download filters - 'Download Filters': 'Фильтр загрузок', - 'Running': 'Запущенные', - 'Active': 'Активные', - 'Waiting': 'Ожидающие', - 'Complete': 'Завершенные', - 'Error': 'С ошибками', - 'Paused': 'Приостановленные', - 'Removed': 'Удаленные', - 'Hide linked meta-data': 'Скрыть связанные метаданные', - 'Toggle': 'Переключить', - 'Reset filters': 'Сбросить фильтры', -// starred properties - 'Quick Access Settings': 'Настройки быстрого доступа', - 'Save settings': 'Сохранить настройки', - 'Currently no download in line to display, use the': 'На данный момент ничего не загружается, используйте кнопку', - 'download button to start downloading files!': 'чтобы начать загрузку файла!', - 'Peers': 'Пиры', - 'More Info': 'Информация', - 'Remove': 'Удалить', - '# of': '# из', - 'Length': 'Размер', -// modals - 'Add Downloads By URIs': 'Добавить загрузки из URL-адресов', - '- You can add multiple downloads (files) at the same time by putting URIs for each file on a separate line.': - '- Вы можете добавить несколько загрузок (файлов) одновременно, помещая URL-адреса для каждого файла на отдельной строке.', - '- You can also add multiple URIs (mirrors) for the *same* file. To do this, separate the URIs by a space.': - '- Можно также добавить несколько URL-адресов (зеркал) для *одного* файла. Для этого отделите URL-адреса пробелом.', - '- A URI can be HTTP(S)/FTP/BitTorrent-Magnet.': '- URL-адрес может быть HTTP(S)/FTP/BitTorrent-Magnet.', - 'Download settings': 'Настройки загрузки', - 'Advanced settings': 'Расширенные настройки', - 'Cancel': 'Отмена', - 'Start': 'Начать', - 'Choose': 'Выбрать', - 'Quick Access (shown on the main page)': 'Простой доступ (смотреть на главной странице)', -// add torrent modal - 'Add Downloads By Torrents': 'Добавить загрузку из Torrent-файлов', - '- Select the torrent from the local filesystem to start the download.': '- Выберите Torrent-файлы из локальной файловой системы для начала загрузку.', - '- You can select multiple torrents to start multiple downloads.': '- Вы можете выбрать несколько Torrent-файлы для запуска нескольких загрузок.', - '- To add a BitTorrent-Magnet URL, use the Add By URI option and add it there.': '- Для добавления BitTorrent-Magnet ссылки воспользуйтесь пунктом меню *Добавить из URL-адреса*', - 'Select Torrents': 'Выберите торренты', - 'Select a Torrent': 'Выберите торрент', -// add metalink modal - 'Add Downloads By Metalinks': 'Добавить загрузку из Metalink-файлов', - 'Select Metalinks': 'Выбрать Metalink-файлы', - '- Select the Metalink from the local filesystem to start the download.': '- Выберите Metalink-файлы из локальной файловой системы для начала загрузки', - '- You can select multiple Metalinks to start multiple downloads.': '- Вы можете выбрать несколько Metalink-файлов для запуска нескольких загрузок.', - 'Select a Metalink': 'Выберите Metalink', -// select file modal - 'Choose files to start download for': 'Выберите файлы чтобы начать загрузку для', - 'Select to download': 'Выберите для загрузки', -// settings modal - 'Aria2 RPC host and port': 'Aria2 RPC хост и порт', - 'Enter the host': 'Укажите хост', - 'Enter the IP or DNS name of the server on which the RPC for Aria2 is running (default: localhost)': - 'Укажите IP или DNS-имя сервера, на котором запущена Aria2 со включенным RPC (по умолчанию: localhost)', - 'Enter the port': 'Укажите порт', - 'Enter the port of the server on which the RPC for Aria2 is running (default: 6800)': - 'Укажите порт сервера, на котором запущена Aria2 со включенным RPC (по умолчанию: 6800)', - 'Enter the RPC path': 'Укажите путь RPC', - 'Enter the path for the Aria2 RPC endpoint (default: /jsonrpc)': 'Укажите конечный путь для Aria2 RPC (по умолчанию: /jsonrpc)', - 'SSL/TLS encryption': 'SSL/TLS шифрование', - 'Enable SSL/TLS encryption': 'Разрешить SSL/TLS шифрование', - 'Enter the secret token (optional)': 'Укажите секретный токен (необязательно)', - 'Enter the Aria2 RPC secret token (leave empty if authentication is not enabled)': - 'Укажите секретный токен Aria2 RPC (оставьте пустым, если авторизация не включена)', - 'Enter the username (optional)': 'Укажите имя пользователя (необязательно)', - 'Enter the Aria2 RPC username (empty if authentication not enabled)': - 'Укажите имя пользователя Aria2 RPC (оставьте пустым, если авторизация не включена)', - 'Enter the password (optional)': 'Укажите пароль (необязательно)', - 'Enter the Aria2 RPC password (empty if authentication not enabled)': 'Укажите пароль для Aria2 RPC (оставьте пустым, если авторизация не включена)', - 'Enter base URL (optional)': 'Укажите базовый URL-адрес (необязательно)', - 'Direct Download': 'Прямая загрузка', - 'If supplied, links will be created to enable direct download from the Aria2 server.': - 'Ссылки (при наличии) будут созданы для загрузки непосредственно с сервера Aria2.', - '(Requires appropriate webserver to be configured.)': '(Требуется соответствующий веб-сервер для настройки.)', - 'Save Connection configuration': 'Сохранить настройки соединения', - 'Filter': 'Фильтр', -// server info modal - 'Aria2 server info': 'Информация о сервере Aria2', - 'Aria2 Version': 'Версия Aria2', - 'Features Enabled': 'Имеющийся функционал', -// about modal - 'To download the latest version of the project, add issues or to contribute back, head on to': - 'Чтобы загрузить последнюю версию проекта, добавить вопросы или внести свой вклад, передите на', - 'Or you can open the latest version in the browser through': 'Или вы можете открыть последнюю версию в браузере через', - 'Close': 'Закрыть', -// lables - 'Download status':'Статус загрузки', - 'Download Speed':'Скорость загрузки', - 'Upload Speed':'Скорость отдачи', - 'Estimated time':'Оставшееся время', - 'Download Size':'Размер загрузки', - 'Downloaded':'Загружено', - 'Progress':'Прогресс', - 'Download Path':'Путь к загружаемым файлам', - 'Uploaded':'Отдано', - 'Download GID':'Загруженый GID', - 'Number of Pieces':'Количество частей', - 'Piece Length': 'Размер частей', - 'Shutdown Server': 'Выключить сервер', + // header + Search: "Поиск", + // Nav menu + Add: "Добавить", + "By URIs": "URL-адреса", + "By Torrents": "Torrent-файлы", + "By Metalinks": "Metalink-файлы", + Manage: "Управление", + "Pause All": "Приостановить всё", + "Resume Paused": "Возобновить всё", + "Purge Completed": "Удалить завершенные", + Settings: "Настройки", + "Connection Settings": "Настройки соединения", + "Global Settings": "Глобальные настройки", + "Server info": "Информация о сервере", + "About and contribute": "Информация и сотрудничество", + "Toggle navigation": "Переключение навигации", + // body + // nav side bar + Miscellaneous: "Разное", + "Global Statistics": "Глобальная статистика", + About: "Об", + Displaying: "Показано", + of: "из", + downloads: "загрузок", + Language: "Язык", + // download filters + "Download Filters": "Фильтр загрузок", + Running: "Запущенные", + Active: "Активные", + Waiting: "Ожидающие", + Complete: "Завершенные", + Error: "С ошибками", + Paused: "Приостановленные", + Removed: "Удаленные", + "Hide linked meta-data": "Скрыть связанные метаданные", + Toggle: "Переключить", + "Reset filters": "Сбросить фильтры", + // starred properties + "Quick Access Settings": "Настройки быстрого доступа", + "Save settings": "Сохранить настройки", + "Currently no download in line to display, use the": + "На данный момент ничего не загружается, используйте кнопку", + "download button to start downloading files!": "чтобы начать загрузку файла!", + Peers: "Пиры", + "More Info": "Информация", + Remove: "Удалить", + "# of": "# из", + Length: "Размер", + // modals + "Add Downloads By URIs": "Добавить загрузки из URL-адресов", + "- You can add multiple downloads (files) at the same time by putting URIs for each file on a separate line.": + "- Вы можете добавить несколько загрузок (файлов) одновременно, помещая URL-адреса для каждого файла на отдельной строке.", + "- You can also add multiple URIs (mirrors) for the *same* file. To do this, separate the URIs by a space.": + "- Можно также добавить несколько URL-адресов (зеркал) для *одного* файла. Для этого отделите URL-адреса пробелом.", + "- A URI can be HTTP(S)/FTP/BitTorrent-Magnet.": + "- URL-адрес может быть HTTP(S)/FTP/BitTorrent-Magnet.", + "Download settings": "Настройки загрузки", + "Advanced settings": "Расширенные настройки", + Cancel: "Отмена", + Start: "Начать", + Choose: "Выбрать", + "Quick Access (shown on the main page)": "Простой доступ (смотреть на главной странице)", + // add torrent modal + "Add Downloads By Torrents": "Добавить загрузку из Torrent-файлов", + "- Select the torrent from the local filesystem to start the download.": + "- Выберите Torrent-файлы из локальной файловой системы для начала загрузку.", + "- You can select multiple torrents to start multiple downloads.": + "- Вы можете выбрать несколько Torrent-файлы для запуска нескольких загрузок.", + "- To add a BitTorrent-Magnet URL, use the Add By URI option and add it there.": + "- Для добавления BitTorrent-Magnet ссылки воспользуйтесь пунктом меню *Добавить из URL-адреса*", + "Select Torrents": "Выберите торренты", + "Select a Torrent": "Выберите торрент", + // add metalink modal + "Add Downloads By Metalinks": "Добавить загрузку из Metalink-файлов", + "Select Metalinks": "Выбрать Metalink-файлы", + "- Select the Metalink from the local filesystem to start the download.": + "- Выберите Metalink-файлы из локальной файловой системы для начала загрузки", + "- You can select multiple Metalinks to start multiple downloads.": + "- Вы можете выбрать несколько Metalink-файлов для запуска нескольких загрузок.", + "Select a Metalink": "Выберите Metalink", + // select file modal + "Choose files to start download for": "Выберите файлы чтобы начать загрузку для", + "Select to download": "Выберите для загрузки", + // settings modal + "Aria2 RPC host and port": "Aria2 RPC хост и порт", + "Enter the host": "Укажите хост", + "Enter the IP or DNS name of the server on which the RPC for Aria2 is running (default: localhost)": + "Укажите IP или DNS-имя сервера, на котором запущена Aria2 со включенным RPC (по умолчанию: localhost)", + "Enter the port": "Укажите порт", + "Enter the port of the server on which the RPC for Aria2 is running (default: 6800)": + "Укажите порт сервера, на котором запущена Aria2 со включенным RPC (по умолчанию: 6800)", + "Enter the RPC path": "Укажите путь RPC", + "Enter the path for the Aria2 RPC endpoint (default: /jsonrpc)": + "Укажите конечный путь для Aria2 RPC (по умолчанию: /jsonrpc)", + "SSL/TLS encryption": "SSL/TLS шифрование", + "Enable SSL/TLS encryption": "Разрешить SSL/TLS шифрование", + "Enter the secret token (optional)": "Укажите секретный токен (необязательно)", + "Enter the Aria2 RPC secret token (leave empty if authentication is not enabled)": + "Укажите секретный токен Aria2 RPC (оставьте пустым, если авторизация не включена)", + "Enter the username (optional)": "Укажите имя пользователя (необязательно)", + "Enter the Aria2 RPC username (empty if authentication not enabled)": + "Укажите имя пользователя Aria2 RPC (оставьте пустым, если авторизация не включена)", + "Enter the password (optional)": "Укажите пароль (необязательно)", + "Enter the Aria2 RPC password (empty if authentication not enabled)": + "Укажите пароль для Aria2 RPC (оставьте пустым, если авторизация не включена)", + "Enter base URL (optional)": "Укажите базовый URL-адрес (необязательно)", + "Direct Download": "Прямая загрузка", + "If supplied, links will be created to enable direct download from the Aria2 server.": + "Ссылки (при наличии) будут созданы для загрузки непосредственно с сервера Aria2.", + "(Requires appropriate webserver to be configured.)": + "(Требуется соответствующий веб-сервер для настройки.)", + "Save Connection configuration": "Сохранить настройки соединения", + Filter: "Фильтр", + // server info modal + "Aria2 server info": "Информация о сервере Aria2", + "Aria2 Version": "Версия Aria2", + "Features Enabled": "Имеющийся функционал", + // about modal + "To download the latest version of the project, add issues or to contribute back, head on to": + "Чтобы загрузить последнюю версию проекта, добавить вопросы или внести свой вклад, передите на", + "Or you can open the latest version in the browser through": + "Или вы можете открыть последнюю версию в браузере через", + Close: "Закрыть", + // lables + "Download status": "Статус загрузки", + "Download Speed": "Скорость загрузки", + "Upload Speed": "Скорость отдачи", + "Estimated time": "Оставшееся время", + "Download Size": "Размер загрузки", + Downloaded: "Загружено", + Progress: "Прогресс", + "Download Path": "Путь к загружаемым файлам", + Uploaded: "Отдано", + "Download GID": "Загруженый GID", + "Number of Pieces": "Количество частей", + "Piece Length": "Размер частей", + "Shutdown Server": "Выключить сервер", - 'The last connection attempt was unsuccessful. Trying another configuration': 'Последняя попытка подключения была неудачной. Попробуйте другую конфигурацию', - 'Oh Snap!': 'Опаньки!', - 'Could not connect to the aria2 RPC server. Will retry in 10 secs. You might want to check the connection settings by going to Settings > Connection Settings': - 'Не удалось подключиться к серверу Aria2 RPC. Попытка будет повторена в течение 10 секунд. Вы можете проверить параметры подключения, перейдя в меню Настройки > Настройки соединения', - 'Successfully connected to Aria2 through its remote RPC …': 'Успешное подключение к Aria2 через удаленный RPC …', - 'Successfully connected to Aria2 through remote RPC, however the connection is still insecure. For complete security try adding an authorization secret token while starting Aria2 (through the flag --rpc-secret)': - 'Успешное подключение к Aria2 через удаленный RPC, однако соединение все еще небезопасно. Для обеспечения лучшей безопасности добавьте секретный токен авторизации при запуске aria2 (через флаг --rpc-secret)', - 'Trying to connect to aria2 using the new connection configuration': - 'Попытка подключиться к aria2 с использованием новой конфигурации', + "The last connection attempt was unsuccessful. Trying another configuration": + "Последняя попытка подключения была неудачной. Попробуйте другую конфигурацию", + "Oh Snap!": "Опаньки!", + "Could not connect to the aria2 RPC server. Will retry in 10 secs. You might want to check the connection settings by going to Settings > Connection Settings": + "Не удалось подключиться к серверу Aria2 RPC. Попытка будет повторена в течение 10 секунд. Вы можете проверить параметры подключения, перейдя в меню Настройки > Настройки соединения", + "Successfully connected to Aria2 through its remote RPC …": + "Успешное подключение к Aria2 через удаленный RPC …", + "Successfully connected to Aria2 through remote RPC, however the connection is still insecure. For complete security try adding an authorization secret token while starting Aria2 (through the flag --rpc-secret)": + "Успешное подключение к Aria2 через удаленный RPC, однако соединение все еще небезопасно. Для обеспечения лучшей безопасности добавьте секретный токен авторизации при запуске aria2 (через флаг --rpc-secret)", + "Trying to connect to aria2 using the new connection configuration": + "Попытка подключиться к aria2 с использованием новой конфигурации" }; diff --git a/js/translate/template.js b/js/translate/template.js index c26e25a6..1a8d10a7 100644 --- a/js/translate/template.js +++ b/js/translate/template.js @@ -12,157 +12,150 @@ // 5. Browser determining preferred language automatically. // http://angular-translate.github.io/docs/en/#/guide/07_multi-language -if(typeof translations == 'undefined'){ - translations = {}; +if (typeof translations == "undefined") { + translations = {}; } -translations.en_US = { // replace en_US to ll_CC, examples: zh_CN, de_AT. -// header - 'Search': '', - // Nav menu - 'Add': '', - 'By URIs': '', - 'By Torrents': '', - 'By Metalinks': '', - 'Manage': '', - 'Pause All': '', - 'Resume Paused': '', - 'Purge Completed': '', - 'Shutdown Server': '', - 'Settings': '', - 'Connection Settings': '', - 'Global Settings': '', - 'Server info': '', - 'About and contribute': '', - 'Toggle navigation': '', -// body -// nav side bar - 'Miscellaneous': '', - 'Global Statistics': '', - 'About': '', - 'Displaying': '', - 'of': '', - 'downloads': '', - 'Language': '', -// download filters - 'Download Filters': '', - 'Running': '', - 'Active': '', - 'Waiting': '', - 'Complete': '', - 'Error': '', - 'Paused': '', - 'Removed': '', - 'Hide linked meta-data': '', - 'Toggle': '', - 'Reset filters': '', -// download status - 'Verifing': '', - 'Verify Pending': '', -// starred properties - 'Quick Access Settings': '', - 'Save': '', - 'Save settings': '', - 'Currently no download in line to display, use the': '', - 'download button to start downloading files!': '', - 'Peers': '', - 'More Info': '', - 'Remove': '', - '# of': '', - 'Length': '', -// modals - 'Add Downloads By URIs': '', - '- You can add multiple downloads (files) at the same time by putting URIs for each file on a separate line.': - '', - '- You can also add multiple URIs (mirrors) for the *same* file. To do this, separate the URIs by a space.': - '', - '- A URI can be HTTP(S)/FTP/BitTorrent-Magnet.': '', - 'Download settings': '', - 'Advanced settings': '', - 'Cancel': '', - 'Start': '', - 'Choose': '', - 'Quick Access (shown on the main page)': '', -// add torrent modal - 'Add Downloads By Torrents': '', - '- Select the torrent from the local filesystem to start the download.': '', - '- You can select multiple torrents to start multiple downloads.': '', - '- To add a BitTorrent-Magnet URL, use the Add By URI option and add it there.': '', - 'Select Torrents': '', - 'Select a Torrent': '', -// add metalink modal - 'Add Downloads By Metalinks': '', - 'Select Metalinks': '', - '- Select the Metalink from the local filesystem to start the download.': '', - '- You can select multiple Metalinks to start multiple downloads.': '', - 'Select a Metalink': '', -// select file modal - 'Choose files to start download for': '', - 'Select to download': '', -// settings modal - 'Aria2 RPC host and port': '', - 'Enter the host': '', - 'Enter the IP or DNS name of the server on which the RPC for Aria2 is running (default: localhost)': - '', - 'Enter the port': '', - 'Enter the port of the server on which the RPC for Aria2 is running (default: 6800)': - '', - 'Enter the RPC path': '', - 'Enter the path for the Aria2 RPC endpoint (default: /jsonrpc)': '', - 'SSL/TLS encryption': '', - 'Enable SSL/TLS encryption': '', - 'Enter the secret token (optional)': '', - 'Enter the Aria2 RPC secret token (leave empty if authentication is not enabled)': - '', - 'Enter the username (optional)': '', - 'Enter the Aria2 RPC username (empty if authentication not enabled)': - '', - 'Enter the password (optional)': '', - 'Enter the Aria2 RPC password (empty if authentication not enabled)': '', - 'Enter base URL (optional)': '', - 'Direct Download': '', - 'If supplied, links will be created to enable direct download from the Aria2 server.': - '', - '(Requires appropriate webserver to be configured.)': '', - 'Save Connection configuration': '', - 'Filter': '', -// server info modal - 'Aria2 server info': '', - 'Aria2 Version': '', - 'Features Enabled': '', -// about modal - 'To download the latest version of the project, add issues or to contribute back, head on to': - '', - 'Or you can open the latest version in the browser through': '', - 'Close': '', -// labels - 'Download status':'', - 'Download Speed':'', - 'Upload Speed':'', - 'Estimated time':'', - 'Download Size':'', - 'Downloaded':'', - 'Progress':'', - 'Download Path':'', - 'Uploaded':'', - 'Download GID':'', - 'Number of Pieces':'', - 'Piece Length':'', +translations.en_US = { + // replace en_US to ll_CC, examples: zh_CN, de_AT. + // header + Search: "", + // Nav menu + Add: "", + "By URIs": "", + "By Torrents": "", + "By Metalinks": "", + Manage: "", + "Pause All": "", + "Resume Paused": "", + "Purge Completed": "", + "Shutdown Server": "", + Settings: "", + "Connection Settings": "", + "Global Settings": "", + "Server info": "", + "About and contribute": "", + "Toggle navigation": "", + // body + // nav side bar + Miscellaneous: "", + "Global Statistics": "", + About: "", + Displaying: "", + of: "", + downloads: "", + Language: "", + // download filters + "Download Filters": "", + Running: "", + Active: "", + Waiting: "", + Complete: "", + Error: "", + Paused: "", + Removed: "", + "Hide linked meta-data": "", + Toggle: "", + "Reset filters": "", + // download status + Verifing: "", + "Verify Pending": "", + // starred properties + "Quick Access Settings": "", + Save: "", + "Save settings": "", + "Currently no download in line to display, use the": "", + "download button to start downloading files!": "", + Peers: "", + "More Info": "", + Remove: "", + "# of": "", + Length: "", + // modals + "Add Downloads By URIs": "", + "- You can add multiple downloads (files) at the same time by putting URIs for each file on a separate line.": + "", + "- You can also add multiple URIs (mirrors) for the *same* file. To do this, separate the URIs by a space.": + "", + "- A URI can be HTTP(S)/FTP/BitTorrent-Magnet.": "", + "Download settings": "", + "Advanced settings": "", + Cancel: "", + Start: "", + Choose: "", + "Quick Access (shown on the main page)": "", + // add torrent modal + "Add Downloads By Torrents": "", + "- Select the torrent from the local filesystem to start the download.": "", + "- You can select multiple torrents to start multiple downloads.": "", + "- To add a BitTorrent-Magnet URL, use the Add By URI option and add it there.": "", + "Select Torrents": "", + "Select a Torrent": "", + // add metalink modal + "Add Downloads By Metalinks": "", + "Select Metalinks": "", + "- Select the Metalink from the local filesystem to start the download.": "", + "- You can select multiple Metalinks to start multiple downloads.": "", + "Select a Metalink": "", + // select file modal + "Choose files to start download for": "", + "Select to download": "", + // settings modal + "Aria2 RPC host and port": "", + "Enter the host": "", + "Enter the IP or DNS name of the server on which the RPC for Aria2 is running (default: localhost)": + "", + "Enter the port": "", + "Enter the port of the server on which the RPC for Aria2 is running (default: 6800)": "", + "Enter the RPC path": "", + "Enter the path for the Aria2 RPC endpoint (default: /jsonrpc)": "", + "SSL/TLS encryption": "", + "Enable SSL/TLS encryption": "", + "Enter the secret token (optional)": "", + "Enter the Aria2 RPC secret token (leave empty if authentication is not enabled)": "", + "Enter the username (optional)": "", + "Enter the Aria2 RPC username (empty if authentication not enabled)": "", + "Enter the password (optional)": "", + "Enter the Aria2 RPC password (empty if authentication not enabled)": "", + "Enter base URL (optional)": "", + "Direct Download": "", + "If supplied, links will be created to enable direct download from the Aria2 server.": "", + "(Requires appropriate webserver to be configured.)": "", + "Save Connection configuration": "", + Filter: "", + // server info modal + "Aria2 server info": "", + "Aria2 Version": "", + "Features Enabled": "", + // about modal + "To download the latest version of the project, add issues or to contribute back, head on to": "", + "Or you can open the latest version in the browser through": "", + Close: "", + // labels + "Download status": "", + "Download Speed": "", + "Upload Speed": "", + "Estimated time": "", + "Download Size": "", + Downloaded: "", + Progress: "", + "Download Path": "", + Uploaded: "", + "Download GID": "", + "Number of Pieces": "", + "Piece Length": "", -//alerts - 'The last connection attempt was unsuccessful. Trying another configuration': - '', - 'Oh Snap!': '', - 'Could not connect to the aria2 RPC server. Will retry in 10 secs. You might want to check the connection settings by going to Settings > Connection Settings': - '', - 'Authentication failed while connecting to Aria2 RPC server. Will retry in 10 secs. You might want to confirm your authentication details by going to Settings > Connection Settings': - '', - 'Successfully connected to Aria2 through its remote RPC …': - '', - 'Successfully connected to Aria2 through remote RPC, however the connection is still insecure. For complete security try adding an authorization secret token while starting Aria2 (through the flag --rpc-secret)': - '', - 'Trying to connect to aria2 using the new connection configuration': - '', - 'Remove {{name}} and associated meta-data?': // {{name}} refers to the download name, do not modify. - '' + //alerts + "The last connection attempt was unsuccessful. Trying another configuration": "", + "Oh Snap!": "", + "Could not connect to the aria2 RPC server. Will retry in 10 secs. You might want to check the connection settings by going to Settings > Connection Settings": + "", + "Authentication failed while connecting to Aria2 RPC server. Will retry in 10 secs. You might want to confirm your authentication details by going to Settings > Connection Settings": + "", + "Successfully connected to Aria2 through its remote RPC …": "", + "Successfully connected to Aria2 through remote RPC, however the connection is still insecure. For complete security try adding an authorization secret token while starting Aria2 (through the flag --rpc-secret)": + "", + "Trying to connect to aria2 using the new connection configuration": "", + // {{name}} refers to the download name, do not modify. + "Remove {{name}} and associated meta-data?": "" }; diff --git a/js/translate/th_TH.js b/js/translate/th_TH.js index 7c83de5e..dc4c635f 100644 --- a/js/translate/th_TH.js +++ b/js/translate/th_TH.js @@ -1,119 +1,117 @@ -if(typeof translations == 'undefined'){ - translations = {}; +if (typeof translations == "undefined") { + translations = {}; } translations.th_TH = { -// header - 'Search': 'ค้นหา', - // Nav menu - 'Add': 'เพื่ม', - 'By URIs': 'ด้วยยูอาร์ไอ', - 'By Torrents': 'ด้วยทอร์เรนต์', - 'By Metalinks': 'ด้วยเมทาลิงค์', - 'Manage': 'บริหาร', - 'Pause All': 'หยุดชั่วคราวหมด', - 'Resume Paused': 'ไปต่อหมด', - 'Purge Completed': 'ลบอันเสร็จ', - 'Settings': 'ตั้งค่า', - 'Connection Settings': 'ตั้งค่าเชื่อมต่อ', - 'Global Settings': 'ตั้งค่าทั่วไป', - 'Server info': 'ข้อมูลเซอร์เวอร์', - 'About and contribute': 'เกี่ยวกับและช่วย', - 'Toggle navigation': 'สลับนำทาง', - 'Language': 'ภาษา', -// body -// nav side bar - 'Miscellaneous': 'เบ็ดเตล็ด', - 'Global Statistics': 'สถิติทั่วไป', - 'About': 'เกี่ยวกับ', - 'Displaying': 'แแสดงดาวน์โหลด', - 'of': 'อันใน', - 'downloads': 'อันทั้งหมด', -// download filters - 'Download Filters': 'กรองดาวน์โหลด', - 'Running': 'กำลังทำงาน', - 'Active': 'ใช้งานอยู่', - 'Waiting': 'กำลังรอ', - 'Complete': 'เสร็จ', - 'Error': 'ผิดพลาด', - 'Paused': 'หยุดอยู่', - 'Removed': 'ลบแล้ว', - 'Hide linked meta-data': 'ซ่อนข้อมูลเมตาที่เชื่อมโยง', - 'Toggle': 'สลับ', - 'Reset filters': 'รีเซตตัวกรอง', -// starred properties - 'Quick Access Settings': 'ตั้งค่าอย่างรวดเร็ว', - 'Save settings': 'บันทึกการตั้งค่า', - 'Currently no download in line to display, use the': 'ตอนนี้ไม่มีการดาวน์โหลดที่แสดงได้ ก็ใช้ปุ่ม', - 'download button to start downloading files!': 'ให้เริ่มดาวน์โหลดไฟล์', - 'Peers': 'พีร์ส', - 'More Info': 'ข้อมูลเพิ่ม', - 'Remove': 'ลบ', - '# of': 'จำนวน', - 'Length': 'ความยาว', -// modals - 'Add Downloads By URIs': 'เพิ่มดาวน์โหลดด้วยยูอาร์ไอ', - '- You can add multiple downloads (files) at the same time by putting URIs for each file on a separate line.': - '', - '- You can also add multiple URIs (mirrors) for the *same* file. To do this, separate the URIs by a space.': - '', - '- A URI can be HTTP(S)/FTP/BitTorrent-Magnet.': '', - 'Download settings': 'ตั้งค่าการดาวน์โหลด', - 'Advanced settings': 'ตั้งค่าขั้นสูง', - 'Cancel': 'ยกเลิก', - 'Start': 'เริ่มต้น', - 'Choose': 'เลือก', - 'Quick Access (shown on the main page)': 'ใช้งานอย่างรวดเร็ว (แสดงที่เพจหลัก)', -// add torrent modal - 'Add Downloads By Torrents': 'เพิ่มดาวน์โหลดด้วยทอร์เรนต์', - '- Select the torrent from the local filesystem to start the download.': '', - '- You can select multiple torrents to start multiple downloads.': '', - '- To add a BitTorrent-Magnet URL, use the Add By URI option and add it there.': '', - 'Select Torrents': 'เลือกทอร์เรนต์', - 'Select a Torrent': 'เลือกทอร์เรนต์', -// add metalink modal - 'Add Downloads By Metalinks': 'เพิ่มดาวน์โหลดด้วยเมทาลิงค์', - 'Select Metalinks': 'เลือกเมทาลิงค์', - '- Select the Metalink from the local filesystem to start the download.': '', - '- You can select multiple Metalinks to start multiple downloads.': '', - 'Select a Metalink': 'เลือกเมทาลิงค์', -// select file modal - 'Choose files to start download for': 'เลือกไฟล์ที่จะเริ่มดาวน์โหลด', - 'Select to download': 'เลือกให้ดาวน์โหลด', -// settings modal - 'Aria2 RPC host and port': 'โฮสต์และพอร์ตของ Aria2 RPC', - 'Enter the host': 'ป้อนโฮสต์', - 'Enter the IP or DNS name of the server on which the RPC for Aria2 is running (default: localhost)': - '', - 'Enter the port': 'ป้อนพอร์ต', - 'Enter the port of the server on which the RPC for Aria2 is running (default: 6800)': - '', - 'Enter the RPC path': 'ป้อนเส้นทาง RPC', - 'Enter the path for the Aria2 RPC endpoint (default: /jsonrpc)': '', - 'SSL/TLS encryption': 'การเข้ารหัสลับ SSL/TLS', - 'Enable SSL/TLS encryption': 'เปิดใช้การเข้ารหัสลับ SSL/TLS', - 'Enter the secret token (optional)': 'ป้อนสัญลักษณ์ความลับ (เป็นตัวเลือก)', - 'Enter the Aria2 RPC secret token (leave empty if authentication is not enabled)': - '', - 'Enter the username (optional)': 'ป้อนเชื่อ (เป็นตัวเลือก)', - 'Enter the Aria2 RPC username (empty if authentication not enabled)': - '', - 'Enter the password (optional)': 'ป้อนรหัสผ่าน (เป็นตัวเลือก)', - 'Enter the Aria2 RPC password (empty if authentication not enabled)': '', - 'Enter base URL (optional)': 'ป้อน URL หลัก (เป็นตัวเลือก)', - 'Direct Download': 'ดาวน์โหลดโดยตรง', - 'If supplied, links will be created to enable direct download from the Aria2 server.': - '', - '(Requires appropriate webserver to be configured.)': '', - 'Save Connection configuration': 'บันทึกการตั้งค่าการเชื่อมต่อ', - 'Filter': 'กรอง', -// server info modal - 'Aria2 server info': 'ข้อมูลเซอร์เวอร์ Aria2', - 'Aria2 Version': 'รุ่น Aria2', - 'Features Enabled': 'คุณสมบัติที่เปิดใช้งาน', -// about modal - 'To download the latest version of the project, add issues or to contribute back, head on to': - 'ให้ดาวน์โหลดรุ่นสุดท้ายของโครงการ เพิ่มปัญหา หรือช่วยเหลือมีส่วนร่วม ไปสู่', - 'Or you can open the latest version in the browser through': 'หรือเปิดรุ่นสุดท้ายในเบราว์เซอร์โดยใช้', - 'Close': 'ปิด' + // header + Search: "ค้นหา", + // Nav menu + Add: "เพื่ม", + "By URIs": "ด้วยยูอาร์ไอ", + "By Torrents": "ด้วยทอร์เรนต์", + "By Metalinks": "ด้วยเมทาลิงค์", + Manage: "บริหาร", + "Pause All": "หยุดชั่วคราวหมด", + "Resume Paused": "ไปต่อหมด", + "Purge Completed": "ลบอันเสร็จ", + Settings: "ตั้งค่า", + "Connection Settings": "ตั้งค่าเชื่อมต่อ", + "Global Settings": "ตั้งค่าทั่วไป", + "Server info": "ข้อมูลเซอร์เวอร์", + "About and contribute": "เกี่ยวกับและช่วย", + "Toggle navigation": "สลับนำทาง", + Language: "ภาษา", + // body + // nav side bar + Miscellaneous: "เบ็ดเตล็ด", + "Global Statistics": "สถิติทั่วไป", + About: "เกี่ยวกับ", + Displaying: "แแสดงดาวน์โหลด", + of: "อันใน", + downloads: "อันทั้งหมด", + // download filters + "Download Filters": "กรองดาวน์โหลด", + Running: "กำลังทำงาน", + Active: "ใช้งานอยู่", + Waiting: "กำลังรอ", + Complete: "เสร็จ", + Error: "ผิดพลาด", + Paused: "หยุดอยู่", + Removed: "ลบแล้ว", + "Hide linked meta-data": "ซ่อนข้อมูลเมตาที่เชื่อมโยง", + Toggle: "สลับ", + "Reset filters": "รีเซตตัวกรอง", + // starred properties + "Quick Access Settings": "ตั้งค่าอย่างรวดเร็ว", + "Save settings": "บันทึกการตั้งค่า", + "Currently no download in line to display, use the": + "ตอนนี้ไม่มีการดาวน์โหลดที่แสดงได้ ก็ใช้ปุ่ม", + "download button to start downloading files!": "ให้เริ่มดาวน์โหลดไฟล์", + Peers: "พีร์ส", + "More Info": "ข้อมูลเพิ่ม", + Remove: "ลบ", + "# of": "จำนวน", + Length: "ความยาว", + // modals + "Add Downloads By URIs": "เพิ่มดาวน์โหลดด้วยยูอาร์ไอ", + "- You can add multiple downloads (files) at the same time by putting URIs for each file on a separate line.": + "", + "- You can also add multiple URIs (mirrors) for the *same* file. To do this, separate the URIs by a space.": + "", + "- A URI can be HTTP(S)/FTP/BitTorrent-Magnet.": "", + "Download settings": "ตั้งค่าการดาวน์โหลด", + "Advanced settings": "ตั้งค่าขั้นสูง", + Cancel: "ยกเลิก", + Start: "เริ่มต้น", + Choose: "เลือก", + "Quick Access (shown on the main page)": "ใช้งานอย่างรวดเร็ว (แสดงที่เพจหลัก)", + // add torrent modal + "Add Downloads By Torrents": "เพิ่มดาวน์โหลดด้วยทอร์เรนต์", + "- Select the torrent from the local filesystem to start the download.": "", + "- You can select multiple torrents to start multiple downloads.": "", + "- To add a BitTorrent-Magnet URL, use the Add By URI option and add it there.": "", + "Select Torrents": "เลือกทอร์เรนต์", + "Select a Torrent": "เลือกทอร์เรนต์", + // add metalink modal + "Add Downloads By Metalinks": "เพิ่มดาวน์โหลดด้วยเมทาลิงค์", + "Select Metalinks": "เลือกเมทาลิงค์", + "- Select the Metalink from the local filesystem to start the download.": "", + "- You can select multiple Metalinks to start multiple downloads.": "", + "Select a Metalink": "เลือกเมทาลิงค์", + // select file modal + "Choose files to start download for": "เลือกไฟล์ที่จะเริ่มดาวน์โหลด", + "Select to download": "เลือกให้ดาวน์โหลด", + // settings modal + "Aria2 RPC host and port": "โฮสต์และพอร์ตของ Aria2 RPC", + "Enter the host": "ป้อนโฮสต์", + "Enter the IP or DNS name of the server on which the RPC for Aria2 is running (default: localhost)": + "", + "Enter the port": "ป้อนพอร์ต", + "Enter the port of the server on which the RPC for Aria2 is running (default: 6800)": "", + "Enter the RPC path": "ป้อนเส้นทาง RPC", + "Enter the path for the Aria2 RPC endpoint (default: /jsonrpc)": "", + "SSL/TLS encryption": "การเข้ารหัสลับ SSL/TLS", + "Enable SSL/TLS encryption": "เปิดใช้การเข้ารหัสลับ SSL/TLS", + "Enter the secret token (optional)": "ป้อนสัญลักษณ์ความลับ (เป็นตัวเลือก)", + "Enter the Aria2 RPC secret token (leave empty if authentication is not enabled)": "", + "Enter the username (optional)": "ป้อนเชื่อ (เป็นตัวเลือก)", + "Enter the Aria2 RPC username (empty if authentication not enabled)": "", + "Enter the password (optional)": "ป้อนรหัสผ่าน (เป็นตัวเลือก)", + "Enter the Aria2 RPC password (empty if authentication not enabled)": "", + "Enter base URL (optional)": "ป้อน URL หลัก (เป็นตัวเลือก)", + "Direct Download": "ดาวน์โหลดโดยตรง", + "If supplied, links will be created to enable direct download from the Aria2 server.": "", + "(Requires appropriate webserver to be configured.)": "", + "Save Connection configuration": "บันทึกการตั้งค่าการเชื่อมต่อ", + Filter: "กรอง", + // server info modal + "Aria2 server info": "ข้อมูลเซอร์เวอร์ Aria2", + "Aria2 Version": "รุ่น Aria2", + "Features Enabled": "คุณสมบัติที่เปิดใช้งาน", + // about modal + "To download the latest version of the project, add issues or to contribute back, head on to": + "ให้ดาวน์โหลดรุ่นสุดท้ายของโครงการ เพิ่มปัญหา หรือช่วยเหลือมีส่วนร่วม ไปสู่", + "Or you can open the latest version in the browser through": + "หรือเปิดรุ่นสุดท้ายในเบราว์เซอร์โดยใช้", + Close: "ปิด" }; diff --git a/js/translate/tr_TR.js b/js/translate/tr_TR.js index b7009244..79d6baf7 100644 --- a/js/translate/tr_TR.js +++ b/js/translate/tr_TR.js @@ -1,140 +1,156 @@ -if(typeof translations == 'undefined'){ - translations = {}; +if (typeof translations == "undefined") { + translations = {}; } translations.tr_TR = { -// header - 'Search': 'Arama', - // Nav menu - 'Add': 'Ekle', - 'By URIs': 'URI ile', - 'By Torrents': 'Torrent ile', - 'By Metalinks': 'Metalink ile', - 'Manage': 'Yönet', - 'Pause All': 'Hepsini Duraklat', - 'Resume Paused': 'Devam Et', - 'Purge Completed': 'Temizleme Tamamlandı', - 'Settings': 'Ayarlar', - 'Connection Settings': 'Bağlantı Ayarları', - 'Global Settings': 'Genel Ayarlar', - 'Server info': 'Sunucu bilgisi', - 'About and contribute': 'Hakkında ve katkıda bulunanlar', - 'Toggle navigation': 'Gezinmeyi aç / kapat', -// body -// nav side bar - 'Miscellaneous': 'Çeşitli', - 'Global Statistics': 'Genel İstatistikler', - 'About': 'Hakkında', - 'Displaying': 'Gösteriliyor', - 'of': ' / ', - 'downloads': 'Indirme', - 'Language': 'Dil', -// download filters - 'Download Filters': 'İndirme Filtreleri', - 'Running': 'Çalışıyor', - 'Active': 'Aktif', - 'Waiting': 'Bekliyor', - 'Complete': 'Tamamlandı', - 'Error': 'Hata', - 'Paused': 'Duraklatıldı', - 'Removed': 'Silindi', - 'Hide linked meta-data': 'Bağlı meta verileri gizle', - 'Toggle': 'aç/kapat', - 'Reset filters': 'Filtreleri sıfırla', -// starred properties - 'Quick Access Settings': 'Hızlı Erişim Ayarları', - 'Save settings': 'Ayarları kaydet', - 'Currently no download in line to display, use the': 'Şu anda görüntülenebilecek bir indirme yok,', - 'download button to start downloading files!': 'butonu aracılığı ile dosya indirebilirsiniz!', - 'Peers': 'Peers', - 'More Info': 'Daha fazla bilgi', - 'Remove': 'Kaldır', - '# of': '# dan', - 'Length': 'Uzunluk', -// modals - 'Add Downloads By URIs': 'URI kullanarak indirmelere ekle', - '- You can add multiple downloads (files) at the same time by putting URIs for each file on a separate line.': - '- Ayrı bir satıra her dosya için URI koyarak aynı anda birden fazla dosya indirebilirsiniz.', - '- You can also add multiple URIs (mirrors) for the *same* file. To do this, separate the URIs by a space.': - '- Aynı dosyalar için birden fazla URI (ayna) da ekleyebilirsiniz. Bunu yapmak için URIları bir boşlukla ayırın.', - '- A URI can be HTTP(S)/FTP/BitTorrent-Magnet.': '- Bir URI, HTTP(S)/FTP/BitTorrent-Magnet olabilir.', - 'Download settings': 'İndirme ayarları', - 'Advanced settings': 'Gelişmiş Ayarlar', - 'Cancel': 'İptal et', - 'Start': 'Başlat', - 'Choose': 'Seçiniz', - 'Quick Access (shown on the main page)': 'Hızlı Erişim (ana sayfada gösterilir)', -// add torrent modal - 'Add Downloads By Torrents': 'Torrent kullanarak indirmelere ekle', - '- Select the torrent from the local filesystem to start the download.': '- İndirmeyi başlatmak için yerel dosya sisteminden torrenti seçin.', - '- You can select multiple torrents to start multiple downloads.': '- Birden çok indirmeyi başlatmak için birden çok torrent seçebilirsiniz.', - '- To add a BitTorrent-Magnet URL, use the Add By URI option and add it there.': '- BitTorrent-Magnetli bir URL eklemek için, İstek Üzerine Ekle seçeneğini kullanın ve oraya ekleyin.', - 'Select Torrents': 'Torrentleri seçin', - 'Select a Torrent': 'Bir Torrent seçin', -// add metalink modal - 'Add Downloads By Metalinks': 'Metalink kullanarak indirmelere ekle', - 'Select Metalinks': 'Metalinkleri seçin', - '- Select the Metalink from the local filesystem to start the download.': '- İndirmeyi başlatmak için yerel dosya sisteminden Metalinki seçin.', - '- You can select multiple Metalinks to start multiple downloads.': '- Birden fazla yüklemeye başlamak için birden fazla Metalink seçebilirsiniz.', - 'Select a Metalink': 'Bir Metalink Seç', -// select file modal - 'Choose files to start download for': 'Için indirmeye başlamak için dosyaları seçin', - 'Select to download': 'Indirmek için seçin', -// settings modal - 'Aria2 RPC host and port': 'Aria2 RPC ana bilgisayar ve bağlantı noktası', - 'Enter the host': 'Ana bilgisayar(host) girin', - 'Enter the IP or DNS name of the server on which the RPC for Aria2 is running (default: localhost)': - 'Aria2 için RPC\'nin çalıştığı sunucunun IP veya DNS adını girin (varsayılan: localhost)', - 'Enter the port': 'Bağlantı noktasını gir', - 'Enter the port of the server on which the RPC for Aria2 is running (default: 6800)': - 'Aria2 için RPC\'nin çalıştığı sunucunun bağlantı noktasını girin (varsayılan: 6800)', - 'Enter the RPC path': 'RPC yolunu girin', - 'Enter the path for the Aria2 RPC endpoint (default: /jsonrpc)': 'Aria2 RPC bitiş noktası için yolu girin (varsayılan: / jsonrpc)', - 'SSL/TLS encryption': 'SSL / TLS şifreleme', - 'Enable SSL/TLS encryption': 'SSL / TLS şifrelemeyi etkinleştir', - 'Enter the secret token (optional)': 'Gizli simge girin (isteğe bağlı)', - 'Enter the Aria2 RPC secret token (leave empty if authentication is not enabled)': - 'Aria2 RPC gizli simgesini girin (kimlik doğrulama etkin değilse boş bırakın)', - 'Enter the username (optional)': 'Kullanıcı adını girin (isteğe bağlı)', - 'Enter the Aria2 RPC username (empty if authentication not enabled)': - 'Aria2 RPC kullanıcı adını girin (kimlik doğrulama etkin değilse boş bırakın)', - 'Enter the password (optional)': 'Parolayı girin (isteğe bağlı)', - 'Enter the Aria2 RPC password (empty if authentication not enabled)': 'Aria2 RPC şifresini girin (kimlik doğrulama etkin değilse boş bırakın)', - 'Enter base URL (optional)': 'Temel URL\'yi girin (isteğe bağlı)', - 'Direct Download': 'Direkt indirme', - 'If supplied, links will be created to enable direct download from the Aria2 server.': - 'Verilen, bağlantıları aria2 sunucudan doğrudan indirmeyi etkinleştirmek için oluşturulur.', - '(Requires appropriate webserver to be configured.)': '(Uygun web sunucusunun yapılandırılmasını gerektirir.)', - 'Save Connection configuration': 'Bağlantı yapılandırmasını kaydedin', - 'Filter':'Filtre', -// server info modal - 'Aria2 server info': 'Aria2 sunucu bilgisi', - 'Aria2 Version': 'Aria2 Sürümü', - 'Features Enabled': 'Aşağıdaki Özellikler Etkin', -// about modal - 'To download the latest version of the project, add issues or to contribute back, head on to': - 'Projenin en son sürümünü indirmek için sorun ekleyin veya katkıda bulunun;', - 'Or you can open the latest version in the browser through': 'Veya en son sürümü tarayıcınız aracılığıyla açabilirsiniz.', - 'Close': 'Kapat', -// lables - 'Download status':'İndirme durumu', - 'Download Speed':'İndirme hızı', - 'Upload Speed':'Yükleme hızı', - 'Estimated time':'Tahmini süre', - 'Download Size':'İndirme Boyutu', - 'Downloaded':'İndirildi', - 'Progress':'İlerleme', - 'Download Path':'İndirme Yolu', - 'Uploaded':'Yüklendi', - 'Download GID':'GID\'yi indirin', - 'Number of Pieces':'Parça sayısı', - 'Piece Length': 'Parça Uzunluğu', - 'Shutdown Server': 'Sunucuyu Kapat', + // header + Search: "Arama", + // Nav menu + Add: "Ekle", + "By URIs": "URI ile", + "By Torrents": "Torrent ile", + "By Metalinks": "Metalink ile", + Manage: "Yönet", + "Pause All": "Hepsini Duraklat", + "Resume Paused": "Devam Et", + "Purge Completed": "Temizleme Tamamlandı", + Settings: "Ayarlar", + "Connection Settings": "Bağlantı Ayarları", + "Global Settings": "Genel Ayarlar", + "Server info": "Sunucu bilgisi", + "About and contribute": "Hakkında ve katkıda bulunanlar", + "Toggle navigation": "Gezinmeyi aç / kapat", + // body + // nav side bar + Miscellaneous: "Çeşitli", + "Global Statistics": "Genel İstatistikler", + About: "Hakkında", + Displaying: "Gösteriliyor", + of: " / ", + downloads: "Indirme", + Language: "Dil", + // download filters + "Download Filters": "İndirme Filtreleri", + Running: "Çalışıyor", + Active: "Aktif", + Waiting: "Bekliyor", + Complete: "Tamamlandı", + Error: "Hata", + Paused: "Duraklatıldı", + Removed: "Silindi", + "Hide linked meta-data": "Bağlı meta verileri gizle", + Toggle: "aç/kapat", + "Reset filters": "Filtreleri sıfırla", + // starred properties + "Quick Access Settings": "Hızlı Erişim Ayarları", + "Save settings": "Ayarları kaydet", + "Currently no download in line to display, use the": + "Şu anda görüntülenebilecek bir indirme yok,", + "download button to start downloading files!": "butonu aracılığı ile dosya indirebilirsiniz!", + Peers: "Peers", + "More Info": "Daha fazla bilgi", + Remove: "Kaldır", + "# of": "# dan", + Length: "Uzunluk", + // modals + "Add Downloads By URIs": "URI kullanarak indirmelere ekle", + "- You can add multiple downloads (files) at the same time by putting URIs for each file on a separate line.": + "- Ayrı bir satıra her dosya için URI koyarak aynı anda birden fazla dosya indirebilirsiniz.", + "- You can also add multiple URIs (mirrors) for the *same* file. To do this, separate the URIs by a space.": + "- Aynı dosyalar için birden fazla URI (ayna) da ekleyebilirsiniz. Bunu yapmak için URIları bir boşlukla ayırın.", + "- A URI can be HTTP(S)/FTP/BitTorrent-Magnet.": + "- Bir URI, HTTP(S)/FTP/BitTorrent-Magnet olabilir.", + "Download settings": "İndirme ayarları", + "Advanced settings": "Gelişmiş Ayarlar", + Cancel: "İptal et", + Start: "Başlat", + Choose: "Seçiniz", + "Quick Access (shown on the main page)": "Hızlı Erişim (ana sayfada gösterilir)", + // add torrent modal + "Add Downloads By Torrents": "Torrent kullanarak indirmelere ekle", + "- Select the torrent from the local filesystem to start the download.": + "- İndirmeyi başlatmak için yerel dosya sisteminden torrenti seçin.", + "- You can select multiple torrents to start multiple downloads.": + "- Birden çok indirmeyi başlatmak için birden çok torrent seçebilirsiniz.", + "- To add a BitTorrent-Magnet URL, use the Add By URI option and add it there.": + "- BitTorrent-Magnetli bir URL eklemek için, İstek Üzerine Ekle seçeneğini kullanın ve oraya ekleyin.", + "Select Torrents": "Torrentleri seçin", + "Select a Torrent": "Bir Torrent seçin", + // add metalink modal + "Add Downloads By Metalinks": "Metalink kullanarak indirmelere ekle", + "Select Metalinks": "Metalinkleri seçin", + "- Select the Metalink from the local filesystem to start the download.": + "- İndirmeyi başlatmak için yerel dosya sisteminden Metalinki seçin.", + "- You can select multiple Metalinks to start multiple downloads.": + "- Birden fazla yüklemeye başlamak için birden fazla Metalink seçebilirsiniz.", + "Select a Metalink": "Bir Metalink Seç", + // select file modal + "Choose files to start download for": "Için indirmeye başlamak için dosyaları seçin", + "Select to download": "Indirmek için seçin", + // settings modal + "Aria2 RPC host and port": "Aria2 RPC ana bilgisayar ve bağlantı noktası", + "Enter the host": "Ana bilgisayar(host) girin", + "Enter the IP or DNS name of the server on which the RPC for Aria2 is running (default: localhost)": + "Aria2 için RPC'nin çalıştığı sunucunun IP veya DNS adını girin (varsayılan: localhost)", + "Enter the port": "Bağlantı noktasını gir", + "Enter the port of the server on which the RPC for Aria2 is running (default: 6800)": + "Aria2 için RPC'nin çalıştığı sunucunun bağlantı noktasını girin (varsayılan: 6800)", + "Enter the RPC path": "RPC yolunu girin", + "Enter the path for the Aria2 RPC endpoint (default: /jsonrpc)": + "Aria2 RPC bitiş noktası için yolu girin (varsayılan: / jsonrpc)", + "SSL/TLS encryption": "SSL / TLS şifreleme", + "Enable SSL/TLS encryption": "SSL / TLS şifrelemeyi etkinleştir", + "Enter the secret token (optional)": "Gizli simge girin (isteğe bağlı)", + "Enter the Aria2 RPC secret token (leave empty if authentication is not enabled)": + "Aria2 RPC gizli simgesini girin (kimlik doğrulama etkin değilse boş bırakın)", + "Enter the username (optional)": "Kullanıcı adını girin (isteğe bağlı)", + "Enter the Aria2 RPC username (empty if authentication not enabled)": + "Aria2 RPC kullanıcı adını girin (kimlik doğrulama etkin değilse boş bırakın)", + "Enter the password (optional)": "Parolayı girin (isteğe bağlı)", + "Enter the Aria2 RPC password (empty if authentication not enabled)": + "Aria2 RPC şifresini girin (kimlik doğrulama etkin değilse boş bırakın)", + "Enter base URL (optional)": "Temel URL'yi girin (isteğe bağlı)", + "Direct Download": "Direkt indirme", + "If supplied, links will be created to enable direct download from the Aria2 server.": + "Verilen, bağlantıları aria2 sunucudan doğrudan indirmeyi etkinleştirmek için oluşturulur.", + "(Requires appropriate webserver to be configured.)": + "(Uygun web sunucusunun yapılandırılmasını gerektirir.)", + "Save Connection configuration": "Bağlantı yapılandırmasını kaydedin", + Filter: "Filtre", + // server info modal + "Aria2 server info": "Aria2 sunucu bilgisi", + "Aria2 Version": "Aria2 Sürümü", + "Features Enabled": "Aşağıdaki Özellikler Etkin", + // about modal + "To download the latest version of the project, add issues or to contribute back, head on to": + "Projenin en son sürümünü indirmek için sorun ekleyin veya katkıda bulunun;", + "Or you can open the latest version in the browser through": + "Veya en son sürümü tarayıcınız aracılığıyla açabilirsiniz.", + Close: "Kapat", + // lables + "Download status": "İndirme durumu", + "Download Speed": "İndirme hızı", + "Upload Speed": "Yükleme hızı", + "Estimated time": "Tahmini süre", + "Download Size": "İndirme Boyutu", + Downloaded: "İndirildi", + Progress: "İlerleme", + "Download Path": "İndirme Yolu", + Uploaded: "Yüklendi", + "Download GID": "GID'yi indirin", + "Number of Pieces": "Parça sayısı", + "Piece Length": "Parça Uzunluğu", + "Shutdown Server": "Sunucuyu Kapat", - 'The last connection attempt was unsuccessful. Trying another configuration': 'Son bağlantı girişimi başarısız oldu. Başka bir yapılandırma deneyin', - 'Oh Snap!': 'HAydaaaaa!', - 'Could not connect to the aria2 RPC server. Will retry in 10 secs. You might want to check the connection settings by going to Settings > Connection Settings': 'Aria2 RPC sunucusuna bağlanılamadı. 10 saniye içinde tekrar deneyecek. Bağlantı ayarlarını, Ayarlar> Bağlantı Ayarları bölümüne giderek kontrol etmek isteyebilirsiniz.', - 'Successfully connected to Aria2 through its remote RPC …': 'Uzak RPC aracılığıyla Aria2\'ye başarıyla bağlandı ...', - 'Successfully connected to Aria2 through remote RPC, however the connection is still insecure. For complete security try adding an authorization secret token while starting Aria2 (through the flag --rpc-secret)': 'Uzak RPC aracılığıyla Aria2\'ye başarıyla bağlandı ancak bağlantı hala güvende değil. Tam güvenlik için, Aria2\'yi başlatırken (--rpc-secret bayrağını kullanın) ve bir yetkilendirme gizli simgesi eklemeyi deneyin.', - 'Trying to connect to aria2 using the new connection configuration': 'Yeni bağlantı yapılandırmasını kullanarak aria2\'ye bağlanmaya çalışılıyor', + "The last connection attempt was unsuccessful. Trying another configuration": + "Son bağlantı girişimi başarısız oldu. Başka bir yapılandırma deneyin", + "Oh Snap!": "HAydaaaaa!", + "Could not connect to the aria2 RPC server. Will retry in 10 secs. You might want to check the connection settings by going to Settings > Connection Settings": + "Aria2 RPC sunucusuna bağlanılamadı. 10 saniye içinde tekrar deneyecek. Bağlantı ayarlarını, Ayarlar> Bağlantı Ayarları bölümüne giderek kontrol etmek isteyebilirsiniz.", + "Successfully connected to Aria2 through its remote RPC …": + "Uzak RPC aracılığıyla Aria2'ye başarıyla bağlandı ...", + "Successfully connected to Aria2 through remote RPC, however the connection is still insecure. For complete security try adding an authorization secret token while starting Aria2 (through the flag --rpc-secret)": + "Uzak RPC aracılığıyla Aria2'ye başarıyla bağlandı ancak bağlantı hala güvende değil. Tam güvenlik için, Aria2'yi başlatırken (--rpc-secret bayrağını kullanın) ve bir yetkilendirme gizli simgesi eklemeyi deneyin.", + "Trying to connect to aria2 using the new connection configuration": + "Yeni bağlantı yapılandırmasını kullanarak aria2'ye bağlanmaya çalışılıyor" }; diff --git a/js/translate/zh_CN.js b/js/translate/zh_CN.js index 1fb534eb..4413e311 100644 --- a/js/translate/zh_CN.js +++ b/js/translate/zh_CN.js @@ -1,154 +1,159 @@ -if(typeof translations == 'undefined'){ - translations = {}; +if (typeof translations == "undefined") { + translations = {}; } translations.zh_CN = { -// header - 'Search': '搜索', - // Nav menu - 'Add': '添加', - 'By URIs': '使用链接', - 'By Torrents': '使用种子', - 'By Metalinks': '使用 Metalink', - 'Manage': '管理', - 'Pause All': '暂停所有', - 'Resume Paused': '恢复下载', - 'Purge Completed': '清除已完成', - 'Shutdown Server': '关闭服务器', - 'Settings': '设置', - 'Connection Settings': '连接设置', - 'Global Settings': '全局设置', - 'Server info': '服务器信息', - 'About and contribute': '关于和捐助', - 'Toggle navigation': '切换导航', -// body -// nav side bar - 'Miscellaneous': '杂项', - 'Global Statistics': '全局统计', - 'About': '关于', - 'Displaying': '正在显示', - 'of': '/', - 'downloads': '下载', - 'Language': '语言', -// download filters - 'Download Filters': '下载过滤器', - 'Running': '运行中', - 'Active': '活动的', - 'Waiting': '等待中', - 'Complete': '已完成', - 'Error': '出错的', - 'Paused': '已暂停', - 'Removed': '已删除', - 'Hide linked meta-data': '隐藏连接的元数据', - 'Toggle': '反向选择', - 'Reset filters': '重置过滤器', -// download status - 'Verifing': '正在验证', - 'Verify Pending': '等待验证', -// starred properties - 'Quick Access Settings': '快速访问设置', - 'Save': '保存', - 'Save settings': '保存设置', - 'Currently no download in line to display, use the': '当前没有可显示的下载项,使用', - 'download button to start downloading files!': '按钮来开始下载!', - 'Peers': 'Peers', - 'More Info': '更多信息', - 'Remove': '删除', - '# of': '块数', - 'Length': '块大小', -// modals - 'Add Downloads By URIs': '使用链接下载', - '- You can add multiple downloads (files) at the same time by putting URIs for each file on a separate line.': - '- 你可以同时添加多个文件下载任务,每行下载一个文件;', - '- You can also add multiple URIs (mirrors) for the *same* file. To do this, separate the URIs by a space.': - '- 你也可以给同一个下载任务添加多个镜像链接,写在一行并用空格分隔每条链接;', - '- A URI can be HTTP(S)/FTP/BitTorrent-Magnet.': '- 链接可以是 HTTP(S)、FTP 和磁力链接。', - 'Download settings': '下载设置', - 'Advanced settings': '高级设置', - 'Cancel': '取消', - 'Start': '开始', - 'Choose': '选择', - 'Quick Access (shown on the main page)': '快速访问(在主页上显示)', -// add torrent modal - 'Add Downloads By Torrents': '使用种子下载', - '- Select the torrent from the local filesystem to start the download.': '- 从本地文件系统选择种子文件开始下载;', - '- You can select multiple torrents to start multiple downloads.': '- 你可以同时选择多个种子来启动多个下载;', - '- To add a BitTorrent-Magnet URL, use the Add By URI option and add it there.': '- 如果要添加磁力链接,请使用添加链接的方式。', - 'Select Torrents': '选择种子文件', - 'Select a Torrent': '选择种子文件', -// add metalink modal - 'Add Downloads By Metalinks': '使用 Metalink 下载', - 'Select Metalinks': '选择 Metalink 文件', - '- Select the Metalink from the local filesystem to start the download.': '* 从本地文件系统选择 Metalink 文件开始下载;', - '- You can select multiple Metalinks to start multiple downloads.': '* 你可以同时选择多个 Metalink 文件来启动多个下载。', - 'Select a Metalink': '选择 Metalink 文件', -// select file modal - 'Choose files to start download for': '请选择要下载的文件', - 'Select to download': '选择以下载', -// settings modal - 'Aria2 RPC host and port': 'Aria2 RPC 主机和端口', - 'Enter the host': '主机', - 'Enter the IP or DNS name of the server on which the RPC for Aria2 is running (default: localhost)': - '输入 Aria2 RPC 所在服务器的 IP 或域名(默认:localhost)', - 'Enter the port': '端口', - 'Enter the port of the server on which the RPC for Aria2 is running (default: 6800)': - '输入 Aria2 RPC 端口号(默认:6800)', - 'Enter the RPC path': 'RPC 路径', - 'Enter the path for the Aria2 RPC endpoint (default: /jsonrpc)': '输入 Aria2 RPC 路径(默认:/jsonrpc)', - 'SSL/TLS encryption': 'SSL/TLS 加密', - 'Enable SSL/TLS encryption': '启用 SSL/TLS 加密', - 'Enter the secret token (optional)': '密码令牌(可选)', - 'Enter the Aria2 RPC secret token (leave empty if authentication is not enabled)': - '输入 Aria2 RPC 密码令牌(如果未启用则留空)', - 'Enter the username (optional)': '用户名(可选)', - 'Enter the Aria2 RPC username (empty if authentication not enabled)': - '输入 Aria2 RPC 用户名(如果未启用身份验证则留空)', - 'Enter the password (optional)': '密码(可选)', - 'Enter the Aria2 RPC password (empty if authentication not enabled)': '输入 Aria2 RPC 密码(如果未启用身份验证则留空)', - 'Enter base URL (optional)': '基本链接地址(可选)', - 'Direct Download': '直接下载', - 'If supplied, links will be created to enable direct download from the Aria2 server.': - '如果指定该选项,将会创建可以直接从 Aria2 服务器上下载文件的链接。', - '(Requires appropriate webserver to be configured.)': '(需要 WEB 服务器配置正确)', - 'Save Connection configuration': '保存连接配置', - 'Filter':'过滤', -// server info modal - 'Aria2 server info': 'Aria2 服务器信息', - 'Aria2 Version': 'Aria2 版本', - 'Features Enabled': '已启用功能', -// about modal - 'To download the latest version of the project, add issues or to contribute back, head on to': - '下载最新版本、提交问题或捐助,请访问', - 'Or you can open the latest version in the browser through': '直接在浏览器中使用最新版本,请访问', - 'Close': '关闭', -// labels - 'Download status':'当前下载状态', - 'Download Speed':'当前下载速度', - 'Upload Speed':'当前上传速度', - 'Estimated time':'预计剩余时间', - 'Download Size':'下载总大小', - 'Downloaded':'已下载大小', - 'Progress':'当前下载进度', - 'Download Path':'文件下载路径', - 'Uploaded':'已上传大小', - 'Download GID':'下载的 GID', - 'Number of Pieces':'文件块数量', - 'Piece Length':'每块大小', + // header + Search: "搜索", + // Nav menu + Add: "添加", + "By URIs": "使用链接", + "By Torrents": "使用种子", + "By Metalinks": "使用 Metalink", + Manage: "管理", + "Pause All": "暂停所有", + "Resume Paused": "恢复下载", + "Purge Completed": "清除已完成", + "Shutdown Server": "关闭服务器", + Settings: "设置", + "Connection Settings": "连接设置", + "Global Settings": "全局设置", + "Server info": "服务器信息", + "About and contribute": "关于和捐助", + "Toggle navigation": "切换导航", + // body + // nav side bar + Miscellaneous: "杂项", + "Global Statistics": "全局统计", + About: "关于", + Displaying: "正在显示", + of: "/", + downloads: "下载", + Language: "语言", + // download filters + "Download Filters": "下载过滤器", + Running: "运行中", + Active: "活动的", + Waiting: "等待中", + Complete: "已完成", + Error: "出错的", + Paused: "已暂停", + Removed: "已删除", + "Hide linked meta-data": "隐藏连接的元数据", + Toggle: "反向选择", + "Reset filters": "重置过滤器", + // download status + Verifing: "正在验证", + "Verify Pending": "等待验证", + // starred properties + "Quick Access Settings": "快速访问设置", + Save: "保存", + "Save settings": "保存设置", + "Currently no download in line to display, use the": "当前没有可显示的下载项,使用", + "download button to start downloading files!": "按钮来开始下载!", + Peers: "Peers", + "More Info": "更多信息", + Remove: "删除", + "# of": "块数", + Length: "块大小", + // modals + "Add Downloads By URIs": "使用链接下载", + "- You can add multiple downloads (files) at the same time by putting URIs for each file on a separate line.": + "- 你可以同时添加多个文件下载任务,每行下载一个文件;", + "- You can also add multiple URIs (mirrors) for the *same* file. To do this, separate the URIs by a space.": + "- 你也可以给同一个下载任务添加多个镜像链接,写在一行并用空格分隔每条链接;", + "- A URI can be HTTP(S)/FTP/BitTorrent-Magnet.": "- 链接可以是 HTTP(S)、FTP 和磁力链接。", + "Download settings": "下载设置", + "Advanced settings": "高级设置", + Cancel: "取消", + Start: "开始", + Choose: "选择", + "Quick Access (shown on the main page)": "快速访问(在主页上显示)", + // add torrent modal + "Add Downloads By Torrents": "使用种子下载", + "- Select the torrent from the local filesystem to start the download.": + "- 从本地文件系统选择种子文件开始下载;", + "- You can select multiple torrents to start multiple downloads.": + "- 你可以同时选择多个种子来启动多个下载;", + "- To add a BitTorrent-Magnet URL, use the Add By URI option and add it there.": + "- 如果要添加磁力链接,请使用添加链接的方式。", + "Select Torrents": "选择种子文件", + "Select a Torrent": "选择种子文件", + // add metalink modal + "Add Downloads By Metalinks": "使用 Metalink 下载", + "Select Metalinks": "选择 Metalink 文件", + "- Select the Metalink from the local filesystem to start the download.": + "* 从本地文件系统选择 Metalink 文件开始下载;", + "- You can select multiple Metalinks to start multiple downloads.": + "* 你可以同时选择多个 Metalink 文件来启动多个下载。", + "Select a Metalink": "选择 Metalink 文件", + // select file modal + "Choose files to start download for": "请选择要下载的文件", + "Select to download": "选择以下载", + // settings modal + "Aria2 RPC host and port": "Aria2 RPC 主机和端口", + "Enter the host": "主机", + "Enter the IP or DNS name of the server on which the RPC for Aria2 is running (default: localhost)": + "输入 Aria2 RPC 所在服务器的 IP 或域名(默认:localhost)", + "Enter the port": "端口", + "Enter the port of the server on which the RPC for Aria2 is running (default: 6800)": + "输入 Aria2 RPC 端口号(默认:6800)", + "Enter the RPC path": "RPC 路径", + "Enter the path for the Aria2 RPC endpoint (default: /jsonrpc)": + "输入 Aria2 RPC 路径(默认:/jsonrpc)", + "SSL/TLS encryption": "SSL/TLS 加密", + "Enable SSL/TLS encryption": "启用 SSL/TLS 加密", + "Enter the secret token (optional)": "密码令牌(可选)", + "Enter the Aria2 RPC secret token (leave empty if authentication is not enabled)": + "输入 Aria2 RPC 密码令牌(如果未启用则留空)", + "Enter the username (optional)": "用户名(可选)", + "Enter the Aria2 RPC username (empty if authentication not enabled)": + "输入 Aria2 RPC 用户名(如果未启用身份验证则留空)", + "Enter the password (optional)": "密码(可选)", + "Enter the Aria2 RPC password (empty if authentication not enabled)": + "输入 Aria2 RPC 密码(如果未启用身份验证则留空)", + "Enter base URL (optional)": "基本链接地址(可选)", + "Direct Download": "直接下载", + "If supplied, links will be created to enable direct download from the Aria2 server.": + "如果指定该选项,将会创建可以直接从 Aria2 服务器上下载文件的链接。", + "(Requires appropriate webserver to be configured.)": "(需要 WEB 服务器配置正确)", + "Save Connection configuration": "保存连接配置", + Filter: "过滤", + // server info modal + "Aria2 server info": "Aria2 服务器信息", + "Aria2 Version": "Aria2 版本", + "Features Enabled": "已启用功能", + // about modal + "To download the latest version of the project, add issues or to contribute back, head on to": + "下载最新版本、提交问题或捐助,请访问", + "Or you can open the latest version in the browser through": "直接在浏览器中使用最新版本,请访问", + Close: "关闭", + // labels + "Download status": "当前下载状态", + "Download Speed": "当前下载速度", + "Upload Speed": "当前上传速度", + "Estimated time": "预计剩余时间", + "Download Size": "下载总大小", + Downloaded: "已下载大小", + Progress: "当前下载进度", + "Download Path": "文件下载路径", + Uploaded: "已上传大小", + "Download GID": "下载的 GID", + "Number of Pieces": "文件块数量", + "Piece Length": "每块大小", -//alerts - 'The last connection attempt was unsuccessful. Trying another configuration': - '上次连接请求未成功,正在尝试使用另一个配置', - 'Oh Snap!': '糟糕!', - 'Could not connect to the aria2 RPC server. Will retry in 10 secs. You might want to check the connection settings by going to Settings > Connection Settings': - '无法连接到 Aria2 RPC 服务器,将在10秒后重试。您可能需要检查连接设置,请前往 设置 > 连接设置', - 'Authentication failed while connecting to Aria2 RPC server. Will retry in 10 secs. You might want to confirm your authentication details by going to Settings > Connection Settings': - '连接到 Aria2 RPC 服务器时认证失败,将在10秒后重试。您可能需要确认您的身份验证信息,请前往 设置 > 连接设置', - 'Successfully connected to Aria2 through its remote RPC …': - '通过 RPC 连接到 Aria2 成功!', - 'Successfully connected to Aria2 through remote RPC, however the connection is still insecure. For complete security try adding an authorization secret token while starting Aria2 (through the flag --rpc-secret)': - '通过 RPC 连接到 Aria2 成功,但是连接并不安全。要想使用安全连接,尝试在启动 Aria2 时添加一个授权密码令牌(通过 --rpc-secret 参数)', - 'Trying to connect to aria2 using the new connection configuration': - '正在尝试使用新的连接配置来连接到 Aria2 ……', - 'Remove {{name}} and associated meta-data?': - '是否删除 {{name}} 和关联的元数据?' + //alerts + "The last connection attempt was unsuccessful. Trying another configuration": + "上次连接请求未成功,正在尝试使用另一个配置", + "Oh Snap!": "糟糕!", + "Could not connect to the aria2 RPC server. Will retry in 10 secs. You might want to check the connection settings by going to Settings > Connection Settings": + "无法连接到 Aria2 RPC 服务器,将在10秒后重试。您可能需要检查连接设置,请前往 设置 > 连接设置", + "Authentication failed while connecting to Aria2 RPC server. Will retry in 10 secs. You might want to confirm your authentication details by going to Settings > Connection Settings": + "连接到 Aria2 RPC 服务器时认证失败,将在10秒后重试。您可能需要确认您的身份验证信息,请前往 设置 > 连接设置", + "Successfully connected to Aria2 through its remote RPC …": "通过 RPC 连接到 Aria2 成功!", + "Successfully connected to Aria2 through remote RPC, however the connection is still insecure. For complete security try adding an authorization secret token while starting Aria2 (through the flag --rpc-secret)": + "通过 RPC 连接到 Aria2 成功,但是连接并不安全。要想使用安全连接,尝试在启动 Aria2 时添加一个授权密码令牌(通过 --rpc-secret 参数)", + "Trying to connect to aria2 using the new connection configuration": + "正在尝试使用新的连接配置来连接到 Aria2 ……", + "Remove {{name}} and associated meta-data?": "是否删除 {{name}} 和关联的元数据?" }; diff --git a/js/translate/zh_TW.js b/js/translate/zh_TW.js index d035c3ad..243c9042 100644 --- a/js/translate/zh_TW.js +++ b/js/translate/zh_TW.js @@ -1,154 +1,159 @@ -if(typeof translations == 'undefined'){ - translations = {}; +if (typeof translations == "undefined") { + translations = {}; } translations.zh_TW = { -// header - 'Search': '搜尋', - // Nav menu - 'Add': '新增', - 'By URIs': '使用連結', - 'By Torrents': '使用種子', - 'By Metalinks': '使用 Metalink', - 'Manage': '管理', - 'Pause All': '暫停所有', - 'Resume Paused': '恢復下載', - 'Purge Completed': '清除已完成', - 'Shutdown Server': '關閉伺服器', - 'Settings': '設定', - 'Connection Settings': '連線設定', - 'Global Settings': '全域性設定', - 'Server info': '伺服器資訊', - 'About and contribute': '關於和捐助', - 'Toggle navigation': '切換導航', -// body -// nav side bar - 'Miscellaneous': '雜項', - 'Global Statistics': '全域性統計', - 'About': '關於', - 'Displaying': '正在顯示', - 'of': '/', - 'downloads': '下載', - 'Language': '語言', -// download filters - 'Download Filters': '下載過濾器', - 'Running': '執行中', - 'Active': '活動的', - 'Waiting': '等待中', - 'Complete': '已完成', - 'Error': '出錯的', - 'Paused': '已暫停', - 'Removed': '已刪除', - 'Hide linked meta-data': '隱藏連線的元資料', - 'Toggle': '反向選擇', - 'Reset filters': '重置過濾器', -// download status - 'Verifing': '正在驗證', - 'Verify Pending': '等待驗證', -// starred properties - 'Quick Access Settings': '快速訪問設定', - 'Save': '儲存', - 'Save settings': '儲存設定', - 'Currently no download in line to display, use the': '當前沒有可顯示的下載項,使用', - 'download button to start downloading files!': '按鈕來開始下載!', - 'Peers': 'Peers', - 'More Info': '更多資訊', - 'Remove': '刪除', - '# of': '塊數', - 'Length': '塊大小', -// modals - 'Add Downloads By URIs': '使用連結下載', - '- You can add multiple downloads (files) at the same time by putting URIs for each file on a separate line.': - '- 你可以同時新增多個檔案下載任務,每行下載一個檔案;', - '- You can also add multiple URIs (mirrors) for the *same* file. To do this, separate the URIs by a space.': - '- 你也可以給同一個下載任務新增多個映象連結,寫在一行並用空格分隔每條連結;', - '- A URI can be HTTP(S)/FTP/BitTorrent-Magnet.': '- 連結可以是 HTTP(S)、FTP 和磁力連結。', - 'Download settings': '下載設定', - 'Advanced settings': '高階設定', - 'Cancel': '取消', - 'Start': '開始', - 'Choose': '選擇', - 'Quick Access (shown on the main page)': '快速訪問(在主頁上顯示)', -// add torrent modal - 'Add Downloads By Torrents': '使用種子下載', - '- Select the torrent from the local filesystem to start the download.': '- 從本地檔案系統選擇種子檔案開始下載;', - '- You can select multiple torrents to start multiple downloads.': '- 你可以同時選擇多個種子來啟動多個下載;', - '- To add a BitTorrent-Magnet URL, use the Add By URI option and add it there.': '- 如果要新增磁力連結,請使用新增連結的方式。', - 'Select Torrents': '選擇種子檔案', - 'Select a Torrent': '選擇種子檔案', -// add metalink modal - 'Add Downloads By Metalinks': '使用 Metalink 下載', - 'Select Metalinks': '選擇 Metalink 檔案', - '- Select the Metalink from the local filesystem to start the download.': '* 從本地檔案系統選擇 Metalink 檔案開始下載;', - '- You can select multiple Metalinks to start multiple downloads.': '* 你可以同時選擇多個 Metalink 檔案來啟動多個下載。', - 'Select a Metalink': '選擇 Metalink 檔案', -// select file modal - 'Choose files to start download for': '請選擇要下載的檔案', - 'Select to download': '選擇以下載', -// settings modal - 'Aria2 RPC host and port': 'Aria2 RPC 主機和埠', - 'Enter the host': '主機', - 'Enter the IP or DNS name of the server on which the RPC for Aria2 is running (default: localhost)': - '輸入 Aria2 RPC 所在伺服器的 IP 或域名(預設:localhost)', - 'Enter the port': '埠號', - 'Enter the port of the server on which the RPC for Aria2 is running (default: 6800)': - '輸入 Aria2 RPC 埠號(預設:6800)', - 'Enter the RPC path': 'RPC 路徑', - 'Enter the path for the Aria2 RPC endpoint (default: /jsonrpc)': '輸入 Aria2 RPC 路徑(預設:/jsonrpc)', - 'SSL/TLS encryption': 'SSL/TLS 加密', - 'Enable SSL/TLS encryption': '啟用 SSL/TLS 加密', - 'Enter the secret token (optional)': '密碼令牌(可選)', - 'Enter the Aria2 RPC secret token (leave empty if authentication is not enabled)': - '輸入 Aria2 RPC 密碼令牌(如果未啟用則留空)', - 'Enter the username (optional)': '使用者名稱(可選)', - 'Enter the Aria2 RPC username (empty if authentication not enabled)': - '輸入 Aria2 RPC 使用者名稱(如果未啟用身份驗證則留空)', - 'Enter the password (optional)': '密碼(可選)', - 'Enter the Aria2 RPC password (empty if authentication not enabled)': '輸入 Aria2 RPC 密碼(如果未啟用身份驗證則留空)', - 'Enter base URL (optional)': '基本連結地址(可選)', - 'Direct Download': '直接下載', - 'If supplied, links will be created to enable direct download from the Aria2 server.': - '如果指定該選項,將會建立可以直接從 Aria2 伺服器上下載檔案的連結。', - '(Requires appropriate webserver to be configured.)': '(需要 WEB 伺服器配置正確)', - 'Save Connection configuration': '儲存連線配置', - 'Filter':'過濾', -// server info modal - 'Aria2 server info': 'Aria2 伺服器資訊', - 'Aria2 Version': 'Aria2 版本', - 'Features Enabled': '已啟用功能', -// about modal - 'To download the latest version of the project, add issues or to contribute back, head on to': - '下載最新版本、提交問題或捐助,請訪問', - 'Or you can open the latest version in the browser through': '直接在瀏覽器中使用最新版本,請訪問', - 'Close': '關閉', -// labels - 'Download status':'當前下載狀態', - 'Download Speed':'當前下載速度', - 'Upload Speed':'當前上傳速度', - 'Estimated time':'預計剩餘時間', - 'Download Size':'下載總大小', - 'Downloaded':'已下載大小', - 'Progress':'當前下載進度', - 'Download Path':'檔案下載路徑', - 'Uploaded':'已上傳大小', - 'Download GID':'下載的 GID', - 'Number of Pieces':'檔案塊數量', - 'Piece Length':'每塊大小', + // header + Search: "搜尋", + // Nav menu + Add: "新增", + "By URIs": "使用連結", + "By Torrents": "使用種子", + "By Metalinks": "使用 Metalink", + Manage: "管理", + "Pause All": "暫停所有", + "Resume Paused": "恢復下載", + "Purge Completed": "清除已完成", + "Shutdown Server": "關閉伺服器", + Settings: "設定", + "Connection Settings": "連線設定", + "Global Settings": "全域性設定", + "Server info": "伺服器資訊", + "About and contribute": "關於和捐助", + "Toggle navigation": "切換導航", + // body + // nav side bar + Miscellaneous: "雜項", + "Global Statistics": "全域性統計", + About: "關於", + Displaying: "正在顯示", + of: "/", + downloads: "下載", + Language: "語言", + // download filters + "Download Filters": "下載過濾器", + Running: "執行中", + Active: "活動的", + Waiting: "等待中", + Complete: "已完成", + Error: "出錯的", + Paused: "已暫停", + Removed: "已刪除", + "Hide linked meta-data": "隱藏連線的元資料", + Toggle: "反向選擇", + "Reset filters": "重置過濾器", + // download status + Verifing: "正在驗證", + "Verify Pending": "等待驗證", + // starred properties + "Quick Access Settings": "快速訪問設定", + Save: "儲存", + "Save settings": "儲存設定", + "Currently no download in line to display, use the": "當前沒有可顯示的下載項,使用", + "download button to start downloading files!": "按鈕來開始下載!", + Peers: "Peers", + "More Info": "更多資訊", + Remove: "刪除", + "# of": "塊數", + Length: "塊大小", + // modals + "Add Downloads By URIs": "使用連結下載", + "- You can add multiple downloads (files) at the same time by putting URIs for each file on a separate line.": + "- 你可以同時新增多個檔案下載任務,每行下載一個檔案;", + "- You can also add multiple URIs (mirrors) for the *same* file. To do this, separate the URIs by a space.": + "- 你也可以給同一個下載任務新增多個映象連結,寫在一行並用空格分隔每條連結;", + "- A URI can be HTTP(S)/FTP/BitTorrent-Magnet.": "- 連結可以是 HTTP(S)、FTP 和磁力連結。", + "Download settings": "下載設定", + "Advanced settings": "高階設定", + Cancel: "取消", + Start: "開始", + Choose: "選擇", + "Quick Access (shown on the main page)": "快速訪問(在主頁上顯示)", + // add torrent modal + "Add Downloads By Torrents": "使用種子下載", + "- Select the torrent from the local filesystem to start the download.": + "- 從本地檔案系統選擇種子檔案開始下載;", + "- You can select multiple torrents to start multiple downloads.": + "- 你可以同時選擇多個種子來啟動多個下載;", + "- To add a BitTorrent-Magnet URL, use the Add By URI option and add it there.": + "- 如果要新增磁力連結,請使用新增連結的方式。", + "Select Torrents": "選擇種子檔案", + "Select a Torrent": "選擇種子檔案", + // add metalink modal + "Add Downloads By Metalinks": "使用 Metalink 下載", + "Select Metalinks": "選擇 Metalink 檔案", + "- Select the Metalink from the local filesystem to start the download.": + "* 從本地檔案系統選擇 Metalink 檔案開始下載;", + "- You can select multiple Metalinks to start multiple downloads.": + "* 你可以同時選擇多個 Metalink 檔案來啟動多個下載。", + "Select a Metalink": "選擇 Metalink 檔案", + // select file modal + "Choose files to start download for": "請選擇要下載的檔案", + "Select to download": "選擇以下載", + // settings modal + "Aria2 RPC host and port": "Aria2 RPC 主機和埠", + "Enter the host": "主機", + "Enter the IP or DNS name of the server on which the RPC for Aria2 is running (default: localhost)": + "輸入 Aria2 RPC 所在伺服器的 IP 或域名(預設:localhost)", + "Enter the port": "埠號", + "Enter the port of the server on which the RPC for Aria2 is running (default: 6800)": + "輸入 Aria2 RPC 埠號(預設:6800)", + "Enter the RPC path": "RPC 路徑", + "Enter the path for the Aria2 RPC endpoint (default: /jsonrpc)": + "輸入 Aria2 RPC 路徑(預設:/jsonrpc)", + "SSL/TLS encryption": "SSL/TLS 加密", + "Enable SSL/TLS encryption": "啟用 SSL/TLS 加密", + "Enter the secret token (optional)": "密碼令牌(可選)", + "Enter the Aria2 RPC secret token (leave empty if authentication is not enabled)": + "輸入 Aria2 RPC 密碼令牌(如果未啟用則留空)", + "Enter the username (optional)": "使用者名稱(可選)", + "Enter the Aria2 RPC username (empty if authentication not enabled)": + "輸入 Aria2 RPC 使用者名稱(如果未啟用身份驗證則留空)", + "Enter the password (optional)": "密碼(可選)", + "Enter the Aria2 RPC password (empty if authentication not enabled)": + "輸入 Aria2 RPC 密碼(如果未啟用身份驗證則留空)", + "Enter base URL (optional)": "基本連結地址(可選)", + "Direct Download": "直接下載", + "If supplied, links will be created to enable direct download from the Aria2 server.": + "如果指定該選項,將會建立可以直接從 Aria2 伺服器上下載檔案的連結。", + "(Requires appropriate webserver to be configured.)": "(需要 WEB 伺服器配置正確)", + "Save Connection configuration": "儲存連線配置", + Filter: "過濾", + // server info modal + "Aria2 server info": "Aria2 伺服器資訊", + "Aria2 Version": "Aria2 版本", + "Features Enabled": "已啟用功能", + // about modal + "To download the latest version of the project, add issues or to contribute back, head on to": + "下載最新版本、提交問題或捐助,請訪問", + "Or you can open the latest version in the browser through": "直接在瀏覽器中使用最新版本,請訪問", + Close: "關閉", + // labels + "Download status": "當前下載狀態", + "Download Speed": "當前下載速度", + "Upload Speed": "當前上傳速度", + "Estimated time": "預計剩餘時間", + "Download Size": "下載總大小", + Downloaded: "已下載大小", + Progress: "當前下載進度", + "Download Path": "檔案下載路徑", + Uploaded: "已上傳大小", + "Download GID": "下載的 GID", + "Number of Pieces": "檔案塊數量", + "Piece Length": "每塊大小", -//alerts - 'The last connection attempt was unsuccessful. Trying another configuration': - '上次連線請求未成功,正在嘗試使用另一個配置', - 'Oh Snap!': '糟糕!', - 'Could not connect to the aria2 RPC server. Will retry in 10 secs. You might want to check the connection settings by going to Settings > Connection Settings': - '無法連線到 Aria2 RPC 伺服器,將在10秒後重試。您可能需要檢查連線設定,請前往 設定 > 連線設定', - 'Authentication failed while connecting to Aria2 RPC server. Will retry in 10 secs. You might want to confirm your authentication details by going to Settings > Connection Settings': - '連線到 Aria2 RPC 伺服器時認證失敗,將在10秒後重試。您可能需要確認您的身份驗證資訊,請前往 設定 > 連線設定', - 'Successfully connected to Aria2 through its remote RPC …': - '通過 RPC 連線到 Aria2 成功!', - 'Successfully connected to Aria2 through remote RPC, however the connection is still insecure. For complete security try adding an authorization secret token while starting Aria2 (through the flag --rpc-secret)': - '通過 RPC 連線到 Aria2 成功,但是連線並不安全。要想使用安全連線,嘗試在啟動 Aria2 時新增一個授權密碼令牌(通過 --rpc-secret 引數)', - 'Trying to connect to aria2 using the new connection configuration': - '正在嘗試使用新的連線配置來連線到 Aria2 ……', - 'Remove {{name}} and associated meta-data?': - '是否刪除 {{name}} 和關聯的元資料?' + //alerts + "The last connection attempt was unsuccessful. Trying another configuration": + "上次連線請求未成功,正在嘗試使用另一個配置", + "Oh Snap!": "糟糕!", + "Could not connect to the aria2 RPC server. Will retry in 10 secs. You might want to check the connection settings by going to Settings > Connection Settings": + "無法連線到 Aria2 RPC 伺服器,將在10秒後重試。您可能需要檢查連線設定,請前往 設定 > 連線設定", + "Authentication failed while connecting to Aria2 RPC server. Will retry in 10 secs. You might want to confirm your authentication details by going to Settings > Connection Settings": + "連線到 Aria2 RPC 伺服器時認證失敗,將在10秒後重試。您可能需要確認您的身份驗證資訊,請前往 設定 > 連線設定", + "Successfully connected to Aria2 through its remote RPC …": "通過 RPC 連線到 Aria2 成功!", + "Successfully connected to Aria2 through remote RPC, however the connection is still insecure. For complete security try adding an authorization secret token while starting Aria2 (through the flag --rpc-secret)": + "通過 RPC 連線到 Aria2 成功,但是連線並不安全。要想使用安全連線,嘗試在啟動 Aria2 時新增一個授權密碼令牌(通過 --rpc-secret 引數)", + "Trying to connect to aria2 using the new connection configuration": + "正在嘗試使用新的連線配置來連線到 Aria2 ……", + "Remove {{name}} and associated meta-data?": "是否刪除 {{name}} 和關聯的元資料?" }; diff --git a/node-server.js b/node-server.js index e9e5accc..17d4f1be 100644 --- a/node-server.js +++ b/node-server.js @@ -1,46 +1,54 @@ var http = require("http"), - url = require("url"), - path = require("path"), - fs = require("fs") - port = process.argv[2] || 8888; + url = require("url"), + path = require("path"), + fs = require("fs"); +port = process.argv[2] || 8888; -http.createServer(function(request, response) { - var uri = url.parse(request.url).pathname, - filename = path.join(process.cwd(), uri); +http + .createServer(function(request, response) { + var uri = url.parse(request.url).pathname, + filename = path.join(process.cwd(), uri); - var extname = path.extname(filename); - var contentType = 'text/html'; - switch (extname) { - case '.js': contentType = 'text/javascript'; break; - case '.css': contentType = 'text/css'; break; - case '.ico': contentType = 'image/x-icon'; break; - case '.svg': contentType = 'image/svg+xml'; break; - } - - - fs.exists(filename, function(exists) { - if(!exists) { - response.writeHead(404, {"Content-Type": "text/plain"}); - response.write("404 Not Found\n"); - response.end(); - return; - } + var extname = path.extname(filename); + var contentType = "text/html"; + switch (extname) { + case ".js": + contentType = "text/javascript"; + break; + case ".css": + contentType = "text/css"; + break; + case ".ico": + contentType = "image/x-icon"; + break; + case ".svg": + contentType = "image/svg+xml"; + break; + } - if (fs.statSync(filename).isDirectory()) filename += '/index.html'; + fs.exists(filename, function(exists) { + if (!exists) { + response.writeHead(404, { "Content-Type": "text/plain" }); + response.write("404 Not Found\n"); + response.end(); + return; + } - fs.readFile(filename, "binary", function(err, file) { - if(err) { - response.writeHead(500, {"Content-Type": "text/plain"}); - response.write(err + "\n"); - response.end(); - return; - } - response.writeHead(200, {'Content-Type': contentType}); - response.write(file, "binary"); - response.end(); - }); + if (fs.statSync(filename).isDirectory()) filename += "/index.html"; - }); -}).listen(parseInt(port, 10)); + fs.readFile(filename, "binary", function(err, file) { + if (err) { + response.writeHead(500, { "Content-Type": "text/plain" }); + response.write(err + "\n"); + response.end(); + return; + } + response.writeHead(200, { "Content-Type": contentType }); + response.write(file, "binary"); + response.end(); + }); + }); + }) + .listen(parseInt(port, 10)); -console.log("WebUI Aria2 Server is running on http://localhost:" + port ); +console.log("WebUI Aria2 Server is running on http://localhost:" + port); From 34590b381c4103071947bc846ca99a769c8569bc Mon Sep 17 00:00:00 2001 From: Pratik Borsadiya Date: Thu, 30 Aug 2018 23:28:55 +0530 Subject: [PATCH 04/16] Add webpack & Migrate codebase to be compatible with webpack --- build/app.js | 835 ++++ {css => build/css}/bootstrap.min.css | 0 {css => build/css}/download.css | 0 {css => build/css}/flag-icon.min.css | 0 {css => build/css}/font-awesome.min.css | 0 {css => build/css}/modals.css | 0 {css => build/css}/style.css | 0 {flags => build/flags}/1x1/ad.svg | 0 {flags => build/flags}/1x1/ae.svg | 0 {flags => build/flags}/1x1/af.svg | 0 {flags => build/flags}/1x1/ag.svg | 0 {flags => build/flags}/1x1/ai.svg | 0 {flags => build/flags}/1x1/al.svg | 0 {flags => build/flags}/1x1/am.svg | 0 {flags => build/flags}/1x1/ao.svg | 0 {flags => build/flags}/1x1/aq.svg | 0 {flags => build/flags}/1x1/ar.svg | 0 {flags => build/flags}/1x1/as.svg | 0 {flags => build/flags}/1x1/at.svg | 0 {flags => build/flags}/1x1/au.svg | 0 {flags => build/flags}/1x1/aw.svg | 0 {flags => build/flags}/1x1/ax.svg | 0 {flags => build/flags}/1x1/az.svg | 0 {flags => build/flags}/1x1/ba.svg | 0 {flags => build/flags}/1x1/bb.svg | 0 {flags => build/flags}/1x1/bd.svg | 0 {flags => build/flags}/1x1/be.svg | 0 {flags => build/flags}/1x1/bf.svg | 0 {flags => build/flags}/1x1/bg.svg | 0 {flags => build/flags}/1x1/bh.svg | 0 {flags => build/flags}/1x1/bi.svg | 0 {flags => build/flags}/1x1/bj.svg | 0 {flags => build/flags}/1x1/bl.svg | 0 {flags => build/flags}/1x1/bm.svg | 0 {flags => build/flags}/1x1/bn.svg | 0 {flags => build/flags}/1x1/bo.svg | 0 {flags => build/flags}/1x1/bq.svg | 0 {flags => build/flags}/1x1/br.svg | 0 {flags => build/flags}/1x1/bs.svg | 0 {flags => build/flags}/1x1/bt.svg | 0 {flags => build/flags}/1x1/bv.svg | 0 {flags => build/flags}/1x1/bw.svg | 0 {flags => build/flags}/1x1/by.svg | 0 {flags => build/flags}/1x1/bz.svg | 0 {flags => build/flags}/1x1/ca.svg | 0 {flags => build/flags}/1x1/cc.svg | 0 {flags => build/flags}/1x1/cd.svg | 0 {flags => build/flags}/1x1/cf.svg | 0 {flags => build/flags}/1x1/cg.svg | 0 {flags => build/flags}/1x1/ch.svg | 0 {flags => build/flags}/1x1/ci.svg | 0 {flags => build/flags}/1x1/ck.svg | 0 {flags => build/flags}/1x1/cl.svg | 0 {flags => build/flags}/1x1/cm.svg | 0 {flags => build/flags}/1x1/cn.svg | 0 {flags => build/flags}/1x1/co.svg | 0 {flags => build/flags}/1x1/cr.svg | 0 {flags => build/flags}/1x1/cu.svg | 0 {flags => build/flags}/1x1/cv.svg | 0 {flags => build/flags}/1x1/cw.svg | 0 {flags => build/flags}/1x1/cx.svg | 0 {flags => build/flags}/1x1/cy.svg | 0 {flags => build/flags}/1x1/cz.svg | 0 {flags => build/flags}/1x1/de.svg | 0 {flags => build/flags}/1x1/dj.svg | 0 {flags => build/flags}/1x1/dk.svg | 0 {flags => build/flags}/1x1/dm.svg | 0 {flags => build/flags}/1x1/do.svg | 0 {flags => build/flags}/1x1/dz.svg | 0 {flags => build/flags}/1x1/ec.svg | 0 {flags => build/flags}/1x1/ee.svg | 0 {flags => build/flags}/1x1/eg.svg | 0 {flags => build/flags}/1x1/eh.svg | 0 {flags => build/flags}/1x1/er.svg | 0 {flags => build/flags}/1x1/es.svg | 0 {flags => build/flags}/1x1/et.svg | 0 {flags => build/flags}/1x1/fi.svg | 0 {flags => build/flags}/1x1/fj.svg | 0 {flags => build/flags}/1x1/fk.svg | 0 {flags => build/flags}/1x1/fm.svg | 0 {flags => build/flags}/1x1/fo.svg | 0 {flags => build/flags}/1x1/fr.svg | 0 {flags => build/flags}/1x1/ga.svg | 0 {flags => build/flags}/1x1/gb.svg | 0 {flags => build/flags}/1x1/gd.svg | 0 {flags => build/flags}/1x1/ge.svg | 0 {flags => build/flags}/1x1/gf.svg | 0 {flags => build/flags}/1x1/gg.svg | 0 {flags => build/flags}/1x1/gh.svg | 0 {flags => build/flags}/1x1/gi.svg | 0 {flags => build/flags}/1x1/gl.svg | 0 {flags => build/flags}/1x1/gm.svg | 0 {flags => build/flags}/1x1/gn.svg | 0 {flags => build/flags}/1x1/gp.svg | 0 {flags => build/flags}/1x1/gq.svg | 0 {flags => build/flags}/1x1/gr.svg | 0 {flags => build/flags}/1x1/gs.svg | 0 {flags => build/flags}/1x1/gt.svg | 0 {flags => build/flags}/1x1/gu.svg | 0 {flags => build/flags}/1x1/gw.svg | 0 {flags => build/flags}/1x1/gy.svg | 0 {flags => build/flags}/1x1/hk.svg | 0 {flags => build/flags}/1x1/hm.svg | 0 {flags => build/flags}/1x1/hn.svg | 0 {flags => build/flags}/1x1/hr.svg | 0 {flags => build/flags}/1x1/ht.svg | 0 {flags => build/flags}/1x1/hu.svg | 0 {flags => build/flags}/1x1/id.svg | 0 {flags => build/flags}/1x1/ie.svg | 0 {flags => build/flags}/1x1/il.svg | 0 {flags => build/flags}/1x1/im.svg | 0 {flags => build/flags}/1x1/in.svg | 0 {flags => build/flags}/1x1/io.svg | 0 {flags => build/flags}/1x1/iq.svg | 0 {flags => build/flags}/1x1/ir.svg | 0 {flags => build/flags}/1x1/is.svg | 0 {flags => build/flags}/1x1/it.svg | 0 {flags => build/flags}/1x1/je.svg | 0 {flags => build/flags}/1x1/jm.svg | 0 {flags => build/flags}/1x1/jo.svg | 0 {flags => build/flags}/1x1/jp.svg | 0 {flags => build/flags}/1x1/ke.svg | 0 {flags => build/flags}/1x1/kg.svg | 0 {flags => build/flags}/1x1/kh.svg | 0 {flags => build/flags}/1x1/ki.svg | 0 {flags => build/flags}/1x1/km.svg | 0 {flags => build/flags}/1x1/kn.svg | 0 {flags => build/flags}/1x1/kp.svg | 0 {flags => build/flags}/1x1/kr.svg | 0 {flags => build/flags}/1x1/kw.svg | 0 {flags => build/flags}/1x1/ky.svg | 0 {flags => build/flags}/1x1/kz.svg | 0 {flags => build/flags}/1x1/la.svg | 0 {flags => build/flags}/1x1/lb.svg | 0 {flags => build/flags}/1x1/lc.svg | 0 {flags => build/flags}/1x1/li.svg | 0 {flags => build/flags}/1x1/lk.svg | 0 {flags => build/flags}/1x1/lr.svg | 0 {flags => build/flags}/1x1/ls.svg | 0 {flags => build/flags}/1x1/lt.svg | 0 {flags => build/flags}/1x1/lu.svg | 0 {flags => build/flags}/1x1/lv.svg | 0 {flags => build/flags}/1x1/ly.svg | 0 {flags => build/flags}/1x1/ma.svg | 0 {flags => build/flags}/1x1/mc.svg | 0 {flags => build/flags}/1x1/md.svg | 0 {flags => build/flags}/1x1/me.svg | 0 {flags => build/flags}/1x1/mf.svg | 0 {flags => build/flags}/1x1/mg.svg | 0 {flags => build/flags}/1x1/mh.svg | 0 {flags => build/flags}/1x1/mk.svg | 0 {flags => build/flags}/1x1/ml.svg | 0 {flags => build/flags}/1x1/mm.svg | 0 {flags => build/flags}/1x1/mn.svg | 0 {flags => build/flags}/1x1/mo.svg | 0 {flags => build/flags}/1x1/mp.svg | 0 {flags => build/flags}/1x1/mq.svg | 0 {flags => build/flags}/1x1/mr.svg | 0 {flags => build/flags}/1x1/ms.svg | 0 {flags => build/flags}/1x1/mt.svg | 0 {flags => build/flags}/1x1/mu.svg | 0 {flags => build/flags}/1x1/mv.svg | 0 {flags => build/flags}/1x1/mw.svg | 0 {flags => build/flags}/1x1/mx.svg | 0 {flags => build/flags}/1x1/my.svg | 0 {flags => build/flags}/1x1/mz.svg | 0 {flags => build/flags}/1x1/na.svg | 0 {flags => build/flags}/1x1/nc.svg | 0 {flags => build/flags}/1x1/ne.svg | 0 {flags => build/flags}/1x1/nf.svg | 0 {flags => build/flags}/1x1/ng.svg | 0 {flags => build/flags}/1x1/ni.svg | 0 {flags => build/flags}/1x1/nl.svg | 0 {flags => build/flags}/1x1/no.svg | 0 {flags => build/flags}/1x1/np.svg | 0 {flags => build/flags}/1x1/nr.svg | 0 {flags => build/flags}/1x1/nu.svg | 0 {flags => build/flags}/1x1/nz.svg | 0 {flags => build/flags}/1x1/om.svg | 0 {flags => build/flags}/1x1/pa.svg | 0 {flags => build/flags}/1x1/pe.svg | 0 {flags => build/flags}/1x1/pf.svg | 0 {flags => build/flags}/1x1/pg.svg | 0 {flags => build/flags}/1x1/ph.svg | 0 {flags => build/flags}/1x1/pk.svg | 0 {flags => build/flags}/1x1/pl.svg | 0 {flags => build/flags}/1x1/pm.svg | 0 {flags => build/flags}/1x1/pn.svg | 0 {flags => build/flags}/1x1/pr.svg | 0 {flags => build/flags}/1x1/ps.svg | 0 {flags => build/flags}/1x1/pt.svg | 0 {flags => build/flags}/1x1/pw.svg | 0 {flags => build/flags}/1x1/py.svg | 0 {flags => build/flags}/1x1/qa.svg | 0 {flags => build/flags}/1x1/re.svg | 0 {flags => build/flags}/1x1/ro.svg | 0 {flags => build/flags}/1x1/rs.svg | 0 {flags => build/flags}/1x1/ru.svg | 0 {flags => build/flags}/1x1/rw.svg | 0 {flags => build/flags}/1x1/sa.svg | 0 {flags => build/flags}/1x1/sb.svg | 0 {flags => build/flags}/1x1/sc.svg | 0 {flags => build/flags}/1x1/sd.svg | 0 {flags => build/flags}/1x1/se.svg | 0 {flags => build/flags}/1x1/sg.svg | 0 {flags => build/flags}/1x1/sh.svg | 0 {flags => build/flags}/1x1/si.svg | 0 {flags => build/flags}/1x1/sj.svg | 0 {flags => build/flags}/1x1/sk.svg | 0 {flags => build/flags}/1x1/sl.svg | 0 {flags => build/flags}/1x1/sm.svg | 0 {flags => build/flags}/1x1/sn.svg | 0 {flags => build/flags}/1x1/so.svg | 0 {flags => build/flags}/1x1/sr.svg | 0 {flags => build/flags}/1x1/ss.svg | 0 {flags => build/flags}/1x1/st.svg | 0 {flags => build/flags}/1x1/sv.svg | 0 {flags => build/flags}/1x1/sx.svg | 0 {flags => build/flags}/1x1/sy.svg | 0 {flags => build/flags}/1x1/sz.svg | 0 {flags => build/flags}/1x1/tc.svg | 0 {flags => build/flags}/1x1/td.svg | 0 {flags => build/flags}/1x1/tf.svg | 0 {flags => build/flags}/1x1/tg.svg | 0 {flags => build/flags}/1x1/th.svg | 0 {flags => build/flags}/1x1/tj.svg | 0 {flags => build/flags}/1x1/tk.svg | 0 {flags => build/flags}/1x1/tl.svg | 0 {flags => build/flags}/1x1/tm.svg | 0 {flags => build/flags}/1x1/tn.svg | 0 {flags => build/flags}/1x1/to.svg | 0 {flags => build/flags}/1x1/tr.svg | 0 {flags => build/flags}/1x1/tt.svg | 0 {flags => build/flags}/1x1/tv.svg | 0 {flags => build/flags}/1x1/tw.svg | 0 {flags => build/flags}/1x1/tz.svg | 0 {flags => build/flags}/1x1/ua.svg | 0 {flags => build/flags}/1x1/ug.svg | 0 {flags => build/flags}/1x1/um.svg | 0 {flags => build/flags}/1x1/us.svg | 0 {flags => build/flags}/1x1/uy.svg | 0 {flags => build/flags}/1x1/uz.svg | 0 {flags => build/flags}/1x1/va.svg | 0 {flags => build/flags}/1x1/vc.svg | 0 {flags => build/flags}/1x1/ve.svg | 0 {flags => build/flags}/1x1/vg.svg | 0 {flags => build/flags}/1x1/vi.svg | 0 {flags => build/flags}/1x1/vn.svg | 0 {flags => build/flags}/1x1/vu.svg | 0 {flags => build/flags}/1x1/wf.svg | 0 {flags => build/flags}/1x1/ws.svg | 0 {flags => build/flags}/1x1/ye.svg | 0 {flags => build/flags}/1x1/yt.svg | 0 {flags => build/flags}/1x1/za.svg | 0 {flags => build/flags}/1x1/zm.svg | 0 {flags => build/flags}/1x1/zw.svg | 0 {flags => build/flags}/4x3/ad.svg | 0 {flags => build/flags}/4x3/ae.svg | 0 {flags => build/flags}/4x3/af.svg | 0 {flags => build/flags}/4x3/ag.svg | 0 {flags => build/flags}/4x3/ai.svg | 0 {flags => build/flags}/4x3/al.svg | 0 {flags => build/flags}/4x3/am.svg | 0 {flags => build/flags}/4x3/ao.svg | 0 {flags => build/flags}/4x3/aq.svg | 0 {flags => build/flags}/4x3/ar.svg | 0 {flags => build/flags}/4x3/as.svg | 0 {flags => build/flags}/4x3/at.svg | 0 {flags => build/flags}/4x3/au.svg | 0 {flags => build/flags}/4x3/aw.svg | 0 {flags => build/flags}/4x3/ax.svg | 0 {flags => build/flags}/4x3/az.svg | 0 {flags => build/flags}/4x3/ba.svg | 0 {flags => build/flags}/4x3/bb.svg | 0 {flags => build/flags}/4x3/bd.svg | 0 {flags => build/flags}/4x3/be.svg | 0 {flags => build/flags}/4x3/bf.svg | 0 {flags => build/flags}/4x3/bg.svg | 0 {flags => build/flags}/4x3/bh.svg | 0 {flags => build/flags}/4x3/bi.svg | 0 {flags => build/flags}/4x3/bj.svg | 0 {flags => build/flags}/4x3/bl.svg | 0 {flags => build/flags}/4x3/bm.svg | 0 {flags => build/flags}/4x3/bn.svg | 0 {flags => build/flags}/4x3/bo.svg | 0 {flags => build/flags}/4x3/bq.svg | 0 {flags => build/flags}/4x3/br.svg | 0 {flags => build/flags}/4x3/bs.svg | 0 {flags => build/flags}/4x3/bt.svg | 0 {flags => build/flags}/4x3/bv.svg | 0 {flags => build/flags}/4x3/bw.svg | 0 {flags => build/flags}/4x3/by.svg | 0 {flags => build/flags}/4x3/bz.svg | 0 {flags => build/flags}/4x3/ca.svg | 0 {flags => build/flags}/4x3/cc.svg | 0 {flags => build/flags}/4x3/cd.svg | 0 {flags => build/flags}/4x3/cf.svg | 0 {flags => build/flags}/4x3/cg.svg | 0 {flags => build/flags}/4x3/ch.svg | 0 {flags => build/flags}/4x3/ci.svg | 0 {flags => build/flags}/4x3/ck.svg | 0 {flags => build/flags}/4x3/cl.svg | 0 {flags => build/flags}/4x3/cm.svg | 0 {flags => build/flags}/4x3/cn.svg | 0 {flags => build/flags}/4x3/co.svg | 0 {flags => build/flags}/4x3/cr.svg | 0 {flags => build/flags}/4x3/cu.svg | 0 {flags => build/flags}/4x3/cv.svg | 0 {flags => build/flags}/4x3/cw.svg | 0 {flags => build/flags}/4x3/cx.svg | 0 {flags => build/flags}/4x3/cy.svg | 0 {flags => build/flags}/4x3/cz.svg | 0 {flags => build/flags}/4x3/de.svg | 0 {flags => build/flags}/4x3/dj.svg | 0 {flags => build/flags}/4x3/dk.svg | 0 {flags => build/flags}/4x3/dm.svg | 0 {flags => build/flags}/4x3/do.svg | 0 {flags => build/flags}/4x3/dz.svg | 0 {flags => build/flags}/4x3/ec.svg | 0 {flags => build/flags}/4x3/ee.svg | 0 {flags => build/flags}/4x3/eg.svg | 0 {flags => build/flags}/4x3/eh.svg | 0 {flags => build/flags}/4x3/er.svg | 0 {flags => build/flags}/4x3/es.svg | 0 {flags => build/flags}/4x3/et.svg | 0 {flags => build/flags}/4x3/fi.svg | 0 {flags => build/flags}/4x3/fj.svg | 0 {flags => build/flags}/4x3/fk.svg | 0 {flags => build/flags}/4x3/fm.svg | 0 {flags => build/flags}/4x3/fo.svg | 0 {flags => build/flags}/4x3/fr.svg | 0 {flags => build/flags}/4x3/ga.svg | 0 {flags => build/flags}/4x3/gb.svg | 0 {flags => build/flags}/4x3/gd.svg | 0 {flags => build/flags}/4x3/ge.svg | 0 {flags => build/flags}/4x3/gf.svg | 0 {flags => build/flags}/4x3/gg.svg | 0 {flags => build/flags}/4x3/gh.svg | 0 {flags => build/flags}/4x3/gi.svg | 0 {flags => build/flags}/4x3/gl.svg | 0 {flags => build/flags}/4x3/gm.svg | 0 {flags => build/flags}/4x3/gn.svg | 0 {flags => build/flags}/4x3/gp.svg | 0 {flags => build/flags}/4x3/gq.svg | 0 {flags => build/flags}/4x3/gr.svg | 0 {flags => build/flags}/4x3/gs.svg | 0 {flags => build/flags}/4x3/gt.svg | 0 {flags => build/flags}/4x3/gu.svg | 0 {flags => build/flags}/4x3/gw.svg | 0 {flags => build/flags}/4x3/gy.svg | 0 {flags => build/flags}/4x3/hk.svg | 0 {flags => build/flags}/4x3/hm.svg | 0 {flags => build/flags}/4x3/hn.svg | 0 {flags => build/flags}/4x3/hr.svg | 0 {flags => build/flags}/4x3/ht.svg | 0 {flags => build/flags}/4x3/hu.svg | 0 {flags => build/flags}/4x3/id.svg | 0 {flags => build/flags}/4x3/ie.svg | 0 {flags => build/flags}/4x3/il.svg | 0 {flags => build/flags}/4x3/im.svg | 0 {flags => build/flags}/4x3/in.svg | 0 {flags => build/flags}/4x3/io.svg | 0 {flags => build/flags}/4x3/iq.svg | 0 {flags => build/flags}/4x3/ir.svg | 0 {flags => build/flags}/4x3/is.svg | 0 {flags => build/flags}/4x3/it.svg | 0 {flags => build/flags}/4x3/je.svg | 0 {flags => build/flags}/4x3/jm.svg | 0 {flags => build/flags}/4x3/jo.svg | 0 {flags => build/flags}/4x3/jp.svg | 0 {flags => build/flags}/4x3/ke.svg | 0 {flags => build/flags}/4x3/kg.svg | 0 {flags => build/flags}/4x3/kh.svg | 0 {flags => build/flags}/4x3/ki.svg | 0 {flags => build/flags}/4x3/km.svg | 0 {flags => build/flags}/4x3/kn.svg | 0 {flags => build/flags}/4x3/kp.svg | 0 {flags => build/flags}/4x3/kr.svg | 0 {flags => build/flags}/4x3/kw.svg | 0 {flags => build/flags}/4x3/ky.svg | 0 {flags => build/flags}/4x3/kz.svg | 0 {flags => build/flags}/4x3/la.svg | 0 {flags => build/flags}/4x3/lb.svg | 0 {flags => build/flags}/4x3/lc.svg | 0 {flags => build/flags}/4x3/li.svg | 0 {flags => build/flags}/4x3/lk.svg | 0 {flags => build/flags}/4x3/lr.svg | 0 {flags => build/flags}/4x3/ls.svg | 0 {flags => build/flags}/4x3/lt.svg | 0 {flags => build/flags}/4x3/lu.svg | 0 {flags => build/flags}/4x3/lv.svg | 0 {flags => build/flags}/4x3/ly.svg | 0 {flags => build/flags}/4x3/ma.svg | 0 {flags => build/flags}/4x3/mc.svg | 0 {flags => build/flags}/4x3/md.svg | 0 {flags => build/flags}/4x3/me.svg | 0 {flags => build/flags}/4x3/mf.svg | 0 {flags => build/flags}/4x3/mg.svg | 0 {flags => build/flags}/4x3/mh.svg | 0 {flags => build/flags}/4x3/mk.svg | 0 {flags => build/flags}/4x3/ml.svg | 0 {flags => build/flags}/4x3/mm.svg | 0 {flags => build/flags}/4x3/mn.svg | 0 {flags => build/flags}/4x3/mo.svg | 0 {flags => build/flags}/4x3/mp.svg | 0 {flags => build/flags}/4x3/mq.svg | 0 {flags => build/flags}/4x3/mr.svg | 0 {flags => build/flags}/4x3/ms.svg | 0 {flags => build/flags}/4x3/mt.svg | 0 {flags => build/flags}/4x3/mu.svg | 0 {flags => build/flags}/4x3/mv.svg | 0 {flags => build/flags}/4x3/mw.svg | 0 {flags => build/flags}/4x3/mx.svg | 0 {flags => build/flags}/4x3/my.svg | 0 {flags => build/flags}/4x3/mz.svg | 0 {flags => build/flags}/4x3/na.svg | 0 {flags => build/flags}/4x3/nc.svg | 0 {flags => build/flags}/4x3/ne.svg | 0 {flags => build/flags}/4x3/nf.svg | 0 {flags => build/flags}/4x3/ng.svg | 0 {flags => build/flags}/4x3/ni.svg | 0 {flags => build/flags}/4x3/nl.svg | 0 {flags => build/flags}/4x3/no.svg | 0 {flags => build/flags}/4x3/np.svg | 0 {flags => build/flags}/4x3/nr.svg | 0 {flags => build/flags}/4x3/nu.svg | 0 {flags => build/flags}/4x3/nz.svg | 0 {flags => build/flags}/4x3/om.svg | 0 {flags => build/flags}/4x3/pa.svg | 0 {flags => build/flags}/4x3/pe.svg | 0 {flags => build/flags}/4x3/pf.svg | 0 {flags => build/flags}/4x3/pg.svg | 0 {flags => build/flags}/4x3/ph.svg | 0 {flags => build/flags}/4x3/pk.svg | 0 {flags => build/flags}/4x3/pl.svg | 0 {flags => build/flags}/4x3/pm.svg | 0 {flags => build/flags}/4x3/pn.svg | 0 {flags => build/flags}/4x3/pr.svg | 0 {flags => build/flags}/4x3/ps.svg | 0 {flags => build/flags}/4x3/pt.svg | 0 {flags => build/flags}/4x3/pw.svg | 0 {flags => build/flags}/4x3/py.svg | 0 {flags => build/flags}/4x3/qa.svg | 0 {flags => build/flags}/4x3/re.svg | 0 {flags => build/flags}/4x3/ro.svg | 0 {flags => build/flags}/4x3/rs.svg | 0 {flags => build/flags}/4x3/ru.svg | 0 {flags => build/flags}/4x3/rw.svg | 0 {flags => build/flags}/4x3/sa.svg | 0 {flags => build/flags}/4x3/sb.svg | 0 {flags => build/flags}/4x3/sc.svg | 0 {flags => build/flags}/4x3/sd.svg | 0 {flags => build/flags}/4x3/se.svg | 0 {flags => build/flags}/4x3/sg.svg | 0 {flags => build/flags}/4x3/sh.svg | 0 {flags => build/flags}/4x3/si.svg | 0 {flags => build/flags}/4x3/sj.svg | 0 {flags => build/flags}/4x3/sk.svg | 0 {flags => build/flags}/4x3/sl.svg | 0 {flags => build/flags}/4x3/sm.svg | 0 {flags => build/flags}/4x3/sn.svg | 0 {flags => build/flags}/4x3/so.svg | 0 {flags => build/flags}/4x3/sr.svg | 0 {flags => build/flags}/4x3/ss.svg | 0 {flags => build/flags}/4x3/st.svg | 0 {flags => build/flags}/4x3/sv.svg | 0 {flags => build/flags}/4x3/sx.svg | 0 {flags => build/flags}/4x3/sy.svg | 0 {flags => build/flags}/4x3/sz.svg | 0 {flags => build/flags}/4x3/tc.svg | 0 {flags => build/flags}/4x3/td.svg | 0 {flags => build/flags}/4x3/tf.svg | 0 {flags => build/flags}/4x3/tg.svg | 0 {flags => build/flags}/4x3/th.svg | 0 {flags => build/flags}/4x3/tj.svg | 0 {flags => build/flags}/4x3/tk.svg | 0 {flags => build/flags}/4x3/tl.svg | 0 {flags => build/flags}/4x3/tm.svg | 0 {flags => build/flags}/4x3/tn.svg | 0 {flags => build/flags}/4x3/to.svg | 0 {flags => build/flags}/4x3/tr.svg | 0 {flags => build/flags}/4x3/tt.svg | 0 {flags => build/flags}/4x3/tv.svg | 0 {flags => build/flags}/4x3/tw.svg | 0 {flags => build/flags}/4x3/tz.svg | 0 {flags => build/flags}/4x3/ua.svg | 0 {flags => build/flags}/4x3/ug.svg | 0 {flags => build/flags}/4x3/um.svg | 0 {flags => build/flags}/4x3/us.svg | 0 {flags => build/flags}/4x3/uy.svg | 0 {flags => build/flags}/4x3/uz.svg | 0 {flags => build/flags}/4x3/va.svg | 0 {flags => build/flags}/4x3/vc.svg | 0 {flags => build/flags}/4x3/ve.svg | 0 {flags => build/flags}/4x3/vg.svg | 0 {flags => build/flags}/4x3/vi.svg | 0 {flags => build/flags}/4x3/vn.svg | 0 {flags => build/flags}/4x3/vu.svg | 0 {flags => build/flags}/4x3/wf.svg | 0 {flags => build/flags}/4x3/ws.svg | 0 {flags => build/flags}/4x3/ye.svg | 0 {flags => build/flags}/4x3/yt.svg | 0 {flags => build/flags}/4x3/za.svg | 0 {flags => build/flags}/4x3/zm.svg | 0 {flags => build/flags}/4x3/zw.svg | 0 {fonts => build/fonts}/FontAwesome.otf | Bin .../fonts}/fontawesome-webfont.eot | Bin .../fonts}/fontawesome-webfont.svg | 0 .../fonts}/fontawesome-webfont.ttf | Bin .../fonts}/fontawesome-webfont.woff | Bin .../fonts}/fontawesome-webfont.woff2 | Bin index.html => build/index.html | 73 +- js/ctrls/alert.js | 33 - js/directives/chunkbar.js | 50 - js/directives/fileselect.js | 153 - js/directives/fselect.js | 18 - js/filters/url.js | 3 - js/init.js | 82 - js/services/deps.js | 5 - js/services/errors.js | 66 - js/services/utils.js | 187 - node-server.js | 2 +- package-lock.json | 4204 ++++++++++++++++- package.json | 14 +- src/js/app.js | 148 + src/js/ctrls/alert.js | 37 + {js => src/js}/ctrls/main.js | 7 +- {js => src/js}/ctrls/modal.js | 6 +- {js => src/js}/ctrls/nav.js | 6 +- {js => src/js}/ctrls/props.js | 6 +- src/js/directives/chunkbar.js | 54 + {js => src/js}/directives/dgraph.js | 8 +- src/js/directives/fileselect.js | 156 + src/js/directives/fselect.js | 22 + {js => src/js}/directives/textarea.js | 6 +- {js => src/js}/filters/bytes.js | 6 +- src/js/filters/url.js | 7 + {js => src/js}/libs/angular-translate.min.js | 0 {js => src/js}/libs/angular.min.js | 0 .../js}/libs/angularui-bootstrap-tpls.min.js | 0 {js => src/js}/libs/bootstrap-filestyle.js | 0 {js => src/js}/libs/jquery-2.2.4.min.js | 0 {js => src/js}/libs/jquery.flot.min.js | 0 {js => src/js}/libs/jquery.flot.resize.min.js | 0 {js => src/js}/libs/jquery.flot.time.min.js | 0 {js => src/js}/libs/lodash-4.17.3.min.js | 0 {js => src/js}/services/alerts.js | 6 +- {js => src/js}/services/base64.js | 6 +- .../js/services/configuration.js | 6 +- src/js/services/deps.js | 9 + src/js/services/errors.js | 70 + {js => src/js}/services/modals.js | 6 +- {js => src/js}/services/rpc/helpers.js | 6 +- {js => src/js}/services/rpc/jsoncall.js | 6 +- {js => src/js}/services/rpc/rpc.js | 6 +- {js => src/js}/services/rpc/sockcall.js | 6 +- {js => src/js}/services/rpc/syscall.js | 6 +- {js => src/js}/services/settings/filters.js | 6 +- {js => src/js}/services/settings/settings.js | 6 +- src/js/services/utils.js | 191 + {js => src/js}/translate/cs_CZ.js | 0 {js => src/js}/translate/de_DE.js | 0 {js => src/js}/translate/en_US.js | 0 {js => src/js}/translate/es_ES.js | 0 {js => src/js}/translate/fa_IR.js | 0 {js => src/js}/translate/fr_FR.js | 0 {js => src/js}/translate/id_ID.js | 0 {js => src/js}/translate/it_IT.js | 0 {js => src/js}/translate/nl_NL.js | 0 {js => src/js}/translate/pl_PL.js | 0 {js => src/js}/translate/pt_BR.js | 0 {js => src/js}/translate/ru_RU.js | 0 {js => src/js}/translate/template.js | 0 {js => src/js}/translate/th_TH.js | 0 {js => src/js}/translate/tr_TR.js | 0 {js => src/js}/translate/zh_CN.js | 0 {js => src/js}/translate/zh_TW.js | 0 webpack.config.js | 28 + 578 files changed, 5711 insertions(+), 847 deletions(-) create mode 100644 build/app.js rename {css => build/css}/bootstrap.min.css (100%) rename {css => build/css}/download.css (100%) rename {css => build/css}/flag-icon.min.css (100%) rename {css => build/css}/font-awesome.min.css (100%) rename {css => build/css}/modals.css (100%) rename {css => build/css}/style.css (100%) rename {flags => build/flags}/1x1/ad.svg (100%) rename {flags => build/flags}/1x1/ae.svg (100%) rename {flags => build/flags}/1x1/af.svg (100%) rename {flags => build/flags}/1x1/ag.svg (100%) rename {flags => build/flags}/1x1/ai.svg (100%) rename {flags => build/flags}/1x1/al.svg (100%) rename {flags => build/flags}/1x1/am.svg (100%) rename {flags => build/flags}/1x1/ao.svg (100%) rename {flags => build/flags}/1x1/aq.svg (100%) rename {flags => build/flags}/1x1/ar.svg (100%) rename {flags => build/flags}/1x1/as.svg (100%) rename {flags => build/flags}/1x1/at.svg (100%) rename {flags => build/flags}/1x1/au.svg (100%) rename {flags => build/flags}/1x1/aw.svg (100%) rename {flags => build/flags}/1x1/ax.svg (100%) rename {flags => build/flags}/1x1/az.svg (100%) rename {flags => build/flags}/1x1/ba.svg (100%) rename {flags => build/flags}/1x1/bb.svg (100%) rename {flags => build/flags}/1x1/bd.svg (100%) rename {flags => build/flags}/1x1/be.svg (100%) rename {flags => build/flags}/1x1/bf.svg (100%) rename {flags => build/flags}/1x1/bg.svg (100%) rename {flags => build/flags}/1x1/bh.svg (100%) rename {flags => build/flags}/1x1/bi.svg (100%) rename {flags => build/flags}/1x1/bj.svg (100%) rename {flags => build/flags}/1x1/bl.svg (100%) rename {flags => build/flags}/1x1/bm.svg (100%) rename {flags => build/flags}/1x1/bn.svg (100%) rename {flags => build/flags}/1x1/bo.svg (100%) rename {flags => build/flags}/1x1/bq.svg (100%) rename {flags => build/flags}/1x1/br.svg (100%) rename {flags => build/flags}/1x1/bs.svg (100%) rename {flags => build/flags}/1x1/bt.svg (100%) rename {flags => build/flags}/1x1/bv.svg (100%) rename {flags => build/flags}/1x1/bw.svg (100%) rename {flags => build/flags}/1x1/by.svg (100%) rename {flags => build/flags}/1x1/bz.svg (100%) rename {flags => build/flags}/1x1/ca.svg (100%) rename {flags => build/flags}/1x1/cc.svg (100%) rename {flags => build/flags}/1x1/cd.svg (100%) rename {flags => build/flags}/1x1/cf.svg (100%) rename {flags => build/flags}/1x1/cg.svg (100%) rename {flags => build/flags}/1x1/ch.svg (100%) rename {flags => build/flags}/1x1/ci.svg (100%) rename {flags => build/flags}/1x1/ck.svg (100%) rename {flags => build/flags}/1x1/cl.svg (100%) rename {flags => build/flags}/1x1/cm.svg (100%) rename {flags => build/flags}/1x1/cn.svg (100%) rename {flags => build/flags}/1x1/co.svg (100%) rename {flags => build/flags}/1x1/cr.svg (100%) rename {flags => build/flags}/1x1/cu.svg (100%) rename {flags => build/flags}/1x1/cv.svg (100%) rename {flags => build/flags}/1x1/cw.svg (100%) rename {flags => build/flags}/1x1/cx.svg (100%) rename {flags => build/flags}/1x1/cy.svg (100%) rename {flags => build/flags}/1x1/cz.svg (100%) rename {flags => build/flags}/1x1/de.svg (100%) rename {flags => build/flags}/1x1/dj.svg (100%) rename {flags => build/flags}/1x1/dk.svg (100%) rename {flags => build/flags}/1x1/dm.svg (100%) rename {flags => build/flags}/1x1/do.svg (100%) rename {flags => build/flags}/1x1/dz.svg (100%) rename {flags => build/flags}/1x1/ec.svg (100%) rename {flags => build/flags}/1x1/ee.svg (100%) rename {flags => build/flags}/1x1/eg.svg (100%) rename {flags => build/flags}/1x1/eh.svg (100%) rename {flags => build/flags}/1x1/er.svg (100%) rename {flags => build/flags}/1x1/es.svg (100%) rename {flags => build/flags}/1x1/et.svg (100%) rename {flags => build/flags}/1x1/fi.svg (100%) rename {flags => build/flags}/1x1/fj.svg (100%) rename {flags => build/flags}/1x1/fk.svg (100%) rename {flags => build/flags}/1x1/fm.svg (100%) rename {flags => build/flags}/1x1/fo.svg (100%) rename {flags => build/flags}/1x1/fr.svg (100%) rename {flags => build/flags}/1x1/ga.svg (100%) rename {flags => build/flags}/1x1/gb.svg (100%) rename {flags => build/flags}/1x1/gd.svg (100%) rename {flags => build/flags}/1x1/ge.svg (100%) rename {flags => build/flags}/1x1/gf.svg (100%) rename {flags => build/flags}/1x1/gg.svg (100%) rename {flags => build/flags}/1x1/gh.svg (100%) rename {flags => build/flags}/1x1/gi.svg (100%) rename {flags => build/flags}/1x1/gl.svg (100%) rename {flags => build/flags}/1x1/gm.svg (100%) rename {flags => build/flags}/1x1/gn.svg (100%) rename {flags => build/flags}/1x1/gp.svg (100%) rename {flags => build/flags}/1x1/gq.svg (100%) rename {flags => build/flags}/1x1/gr.svg (100%) rename {flags => build/flags}/1x1/gs.svg (100%) rename {flags => build/flags}/1x1/gt.svg (100%) rename {flags => build/flags}/1x1/gu.svg (100%) rename {flags => build/flags}/1x1/gw.svg (100%) rename {flags => build/flags}/1x1/gy.svg (100%) rename {flags => build/flags}/1x1/hk.svg (100%) rename {flags => build/flags}/1x1/hm.svg (100%) rename {flags => build/flags}/1x1/hn.svg (100%) rename {flags => build/flags}/1x1/hr.svg (100%) rename {flags => build/flags}/1x1/ht.svg (100%) rename {flags => build/flags}/1x1/hu.svg (100%) rename {flags => build/flags}/1x1/id.svg (100%) rename {flags => build/flags}/1x1/ie.svg (100%) rename {flags => build/flags}/1x1/il.svg (100%) rename {flags => build/flags}/1x1/im.svg (100%) rename {flags => build/flags}/1x1/in.svg (100%) rename {flags => build/flags}/1x1/io.svg (100%) rename {flags => build/flags}/1x1/iq.svg (100%) rename {flags => build/flags}/1x1/ir.svg (100%) rename {flags => build/flags}/1x1/is.svg (100%) rename {flags => build/flags}/1x1/it.svg (100%) rename {flags => build/flags}/1x1/je.svg (100%) rename {flags => build/flags}/1x1/jm.svg (100%) rename {flags => build/flags}/1x1/jo.svg (100%) rename {flags => build/flags}/1x1/jp.svg (100%) rename {flags => build/flags}/1x1/ke.svg (100%) rename {flags => build/flags}/1x1/kg.svg (100%) rename {flags => build/flags}/1x1/kh.svg (100%) rename {flags => build/flags}/1x1/ki.svg (100%) rename {flags => build/flags}/1x1/km.svg (100%) rename {flags => build/flags}/1x1/kn.svg (100%) rename {flags => build/flags}/1x1/kp.svg (100%) rename {flags => build/flags}/1x1/kr.svg (100%) rename {flags => build/flags}/1x1/kw.svg (100%) rename {flags => build/flags}/1x1/ky.svg (100%) rename {flags => build/flags}/1x1/kz.svg (100%) rename {flags => build/flags}/1x1/la.svg (100%) rename {flags => build/flags}/1x1/lb.svg (100%) rename {flags => build/flags}/1x1/lc.svg (100%) rename {flags => build/flags}/1x1/li.svg (100%) rename {flags => build/flags}/1x1/lk.svg (100%) rename {flags => build/flags}/1x1/lr.svg (100%) rename {flags => build/flags}/1x1/ls.svg (100%) rename {flags => build/flags}/1x1/lt.svg (100%) rename {flags => build/flags}/1x1/lu.svg (100%) rename {flags => build/flags}/1x1/lv.svg (100%) rename {flags => build/flags}/1x1/ly.svg (100%) rename {flags => build/flags}/1x1/ma.svg (100%) rename {flags => build/flags}/1x1/mc.svg (100%) rename {flags => build/flags}/1x1/md.svg (100%) rename {flags => build/flags}/1x1/me.svg (100%) rename {flags => build/flags}/1x1/mf.svg (100%) rename {flags => build/flags}/1x1/mg.svg (100%) rename {flags => build/flags}/1x1/mh.svg (100%) rename {flags => build/flags}/1x1/mk.svg (100%) rename {flags => build/flags}/1x1/ml.svg (100%) rename {flags => build/flags}/1x1/mm.svg (100%) rename {flags => build/flags}/1x1/mn.svg (100%) rename {flags => build/flags}/1x1/mo.svg (100%) rename {flags => build/flags}/1x1/mp.svg (100%) rename {flags => build/flags}/1x1/mq.svg (100%) rename {flags => build/flags}/1x1/mr.svg (100%) rename {flags => build/flags}/1x1/ms.svg (100%) rename {flags => build/flags}/1x1/mt.svg (100%) rename {flags => build/flags}/1x1/mu.svg (100%) rename {flags => build/flags}/1x1/mv.svg (100%) rename {flags => build/flags}/1x1/mw.svg (100%) rename {flags => build/flags}/1x1/mx.svg (100%) rename {flags => build/flags}/1x1/my.svg (100%) rename {flags => build/flags}/1x1/mz.svg (100%) rename {flags => build/flags}/1x1/na.svg (100%) rename {flags => build/flags}/1x1/nc.svg (100%) rename {flags => build/flags}/1x1/ne.svg (100%) rename {flags => build/flags}/1x1/nf.svg (100%) rename {flags => build/flags}/1x1/ng.svg (100%) rename {flags => build/flags}/1x1/ni.svg (100%) rename {flags => build/flags}/1x1/nl.svg (100%) rename {flags => build/flags}/1x1/no.svg (100%) rename {flags => build/flags}/1x1/np.svg (100%) rename {flags => build/flags}/1x1/nr.svg (100%) rename {flags => build/flags}/1x1/nu.svg (100%) rename {flags => build/flags}/1x1/nz.svg (100%) rename {flags => build/flags}/1x1/om.svg (100%) rename {flags => build/flags}/1x1/pa.svg (100%) rename {flags => build/flags}/1x1/pe.svg (100%) rename {flags => build/flags}/1x1/pf.svg (100%) rename {flags => build/flags}/1x1/pg.svg (100%) rename {flags => build/flags}/1x1/ph.svg (100%) rename {flags => build/flags}/1x1/pk.svg (100%) rename {flags => build/flags}/1x1/pl.svg (100%) rename {flags => build/flags}/1x1/pm.svg (100%) rename {flags => build/flags}/1x1/pn.svg (100%) rename {flags => build/flags}/1x1/pr.svg (100%) rename {flags => build/flags}/1x1/ps.svg (100%) rename {flags => build/flags}/1x1/pt.svg (100%) rename {flags => build/flags}/1x1/pw.svg (100%) rename {flags => build/flags}/1x1/py.svg (100%) rename {flags => build/flags}/1x1/qa.svg (100%) rename {flags => build/flags}/1x1/re.svg (100%) rename {flags => build/flags}/1x1/ro.svg (100%) rename {flags => build/flags}/1x1/rs.svg (100%) rename {flags => build/flags}/1x1/ru.svg (100%) rename {flags => build/flags}/1x1/rw.svg (100%) rename {flags => build/flags}/1x1/sa.svg (100%) rename {flags => build/flags}/1x1/sb.svg (100%) rename {flags => build/flags}/1x1/sc.svg (100%) rename {flags => build/flags}/1x1/sd.svg (100%) rename {flags => build/flags}/1x1/se.svg (100%) rename {flags => build/flags}/1x1/sg.svg (100%) rename {flags => build/flags}/1x1/sh.svg (100%) rename {flags => build/flags}/1x1/si.svg (100%) rename {flags => build/flags}/1x1/sj.svg (100%) rename {flags => build/flags}/1x1/sk.svg (100%) rename {flags => build/flags}/1x1/sl.svg (100%) rename {flags => build/flags}/1x1/sm.svg (100%) rename {flags => build/flags}/1x1/sn.svg (100%) rename {flags => build/flags}/1x1/so.svg (100%) rename {flags => build/flags}/1x1/sr.svg (100%) rename {flags => build/flags}/1x1/ss.svg (100%) rename {flags => build/flags}/1x1/st.svg (100%) rename {flags => build/flags}/1x1/sv.svg (100%) rename {flags => build/flags}/1x1/sx.svg (100%) rename {flags => build/flags}/1x1/sy.svg (100%) rename {flags => build/flags}/1x1/sz.svg (100%) rename {flags => build/flags}/1x1/tc.svg (100%) rename {flags => build/flags}/1x1/td.svg (100%) rename {flags => build/flags}/1x1/tf.svg (100%) rename {flags => build/flags}/1x1/tg.svg (100%) rename {flags => build/flags}/1x1/th.svg (100%) rename {flags => build/flags}/1x1/tj.svg (100%) rename {flags => build/flags}/1x1/tk.svg (100%) rename {flags => build/flags}/1x1/tl.svg (100%) rename {flags => build/flags}/1x1/tm.svg (100%) rename {flags => build/flags}/1x1/tn.svg (100%) rename {flags => build/flags}/1x1/to.svg (100%) rename {flags => build/flags}/1x1/tr.svg (100%) rename {flags => build/flags}/1x1/tt.svg (100%) rename {flags => build/flags}/1x1/tv.svg (100%) rename {flags => build/flags}/1x1/tw.svg (100%) rename {flags => build/flags}/1x1/tz.svg (100%) rename {flags => build/flags}/1x1/ua.svg (100%) rename {flags => build/flags}/1x1/ug.svg (100%) rename {flags => build/flags}/1x1/um.svg (100%) rename {flags => build/flags}/1x1/us.svg (100%) rename {flags => build/flags}/1x1/uy.svg (100%) rename {flags => build/flags}/1x1/uz.svg (100%) rename {flags => build/flags}/1x1/va.svg (100%) rename {flags => build/flags}/1x1/vc.svg (100%) rename {flags => build/flags}/1x1/ve.svg (100%) rename {flags => build/flags}/1x1/vg.svg (100%) rename {flags => build/flags}/1x1/vi.svg (100%) rename {flags => build/flags}/1x1/vn.svg (100%) rename {flags => build/flags}/1x1/vu.svg (100%) rename {flags => build/flags}/1x1/wf.svg (100%) rename {flags => build/flags}/1x1/ws.svg (100%) rename {flags => build/flags}/1x1/ye.svg (100%) rename {flags => build/flags}/1x1/yt.svg (100%) rename {flags => build/flags}/1x1/za.svg (100%) rename {flags => build/flags}/1x1/zm.svg (100%) rename {flags => build/flags}/1x1/zw.svg (100%) rename {flags => build/flags}/4x3/ad.svg (100%) rename {flags => build/flags}/4x3/ae.svg (100%) rename {flags => build/flags}/4x3/af.svg (100%) rename {flags => build/flags}/4x3/ag.svg (100%) rename {flags => build/flags}/4x3/ai.svg (100%) rename {flags => build/flags}/4x3/al.svg (100%) rename {flags => build/flags}/4x3/am.svg (100%) rename {flags => build/flags}/4x3/ao.svg (100%) rename {flags => build/flags}/4x3/aq.svg (100%) rename {flags => build/flags}/4x3/ar.svg (100%) rename {flags => build/flags}/4x3/as.svg (100%) rename {flags => build/flags}/4x3/at.svg (100%) rename {flags => build/flags}/4x3/au.svg (100%) rename {flags => build/flags}/4x3/aw.svg (100%) rename {flags => build/flags}/4x3/ax.svg (100%) rename {flags => build/flags}/4x3/az.svg (100%) rename {flags => build/flags}/4x3/ba.svg (100%) rename {flags => build/flags}/4x3/bb.svg (100%) rename {flags => build/flags}/4x3/bd.svg (100%) rename {flags => build/flags}/4x3/be.svg (100%) rename {flags => build/flags}/4x3/bf.svg (100%) rename {flags => build/flags}/4x3/bg.svg (100%) rename {flags => build/flags}/4x3/bh.svg (100%) rename {flags => build/flags}/4x3/bi.svg (100%) rename {flags => build/flags}/4x3/bj.svg (100%) rename {flags => build/flags}/4x3/bl.svg (100%) rename {flags => build/flags}/4x3/bm.svg (100%) rename {flags => build/flags}/4x3/bn.svg (100%) rename {flags => build/flags}/4x3/bo.svg (100%) rename {flags => build/flags}/4x3/bq.svg (100%) rename {flags => build/flags}/4x3/br.svg (100%) rename {flags => build/flags}/4x3/bs.svg (100%) rename {flags => build/flags}/4x3/bt.svg (100%) rename {flags => build/flags}/4x3/bv.svg (100%) rename {flags => build/flags}/4x3/bw.svg (100%) rename {flags => build/flags}/4x3/by.svg (100%) rename {flags => build/flags}/4x3/bz.svg (100%) rename {flags => build/flags}/4x3/ca.svg (100%) rename {flags => build/flags}/4x3/cc.svg (100%) rename {flags => build/flags}/4x3/cd.svg (100%) rename {flags => build/flags}/4x3/cf.svg (100%) rename {flags => build/flags}/4x3/cg.svg (100%) rename {flags => build/flags}/4x3/ch.svg (100%) rename {flags => build/flags}/4x3/ci.svg (100%) rename {flags => build/flags}/4x3/ck.svg (100%) rename {flags => build/flags}/4x3/cl.svg (100%) rename {flags => build/flags}/4x3/cm.svg (100%) rename {flags => build/flags}/4x3/cn.svg (100%) rename {flags => build/flags}/4x3/co.svg (100%) rename {flags => build/flags}/4x3/cr.svg (100%) rename {flags => build/flags}/4x3/cu.svg (100%) rename {flags => build/flags}/4x3/cv.svg (100%) rename {flags => build/flags}/4x3/cw.svg (100%) rename {flags => build/flags}/4x3/cx.svg (100%) rename {flags => build/flags}/4x3/cy.svg (100%) rename {flags => build/flags}/4x3/cz.svg (100%) rename {flags => build/flags}/4x3/de.svg (100%) rename {flags => build/flags}/4x3/dj.svg (100%) rename {flags => build/flags}/4x3/dk.svg (100%) rename {flags => build/flags}/4x3/dm.svg (100%) rename {flags => build/flags}/4x3/do.svg (100%) rename {flags => build/flags}/4x3/dz.svg (100%) rename {flags => build/flags}/4x3/ec.svg (100%) rename {flags => build/flags}/4x3/ee.svg (100%) rename {flags => build/flags}/4x3/eg.svg (100%) rename {flags => build/flags}/4x3/eh.svg (100%) rename {flags => build/flags}/4x3/er.svg (100%) rename {flags => build/flags}/4x3/es.svg (100%) rename {flags => build/flags}/4x3/et.svg (100%) rename {flags => build/flags}/4x3/fi.svg (100%) rename {flags => build/flags}/4x3/fj.svg (100%) rename {flags => build/flags}/4x3/fk.svg (100%) rename {flags => build/flags}/4x3/fm.svg (100%) rename {flags => build/flags}/4x3/fo.svg (100%) rename {flags => build/flags}/4x3/fr.svg (100%) rename {flags => build/flags}/4x3/ga.svg (100%) rename {flags => build/flags}/4x3/gb.svg (100%) rename {flags => build/flags}/4x3/gd.svg (100%) rename {flags => build/flags}/4x3/ge.svg (100%) rename {flags => build/flags}/4x3/gf.svg (100%) rename {flags => build/flags}/4x3/gg.svg (100%) rename {flags => build/flags}/4x3/gh.svg (100%) rename {flags => build/flags}/4x3/gi.svg (100%) rename {flags => build/flags}/4x3/gl.svg (100%) rename {flags => build/flags}/4x3/gm.svg (100%) rename {flags => build/flags}/4x3/gn.svg (100%) rename {flags => build/flags}/4x3/gp.svg (100%) rename {flags => build/flags}/4x3/gq.svg (100%) rename {flags => build/flags}/4x3/gr.svg (100%) rename {flags => build/flags}/4x3/gs.svg (100%) rename {flags => build/flags}/4x3/gt.svg (100%) rename {flags => build/flags}/4x3/gu.svg (100%) rename {flags => build/flags}/4x3/gw.svg (100%) rename {flags => build/flags}/4x3/gy.svg (100%) rename {flags => build/flags}/4x3/hk.svg (100%) rename {flags => build/flags}/4x3/hm.svg (100%) rename {flags => build/flags}/4x3/hn.svg (100%) rename {flags => build/flags}/4x3/hr.svg (100%) rename {flags => build/flags}/4x3/ht.svg (100%) rename {flags => build/flags}/4x3/hu.svg (100%) rename {flags => build/flags}/4x3/id.svg (100%) rename {flags => build/flags}/4x3/ie.svg (100%) rename {flags => build/flags}/4x3/il.svg (100%) rename {flags => build/flags}/4x3/im.svg (100%) rename {flags => build/flags}/4x3/in.svg (100%) rename {flags => build/flags}/4x3/io.svg (100%) rename {flags => build/flags}/4x3/iq.svg (100%) rename {flags => build/flags}/4x3/ir.svg (100%) rename {flags => build/flags}/4x3/is.svg (100%) rename {flags => build/flags}/4x3/it.svg (100%) rename {flags => build/flags}/4x3/je.svg (100%) rename {flags => build/flags}/4x3/jm.svg (100%) rename {flags => build/flags}/4x3/jo.svg (100%) rename {flags => build/flags}/4x3/jp.svg (100%) rename {flags => build/flags}/4x3/ke.svg (100%) rename {flags => build/flags}/4x3/kg.svg (100%) rename {flags => build/flags}/4x3/kh.svg (100%) rename {flags => build/flags}/4x3/ki.svg (100%) rename {flags => build/flags}/4x3/km.svg (100%) rename {flags => build/flags}/4x3/kn.svg (100%) rename {flags => build/flags}/4x3/kp.svg (100%) rename {flags => build/flags}/4x3/kr.svg (100%) rename {flags => build/flags}/4x3/kw.svg (100%) rename {flags => build/flags}/4x3/ky.svg (100%) rename {flags => build/flags}/4x3/kz.svg (100%) rename {flags => build/flags}/4x3/la.svg (100%) rename {flags => build/flags}/4x3/lb.svg (100%) rename {flags => build/flags}/4x3/lc.svg (100%) rename {flags => build/flags}/4x3/li.svg (100%) rename {flags => build/flags}/4x3/lk.svg (100%) rename {flags => build/flags}/4x3/lr.svg (100%) rename {flags => build/flags}/4x3/ls.svg (100%) rename {flags => build/flags}/4x3/lt.svg (100%) rename {flags => build/flags}/4x3/lu.svg (100%) rename {flags => build/flags}/4x3/lv.svg (100%) rename {flags => build/flags}/4x3/ly.svg (100%) rename {flags => build/flags}/4x3/ma.svg (100%) rename {flags => build/flags}/4x3/mc.svg (100%) rename {flags => build/flags}/4x3/md.svg (100%) rename {flags => build/flags}/4x3/me.svg (100%) rename {flags => build/flags}/4x3/mf.svg (100%) rename {flags => build/flags}/4x3/mg.svg (100%) rename {flags => build/flags}/4x3/mh.svg (100%) rename {flags => build/flags}/4x3/mk.svg (100%) rename {flags => build/flags}/4x3/ml.svg (100%) rename {flags => build/flags}/4x3/mm.svg (100%) rename {flags => build/flags}/4x3/mn.svg (100%) rename {flags => build/flags}/4x3/mo.svg (100%) rename {flags => build/flags}/4x3/mp.svg (100%) rename {flags => build/flags}/4x3/mq.svg (100%) rename {flags => build/flags}/4x3/mr.svg (100%) rename {flags => build/flags}/4x3/ms.svg (100%) rename {flags => build/flags}/4x3/mt.svg (100%) rename {flags => build/flags}/4x3/mu.svg (100%) rename {flags => build/flags}/4x3/mv.svg (100%) rename {flags => build/flags}/4x3/mw.svg (100%) rename {flags => build/flags}/4x3/mx.svg (100%) rename {flags => build/flags}/4x3/my.svg (100%) rename {flags => build/flags}/4x3/mz.svg (100%) rename {flags => build/flags}/4x3/na.svg (100%) rename {flags => build/flags}/4x3/nc.svg (100%) rename {flags => build/flags}/4x3/ne.svg (100%) rename {flags => build/flags}/4x3/nf.svg (100%) rename {flags => build/flags}/4x3/ng.svg (100%) rename {flags => build/flags}/4x3/ni.svg (100%) rename {flags => build/flags}/4x3/nl.svg (100%) rename {flags => build/flags}/4x3/no.svg (100%) rename {flags => build/flags}/4x3/np.svg (100%) rename {flags => build/flags}/4x3/nr.svg (100%) rename {flags => build/flags}/4x3/nu.svg (100%) rename {flags => build/flags}/4x3/nz.svg (100%) rename {flags => build/flags}/4x3/om.svg (100%) rename {flags => build/flags}/4x3/pa.svg (100%) rename {flags => build/flags}/4x3/pe.svg (100%) rename {flags => build/flags}/4x3/pf.svg (100%) rename {flags => build/flags}/4x3/pg.svg (100%) rename {flags => build/flags}/4x3/ph.svg (100%) rename {flags => build/flags}/4x3/pk.svg (100%) rename {flags => build/flags}/4x3/pl.svg (100%) rename {flags => build/flags}/4x3/pm.svg (100%) rename {flags => build/flags}/4x3/pn.svg (100%) rename {flags => build/flags}/4x3/pr.svg (100%) rename {flags => build/flags}/4x3/ps.svg (100%) rename {flags => build/flags}/4x3/pt.svg (100%) rename {flags => build/flags}/4x3/pw.svg (100%) rename {flags => build/flags}/4x3/py.svg (100%) rename {flags => build/flags}/4x3/qa.svg (100%) rename {flags => build/flags}/4x3/re.svg (100%) rename {flags => build/flags}/4x3/ro.svg (100%) rename {flags => build/flags}/4x3/rs.svg (100%) rename {flags => build/flags}/4x3/ru.svg (100%) rename {flags => build/flags}/4x3/rw.svg (100%) rename {flags => build/flags}/4x3/sa.svg (100%) rename {flags => build/flags}/4x3/sb.svg (100%) rename {flags => build/flags}/4x3/sc.svg (100%) rename {flags => build/flags}/4x3/sd.svg (100%) rename {flags => build/flags}/4x3/se.svg (100%) rename {flags => build/flags}/4x3/sg.svg (100%) rename {flags => build/flags}/4x3/sh.svg (100%) rename {flags => build/flags}/4x3/si.svg (100%) rename {flags => build/flags}/4x3/sj.svg (100%) rename {flags => build/flags}/4x3/sk.svg (100%) rename {flags => build/flags}/4x3/sl.svg (100%) rename {flags => build/flags}/4x3/sm.svg (100%) rename {flags => build/flags}/4x3/sn.svg (100%) rename {flags => build/flags}/4x3/so.svg (100%) rename {flags => build/flags}/4x3/sr.svg (100%) rename {flags => build/flags}/4x3/ss.svg (100%) rename {flags => build/flags}/4x3/st.svg (100%) rename {flags => build/flags}/4x3/sv.svg (100%) rename {flags => build/flags}/4x3/sx.svg (100%) rename {flags => build/flags}/4x3/sy.svg (100%) rename {flags => build/flags}/4x3/sz.svg (100%) rename {flags => build/flags}/4x3/tc.svg (100%) rename {flags => build/flags}/4x3/td.svg (100%) rename {flags => build/flags}/4x3/tf.svg (100%) rename {flags => build/flags}/4x3/tg.svg (100%) rename {flags => build/flags}/4x3/th.svg (100%) rename {flags => build/flags}/4x3/tj.svg (100%) rename {flags => build/flags}/4x3/tk.svg (100%) rename {flags => build/flags}/4x3/tl.svg (100%) rename {flags => build/flags}/4x3/tm.svg (100%) rename {flags => build/flags}/4x3/tn.svg (100%) rename {flags => build/flags}/4x3/to.svg (100%) rename {flags => build/flags}/4x3/tr.svg (100%) rename {flags => build/flags}/4x3/tt.svg (100%) rename {flags => build/flags}/4x3/tv.svg (100%) rename {flags => build/flags}/4x3/tw.svg (100%) rename {flags => build/flags}/4x3/tz.svg (100%) rename {flags => build/flags}/4x3/ua.svg (100%) rename {flags => build/flags}/4x3/ug.svg (100%) rename {flags => build/flags}/4x3/um.svg (100%) rename {flags => build/flags}/4x3/us.svg (100%) rename {flags => build/flags}/4x3/uy.svg (100%) rename {flags => build/flags}/4x3/uz.svg (100%) rename {flags => build/flags}/4x3/va.svg (100%) rename {flags => build/flags}/4x3/vc.svg (100%) rename {flags => build/flags}/4x3/ve.svg (100%) rename {flags => build/flags}/4x3/vg.svg (100%) rename {flags => build/flags}/4x3/vi.svg (100%) rename {flags => build/flags}/4x3/vn.svg (100%) rename {flags => build/flags}/4x3/vu.svg (100%) rename {flags => build/flags}/4x3/wf.svg (100%) rename {flags => build/flags}/4x3/ws.svg (100%) rename {flags => build/flags}/4x3/ye.svg (100%) rename {flags => build/flags}/4x3/yt.svg (100%) rename {flags => build/flags}/4x3/za.svg (100%) rename {flags => build/flags}/4x3/zm.svg (100%) rename {flags => build/flags}/4x3/zw.svg (100%) rename {fonts => build/fonts}/FontAwesome.otf (100%) rename {fonts => build/fonts}/fontawesome-webfont.eot (100%) rename {fonts => build/fonts}/fontawesome-webfont.svg (100%) rename {fonts => build/fonts}/fontawesome-webfont.ttf (100%) rename {fonts => build/fonts}/fontawesome-webfont.woff (100%) rename {fonts => build/fonts}/fontawesome-webfont.woff2 (100%) rename index.html => build/index.html (95%) delete mode 100644 js/ctrls/alert.js delete mode 100644 js/directives/chunkbar.js delete mode 100644 js/directives/fileselect.js delete mode 100644 js/directives/fselect.js delete mode 100644 js/filters/url.js delete mode 100644 js/init.js delete mode 100644 js/services/deps.js delete mode 100644 js/services/errors.js delete mode 100644 js/services/utils.js create mode 100644 src/js/app.js create mode 100644 src/js/ctrls/alert.js rename {js => src/js}/ctrls/main.js (99%) rename {js => src/js}/ctrls/modal.js (99%) rename {js => src/js}/ctrls/nav.js (98%) rename {js => src/js}/ctrls/props.js (97%) create mode 100644 src/js/directives/chunkbar.js rename {js => src/js}/directives/dgraph.js (96%) create mode 100644 src/js/directives/fileselect.js create mode 100644 src/js/directives/fselect.js rename {js => src/js}/directives/textarea.js (88%) rename {js => src/js}/filters/bytes.js (93%) create mode 100644 src/js/filters/url.js rename {js => src/js}/libs/angular-translate.min.js (100%) rename {js => src/js}/libs/angular.min.js (100%) rename {js => src/js}/libs/angularui-bootstrap-tpls.min.js (100%) rename {js => src/js}/libs/bootstrap-filestyle.js (100%) rename {js => src/js}/libs/jquery-2.2.4.min.js (100%) rename {js => src/js}/libs/jquery.flot.min.js (100%) rename {js => src/js}/libs/jquery.flot.resize.min.js (100%) rename {js => src/js}/libs/jquery.flot.time.min.js (100%) rename {js => src/js}/libs/lodash-4.17.3.min.js (100%) rename {js => src/js}/services/alerts.js (77%) rename {js => src/js}/services/base64.js (92%) rename configuration.js => src/js/services/configuration.js (94%) create mode 100644 src/js/services/deps.js create mode 100644 src/js/services/errors.js rename {js => src/js}/services/modals.js (78%) rename {js => src/js}/services/rpc/helpers.js (97%) rename {js => src/js}/services/rpc/jsoncall.js (97%) rename {js => src/js}/services/rpc/rpc.js (99%) rename {js => src/js}/services/rpc/sockcall.js (98%) rename {js => src/js}/services/rpc/syscall.js (94%) rename {js => src/js}/services/settings/filters.js (87%) rename {js => src/js}/services/settings/settings.js (99%) create mode 100644 src/js/services/utils.js rename {js => src/js}/translate/cs_CZ.js (100%) rename {js => src/js}/translate/de_DE.js (100%) rename {js => src/js}/translate/en_US.js (100%) rename {js => src/js}/translate/es_ES.js (100%) rename {js => src/js}/translate/fa_IR.js (100%) rename {js => src/js}/translate/fr_FR.js (100%) rename {js => src/js}/translate/id_ID.js (100%) rename {js => src/js}/translate/it_IT.js (100%) rename {js => src/js}/translate/nl_NL.js (100%) rename {js => src/js}/translate/pl_PL.js (100%) rename {js => src/js}/translate/pt_BR.js (100%) rename {js => src/js}/translate/ru_RU.js (100%) rename {js => src/js}/translate/template.js (100%) rename {js => src/js}/translate/th_TH.js (100%) rename {js => src/js}/translate/tr_TR.js (100%) rename {js => src/js}/translate/zh_CN.js (100%) rename {js => src/js}/translate/zh_TW.js (100%) create mode 100644 webpack.config.js diff --git a/build/app.js b/build/app.js new file mode 100644 index 00000000..18ea040f --- /dev/null +++ b/build/app.js @@ -0,0 +1,835 @@ +/******/ (function(modules) { + // webpackBootstrap + /******/ // The module cache + /******/ var installedModules = {}; // The require function + /******/ + /******/ /******/ function __webpack_require__(moduleId) { + /******/ + /******/ // Check if module is in cache + /******/ if (installedModules[moduleId]) { + /******/ return installedModules[moduleId].exports; + /******/ + } // Create a new module (and put it into the cache) + /******/ /******/ var module = (installedModules[moduleId] = { + /******/ i: moduleId, + /******/ l: false, + /******/ exports: {} + /******/ + }); // Execute the module function + /******/ + /******/ /******/ modules[moduleId].call( + module.exports, + module, + module.exports, + __webpack_require__ + ); // Flag the module as loaded + /******/ + /******/ /******/ module.l = true; // Return the exports of the module + /******/ + /******/ /******/ return module.exports; + /******/ + } // expose the modules object (__webpack_modules__) + /******/ + /******/ + /******/ /******/ __webpack_require__.m = modules; // expose the module cache + /******/ + /******/ /******/ __webpack_require__.c = installedModules; // define getter function for harmony exports + /******/ + /******/ /******/ __webpack_require__.d = function(exports, name, getter) { + /******/ if (!__webpack_require__.o(exports, name)) { + /******/ Object.defineProperty(exports, name, { enumerable: true, get: getter }); + /******/ + } + /******/ + }; // define __esModule on exports + /******/ + /******/ /******/ __webpack_require__.r = function(exports) { + /******/ if (typeof Symbol !== "undefined" && Symbol.toStringTag) { + /******/ Object.defineProperty(exports, Symbol.toStringTag, { value: "Module" }); + /******/ + } + /******/ Object.defineProperty(exports, "__esModule", { value: true }); + /******/ + }; // create a fake namespace object // mode & 1: value is a module id, require it // mode & 2: merge all properties of value into the ns // mode & 4: return value when already ns object // mode & 8|1: behave like require + /******/ + /******/ /******/ /******/ /******/ /******/ /******/ __webpack_require__.t = function( + value, + mode + ) { + /******/ if (mode & 1) value = __webpack_require__(value); + /******/ if (mode & 8) return value; + /******/ if (mode & 4 && typeof value === "object" && value && value.__esModule) return value; + /******/ var ns = Object.create(null); + /******/ __webpack_require__.r(ns); + /******/ Object.defineProperty(ns, "default", { enumerable: true, value: value }); + /******/ if (mode & 2 && typeof value != "string") + for (var key in value) + __webpack_require__.d( + ns, + key, + function(key) { + return value[key]; + }.bind(null, key) + ); + /******/ return ns; + /******/ + }; // getDefaultExport function for compatibility with non-harmony modules + /******/ + /******/ /******/ __webpack_require__.n = function(module) { + /******/ var getter = + module && module.__esModule + ? /******/ function getDefault() { + return module["default"]; + } + : /******/ function getModuleExports() { + return module; + }; + /******/ __webpack_require__.d(getter, "a", getter); + /******/ return getter; + /******/ + }; // Object.prototype.hasOwnProperty.call + /******/ + /******/ /******/ __webpack_require__.o = function(object, property) { + return Object.prototype.hasOwnProperty.call(object, property); + }; // __webpack_public_path__ + /******/ + /******/ /******/ __webpack_require__.p = ""; // Load entry module and return exports + /******/ + /******/ + /******/ /******/ return __webpack_require__((__webpack_require__.s = "./src/js/app.js")); + /******/ +})( + /************************************************************************/ + /******/ { + /***/ "./node_modules/angular-translate/dist/angular-translate.js": + /*!******************************************************************!*\ + !*** ./node_modules/angular-translate/dist/angular-translate.js ***! + \******************************************************************/ + /*! no static exports found */ + /***/ function(module, exports, __webpack_require__) { + eval( + "var __WEBPACK_AMD_DEFINE_ARRAY__, __WEBPACK_AMD_DEFINE_RESULT__;/*!\n * angular-translate - v2.9.0 - 2016-01-24\n * \n * Copyright (c) 2016 The angular-translate team, Pascal Precht; Licensed MIT\n */\n(function (root, factory) {\n if (true) {\n // AMD. Register as an anonymous module unless amdModuleId is set\n !(__WEBPACK_AMD_DEFINE_ARRAY__ = [], __WEBPACK_AMD_DEFINE_RESULT__ = (function () {\n return (factory());\n }).apply(exports, __WEBPACK_AMD_DEFINE_ARRAY__),\n\t\t\t\t__WEBPACK_AMD_DEFINE_RESULT__ !== undefined && (module.exports = __WEBPACK_AMD_DEFINE_RESULT__));\n } else {}\n}(this, function () {\n\n/**\n * @ngdoc overview\n * @name pascalprecht.translate\n *\n * @description\n * The main module which holds everything together.\n */\nangular.module('pascalprecht.translate', ['ng'])\n .run(runTranslate);\n\nfunction runTranslate($translate) {\n\n 'use strict';\n\n var key = $translate.storageKey(),\n storage = $translate.storage();\n\n var fallbackFromIncorrectStorageValue = function () {\n var preferred = $translate.preferredLanguage();\n if (angular.isString(preferred)) {\n $translate.use(preferred);\n // $translate.use() will also remember the language.\n // So, we don't need to call storage.put() here.\n } else {\n storage.put(key, $translate.use());\n }\n };\n\n fallbackFromIncorrectStorageValue.displayName = 'fallbackFromIncorrectStorageValue';\n\n if (storage) {\n if (!storage.get(key)) {\n fallbackFromIncorrectStorageValue();\n } else {\n $translate.use(storage.get(key))['catch'](fallbackFromIncorrectStorageValue);\n }\n } else if (angular.isString($translate.preferredLanguage())) {\n $translate.use($translate.preferredLanguage());\n }\n}\nrunTranslate.$inject = ['$translate'];\n\nrunTranslate.displayName = 'runTranslate';\n\n/**\n * @ngdoc object\n * @name pascalprecht.translate.$translateSanitizationProvider\n *\n * @description\n *\n * Configurations for $translateSanitization\n */\nangular.module('pascalprecht.translate').provider('$translateSanitization', $translateSanitizationProvider);\n\nfunction $translateSanitizationProvider () {\n\n 'use strict';\n\n var $sanitize,\n currentStrategy = null, // TODO change to either 'sanitize', 'escape' or ['sanitize', 'escapeParameters'] in 3.0.\n hasConfiguredStrategy = false,\n hasShownNoStrategyConfiguredWarning = false,\n strategies;\n\n /**\n * Definition of a sanitization strategy function\n * @callback StrategyFunction\n * @param {string|object} value - value to be sanitized (either a string or an interpolated value map)\n * @param {string} mode - either 'text' for a string (translation) or 'params' for the interpolated params\n * @return {string|object}\n */\n\n /**\n * @ngdoc property\n * @name strategies\n * @propertyOf pascalprecht.translate.$translateSanitizationProvider\n *\n * @description\n * Following strategies are built-in:\n *
\n *
sanitize
\n *
Sanitizes HTML in the translation text using $sanitize
\n *
escape
\n *
Escapes HTML in the translation
\n *
sanitizeParameters
\n *
Sanitizes HTML in the values of the interpolation parameters using $sanitize
\n *
escapeParameters
\n *
Escapes HTML in the values of the interpolation parameters
\n *
escaped
\n *
Support legacy strategy name 'escaped' for backwards compatibility (will be removed in 3.0)
\n *
\n *\n */\n\n strategies = {\n sanitize: function (value, mode) {\n if (mode === 'text') {\n value = htmlSanitizeValue(value);\n }\n return value;\n },\n escape: function (value, mode) {\n if (mode === 'text') {\n value = htmlEscapeValue(value);\n }\n return value;\n },\n sanitizeParameters: function (value, mode) {\n if (mode === 'params') {\n value = mapInterpolationParameters(value, htmlSanitizeValue);\n }\n return value;\n },\n escapeParameters: function (value, mode) {\n if (mode === 'params') {\n value = mapInterpolationParameters(value, htmlEscapeValue);\n }\n return value;\n }\n };\n // Support legacy strategy name 'escaped' for backwards compatibility.\n // TODO should be removed in 3.0\n strategies.escaped = strategies.escapeParameters;\n\n /**\n * @ngdoc function\n * @name pascalprecht.translate.$translateSanitizationProvider#addStrategy\n * @methodOf pascalprecht.translate.$translateSanitizationProvider\n *\n * @description\n * Adds a sanitization strategy to the list of known strategies.\n *\n * @param {string} strategyName - unique key for a strategy\n * @param {StrategyFunction} strategyFunction - strategy function\n * @returns {object} this\n */\n this.addStrategy = function (strategyName, strategyFunction) {\n strategies[strategyName] = strategyFunction;\n return this;\n };\n\n /**\n * @ngdoc function\n * @name pascalprecht.translate.$translateSanitizationProvider#removeStrategy\n * @methodOf pascalprecht.translate.$translateSanitizationProvider\n *\n * @description\n * Removes a sanitization strategy from the list of known strategies.\n *\n * @param {string} strategyName - unique key for a strategy\n * @returns {object} this\n */\n this.removeStrategy = function (strategyName) {\n delete strategies[strategyName];\n return this;\n };\n\n /**\n * @ngdoc function\n * @name pascalprecht.translate.$translateSanitizationProvider#useStrategy\n * @methodOf pascalprecht.translate.$translateSanitizationProvider\n *\n * @description\n * Selects a sanitization strategy. When an array is provided the strategies will be executed in order.\n *\n * @param {string|StrategyFunction|array} strategy The sanitization strategy / strategies which should be used. Either a name of an existing strategy, a custom strategy function, or an array consisting of multiple names and / or custom functions.\n * @returns {object} this\n */\n this.useStrategy = function (strategy) {\n hasConfiguredStrategy = true;\n currentStrategy = strategy;\n return this;\n };\n\n /**\n * @ngdoc object\n * @name pascalprecht.translate.$translateSanitization\n * @requires $injector\n * @requires $log\n *\n * @description\n * Sanitizes interpolation parameters and translated texts.\n *\n */\n this.$get = ['$injector', '$log', function ($injector, $log) {\n\n var cachedStrategyMap = {};\n\n var applyStrategies = function (value, mode, selectedStrategies) {\n angular.forEach(selectedStrategies, function (selectedStrategy) {\n if (angular.isFunction(selectedStrategy)) {\n value = selectedStrategy(value, mode);\n } else if (angular.isFunction(strategies[selectedStrategy])) {\n value = strategies[selectedStrategy](value, mode);\n } else if (angular.isString(strategies[selectedStrategy])) {\n if (!cachedStrategyMap[strategies[selectedStrategy]]) {\n try {\n cachedStrategyMap[strategies[selectedStrategy]] = $injector.get(strategies[selectedStrategy]);\n } catch (e) {\n cachedStrategyMap[strategies[selectedStrategy]] = function() {};\n throw new Error('pascalprecht.translate.$translateSanitization: Unknown sanitization strategy: \\'' + selectedStrategy + '\\'');\n }\n }\n value = cachedStrategyMap[strategies[selectedStrategy]](value, mode);\n } else {\n throw new Error('pascalprecht.translate.$translateSanitization: Unknown sanitization strategy: \\'' + selectedStrategy + '\\'');\n }\n });\n return value;\n };\n\n // TODO: should be removed in 3.0\n var showNoStrategyConfiguredWarning = function () {\n if (!hasConfiguredStrategy && !hasShownNoStrategyConfiguredWarning) {\n $log.warn('pascalprecht.translate.$translateSanitization: No sanitization strategy has been configured. This can have serious security implications. See http://angular-translate.github.io/docs/#/guide/19_security for details.');\n hasShownNoStrategyConfiguredWarning = true;\n }\n };\n\n if ($injector.has('$sanitize')) {\n $sanitize = $injector.get('$sanitize');\n }\n\n return {\n /**\n * @ngdoc function\n * @name pascalprecht.translate.$translateSanitization#useStrategy\n * @methodOf pascalprecht.translate.$translateSanitization\n *\n * @description\n * Selects a sanitization strategy. When an array is provided the strategies will be executed in order.\n *\n * @param {string|StrategyFunction|array} strategy The sanitization strategy / strategies which should be used. Either a name of an existing strategy, a custom strategy function, or an array consisting of multiple names and / or custom functions.\n */\n useStrategy: (function (self) {\n return function (strategy) {\n self.useStrategy(strategy);\n };\n })(this),\n\n /**\n * @ngdoc function\n * @name pascalprecht.translate.$translateSanitization#sanitize\n * @methodOf pascalprecht.translate.$translateSanitization\n *\n * @description\n * Sanitizes a value.\n *\n * @param {string|object} value The value which should be sanitized.\n * @param {string} mode The current sanitization mode, either 'params' or 'text'.\n * @param {string|StrategyFunction|array} [strategy] Optional custom strategy which should be used instead of the currently selected strategy.\n * @returns {string|object} sanitized value\n */\n sanitize: function (value, mode, strategy) {\n if (!currentStrategy) {\n showNoStrategyConfiguredWarning();\n }\n\n if (arguments.length < 3) {\n strategy = currentStrategy;\n }\n\n if (!strategy) {\n return value;\n }\n\n var selectedStrategies = angular.isArray(strategy) ? strategy : [strategy];\n return applyStrategies(value, mode, selectedStrategies);\n }\n };\n }];\n\n var htmlEscapeValue = function (value) {\n var element = angular.element('
');\n element.text(value); // not chainable, see #1044\n return element.html();\n };\n\n var htmlSanitizeValue = function (value) {\n if (!$sanitize) {\n throw new Error('pascalprecht.translate.$translateSanitization: Error cannot find $sanitize service. Either include the ngSanitize module (https://docs.angularjs.org/api/ngSanitize) or use a sanitization strategy which does not depend on $sanitize, such as \\'escape\\'.');\n }\n return $sanitize(value);\n };\n\n var mapInterpolationParameters = function (value, iteratee) {\n if (angular.isObject(value)) {\n var result = angular.isArray(value) ? [] : {};\n\n angular.forEach(value, function (propertyValue, propertyKey) {\n result[propertyKey] = mapInterpolationParameters(propertyValue, iteratee);\n });\n\n return result;\n } else if (angular.isNumber(value)) {\n return value;\n } else {\n return iteratee(value);\n }\n };\n}\n\n/**\n * @ngdoc object\n * @name pascalprecht.translate.$translateProvider\n * @description\n *\n * $translateProvider allows developers to register translation-tables, asynchronous loaders\n * and similar to configure translation behavior directly inside of a module.\n *\n */\nangular.module('pascalprecht.translate')\n.constant('pascalprechtTranslateOverrider', {})\n.provider('$translate', $translate);\n\nfunction $translate($STORAGE_KEY, $windowProvider, $translateSanitizationProvider, pascalprechtTranslateOverrider) {\n\n 'use strict';\n\n var $translationTable = {},\n $preferredLanguage,\n $availableLanguageKeys = [],\n $languageKeyAliases,\n $fallbackLanguage,\n $fallbackWasString,\n $uses,\n $nextLang,\n $storageFactory,\n $storageKey = $STORAGE_KEY,\n $storagePrefix,\n $missingTranslationHandlerFactory,\n $interpolationFactory,\n $interpolatorFactories = [],\n $loaderFactory,\n $cloakClassName = 'translate-cloak',\n $loaderOptions,\n $notFoundIndicatorLeft,\n $notFoundIndicatorRight,\n $postCompilingEnabled = false,\n $forceAsyncReloadEnabled = false,\n $nestedObjectDelimeter = '.',\n $isReady = false,\n loaderCache,\n directivePriority = 0,\n statefulFilter = true,\n uniformLanguageTagResolver = 'default',\n languageTagResolver = {\n 'default': function (tag) {\n return (tag || '').split('-').join('_');\n },\n java: function (tag) {\n var temp = (tag || '').split('-').join('_');\n var parts = temp.split('_');\n return parts.length > 1 ? (parts[0].toLowerCase() + '_' + parts[1].toUpperCase()) : temp;\n },\n bcp47: function (tag) {\n var temp = (tag || '').split('_').join('-');\n var parts = temp.split('-');\n return parts.length > 1 ? (parts[0].toLowerCase() + '-' + parts[1].toUpperCase()) : temp;\n }\n };\n\n var version = '2.9.0';\n\n // tries to determine the browsers language\n var getFirstBrowserLanguage = function () {\n\n // internal purpose only\n if (angular.isFunction(pascalprechtTranslateOverrider.getLocale)) {\n return pascalprechtTranslateOverrider.getLocale();\n }\n\n var nav = $windowProvider.$get().navigator,\n browserLanguagePropertyKeys = ['language', 'browserLanguage', 'systemLanguage', 'userLanguage'],\n i,\n language;\n\n // support for HTML 5.1 \"navigator.languages\"\n if (angular.isArray(nav.languages)) {\n for (i = 0; i < nav.languages.length; i++) {\n language = nav.languages[i];\n if (language && language.length) {\n return language;\n }\n }\n }\n\n // support for other well known properties in browsers\n for (i = 0; i < browserLanguagePropertyKeys.length; i++) {\n language = nav[browserLanguagePropertyKeys[i]];\n if (language && language.length) {\n return language;\n }\n }\n\n return null;\n };\n getFirstBrowserLanguage.displayName = 'angular-translate/service: getFirstBrowserLanguage';\n\n // tries to determine the browsers locale\n var getLocale = function () {\n var locale = getFirstBrowserLanguage() || '';\n if (languageTagResolver[uniformLanguageTagResolver]) {\n locale = languageTagResolver[uniformLanguageTagResolver](locale);\n }\n return locale;\n };\n getLocale.displayName = 'angular-translate/service: getLocale';\n\n /**\n * @name indexOf\n * @private\n *\n * @description\n * indexOf polyfill. Kinda sorta.\n *\n * @param {array} array Array to search in.\n * @param {string} searchElement Element to search for.\n *\n * @returns {int} Index of search element.\n */\n var indexOf = function(array, searchElement) {\n for (var i = 0, len = array.length; i < len; i++) {\n if (array[i] === searchElement) {\n return i;\n }\n }\n return -1;\n };\n\n /**\n * @name trim\n * @private\n *\n * @description\n * trim polyfill\n *\n * @returns {string} The string stripped of whitespace from both ends\n */\n var trim = function() {\n return this.toString().replace(/^\\s+|\\s+$/g, '');\n };\n\n var negotiateLocale = function (preferred) {\n if(!preferred) {\n return;\n }\n\n var avail = [],\n locale = angular.lowercase(preferred),\n i = 0,\n n = $availableLanguageKeys.length;\n\n for (; i < n; i++) {\n avail.push(angular.lowercase($availableLanguageKeys[i]));\n }\n\n // Check for an exact match in our list of available keys\n if (indexOf(avail, locale) > -1) {\n return preferred;\n }\n\n if ($languageKeyAliases) {\n var alias;\n for (var langKeyAlias in $languageKeyAliases) {\n var hasWildcardKey = false;\n var hasExactKey = Object.prototype.hasOwnProperty.call($languageKeyAliases, langKeyAlias) &&\n angular.lowercase(langKeyAlias) === angular.lowercase(preferred);\n\n if (langKeyAlias.slice(-1) === '*') {\n hasWildcardKey = langKeyAlias.slice(0, -1) === preferred.slice(0, langKeyAlias.length-1);\n }\n if (hasExactKey || hasWildcardKey) {\n alias = $languageKeyAliases[langKeyAlias];\n if (indexOf(avail, angular.lowercase(alias)) > -1) {\n return alias;\n }\n }\n }\n }\n\n // Check for a language code without region\n var parts = preferred.split('_');\n\n if (parts.length > 1 && indexOf(avail, angular.lowercase(parts[0])) > -1) {\n return parts[0];\n }\n\n // If everything fails, return undefined.\n return;\n };\n\n /**\n * @ngdoc function\n * @name pascalprecht.translate.$translateProvider#translations\n * @methodOf pascalprecht.translate.$translateProvider\n *\n * @description\n * Registers a new translation table for specific language key.\n *\n * To register a translation table for specific language, pass a defined language\n * key as first parameter.\n *\n *
\n   *  // register translation table for language: 'de_DE'\n   *  $translateProvider.translations('de_DE', {\n   *    'GREETING': 'Hallo Welt!'\n   *  });\n   *\n   *  // register another one\n   *  $translateProvider.translations('en_US', {\n   *    'GREETING': 'Hello world!'\n   *  });\n   * 
\n *\n * When registering multiple translation tables for for the same language key,\n * the actual translation table gets extended. This allows you to define module\n * specific translation which only get added, once a specific module is loaded in\n * your app.\n *\n * Invoking this method with no arguments returns the translation table which was\n * registered with no language key. Invoking it with a language key returns the\n * related translation table.\n *\n * @param {string} key A language key.\n * @param {object} translationTable A plain old JavaScript object that represents a translation table.\n *\n */\n var translations = function (langKey, translationTable) {\n\n if (!langKey && !translationTable) {\n return $translationTable;\n }\n\n if (langKey && !translationTable) {\n if (angular.isString(langKey)) {\n return $translationTable[langKey];\n }\n } else {\n if (!angular.isObject($translationTable[langKey])) {\n $translationTable[langKey] = {};\n }\n angular.extend($translationTable[langKey], flatObject(translationTable));\n }\n return this;\n };\n\n this.translations = translations;\n\n /**\n * @ngdoc function\n * @name pascalprecht.translate.$translateProvider#cloakClassName\n * @methodOf pascalprecht.translate.$translateProvider\n *\n * @description\n *\n * Let's you change the class name for `translate-cloak` directive.\n * Default class name is `translate-cloak`.\n *\n * @param {string} name translate-cloak class name\n */\n this.cloakClassName = function (name) {\n if (!name) {\n return $cloakClassName;\n }\n $cloakClassName = name;\n return this;\n };\n\n /**\n * @ngdoc function\n * @name pascalprecht.translate.$translateProvider#nestedObjectDelimeter\n * @methodOf pascalprecht.translate.$translateProvider\n *\n * @description\n *\n * Let's you change the delimiter for namespaced translations.\n * Default delimiter is `.`.\n *\n * @param {string} delimiter namespace separator\n */\n this.nestedObjectDelimeter = function (delimiter) {\n if (!delimiter) {\n return $nestedObjectDelimeter;\n }\n $nestedObjectDelimeter = delimiter;\n return this;\n };\n\n /**\n * @name flatObject\n * @private\n *\n * @description\n * Flats an object. This function is used to flatten given translation data with\n * namespaces, so they are later accessible via dot notation.\n */\n var flatObject = function (data, path, result, prevKey) {\n var key, keyWithPath, keyWithShortPath, val;\n\n if (!path) {\n path = [];\n }\n if (!result) {\n result = {};\n }\n for (key in data) {\n if (!Object.prototype.hasOwnProperty.call(data, key)) {\n continue;\n }\n val = data[key];\n if (angular.isObject(val)) {\n flatObject(val, path.concat(key), result, key);\n } else {\n keyWithPath = path.length ? ('' + path.join($nestedObjectDelimeter) + $nestedObjectDelimeter + key) : key;\n if(path.length && key === prevKey){\n // Create shortcut path (foo.bar == foo.bar.bar)\n keyWithShortPath = '' + path.join($nestedObjectDelimeter);\n // Link it to original path\n result[keyWithShortPath] = '@:' + keyWithPath;\n }\n result[keyWithPath] = val;\n }\n }\n return result;\n };\n flatObject.displayName = 'flatObject';\n\n /**\n * @ngdoc function\n * @name pascalprecht.translate.$translateProvider#addInterpolation\n * @methodOf pascalprecht.translate.$translateProvider\n *\n * @description\n * Adds interpolation services to angular-translate, so it can manage them.\n *\n * @param {object} factory Interpolation service factory\n */\n this.addInterpolation = function (factory) {\n $interpolatorFactories.push(factory);\n return this;\n };\n\n /**\n * @ngdoc function\n * @name pascalprecht.translate.$translateProvider#useMessageFormatInterpolation\n * @methodOf pascalprecht.translate.$translateProvider\n *\n * @description\n * Tells angular-translate to use interpolation functionality of messageformat.js.\n * This is useful when having high level pluralization and gender selection.\n */\n this.useMessageFormatInterpolation = function () {\n return this.useInterpolation('$translateMessageFormatInterpolation');\n };\n\n /**\n * @ngdoc function\n * @name pascalprecht.translate.$translateProvider#useInterpolation\n * @methodOf pascalprecht.translate.$translateProvider\n *\n * @description\n * Tells angular-translate which interpolation style to use as default, application-wide.\n * Simply pass a factory/service name. The interpolation service has to implement\n * the correct interface.\n *\n * @param {string} factory Interpolation service name.\n */\n this.useInterpolation = function (factory) {\n $interpolationFactory = factory;\n return this;\n };\n\n /**\n * @ngdoc function\n * @name pascalprecht.translate.$translateProvider#useSanitizeStrategy\n * @methodOf pascalprecht.translate.$translateProvider\n *\n * @description\n * Simply sets a sanitation strategy type.\n *\n * @param {string} value Strategy type.\n */\n this.useSanitizeValueStrategy = function (value) {\n $translateSanitizationProvider.useStrategy(value);\n return this;\n };\n\n /**\n * @ngdoc function\n * @name pascalprecht.translate.$translateProvider#preferredLanguage\n * @methodOf pascalprecht.translate.$translateProvider\n *\n * @description\n * Tells the module which of the registered translation tables to use for translation\n * at initial startup by passing a language key. Similar to `$translateProvider#use`\n * only that it says which language to **prefer**.\n *\n * @param {string} langKey A language key.\n */\n this.preferredLanguage = function(langKey) {\n if (langKey) {\n setupPreferredLanguage(langKey);\n return this;\n }\n return $preferredLanguage;\n };\n var setupPreferredLanguage = function (langKey) {\n if (langKey) {\n $preferredLanguage = langKey;\n }\n return $preferredLanguage;\n };\n /**\n * @ngdoc function\n * @name pascalprecht.translate.$translateProvider#translationNotFoundIndicator\n * @methodOf pascalprecht.translate.$translateProvider\n *\n * @description\n * Sets an indicator which is used when a translation isn't found. E.g. when\n * setting the indicator as 'X' and one tries to translate a translation id\n * called `NOT_FOUND`, this will result in `X NOT_FOUND X`.\n *\n * Internally this methods sets a left indicator and a right indicator using\n * `$translateProvider.translationNotFoundIndicatorLeft()` and\n * `$translateProvider.translationNotFoundIndicatorRight()`.\n *\n * **Note**: These methods automatically add a whitespace between the indicators\n * and the translation id.\n *\n * @param {string} indicator An indicator, could be any string.\n */\n this.translationNotFoundIndicator = function (indicator) {\n this.translationNotFoundIndicatorLeft(indicator);\n this.translationNotFoundIndicatorRight(indicator);\n return this;\n };\n\n /**\n * ngdoc function\n * @name pascalprecht.translate.$translateProvider#translationNotFoundIndicatorLeft\n * @methodOf pascalprecht.translate.$translateProvider\n *\n * @description\n * Sets an indicator which is used when a translation isn't found left to the\n * translation id.\n *\n * @param {string} indicator An indicator.\n */\n this.translationNotFoundIndicatorLeft = function (indicator) {\n if (!indicator) {\n return $notFoundIndicatorLeft;\n }\n $notFoundIndicatorLeft = indicator;\n return this;\n };\n\n /**\n * ngdoc function\n * @name pascalprecht.translate.$translateProvider#translationNotFoundIndicatorLeft\n * @methodOf pascalprecht.translate.$translateProvider\n *\n * @description\n * Sets an indicator which is used when a translation isn't found right to the\n * translation id.\n *\n * @param {string} indicator An indicator.\n */\n this.translationNotFoundIndicatorRight = function (indicator) {\n if (!indicator) {\n return $notFoundIndicatorRight;\n }\n $notFoundIndicatorRight = indicator;\n return this;\n };\n\n /**\n * @ngdoc function\n * @name pascalprecht.translate.$translateProvider#fallbackLanguage\n * @methodOf pascalprecht.translate.$translateProvider\n *\n * @description\n * Tells the module which of the registered translation tables to use when missing translations\n * at initial startup by passing a language key. Similar to `$translateProvider#use`\n * only that it says which language to **fallback**.\n *\n * @param {string||array} langKey A language key.\n *\n */\n this.fallbackLanguage = function (langKey) {\n fallbackStack(langKey);\n return this;\n };\n\n var fallbackStack = function (langKey) {\n if (langKey) {\n if (angular.isString(langKey)) {\n $fallbackWasString = true;\n $fallbackLanguage = [ langKey ];\n } else if (angular.isArray(langKey)) {\n $fallbackWasString = false;\n $fallbackLanguage = langKey;\n }\n if (angular.isString($preferredLanguage) && indexOf($fallbackLanguage, $preferredLanguage) < 0) {\n $fallbackLanguage.push($preferredLanguage);\n }\n\n return this;\n } else {\n if ($fallbackWasString) {\n return $fallbackLanguage[0];\n } else {\n return $fallbackLanguage;\n }\n }\n };\n\n /**\n * @ngdoc function\n * @name pascalprecht.translate.$translateProvider#use\n * @methodOf pascalprecht.translate.$translateProvider\n *\n * @description\n * Set which translation table to use for translation by given language key. When\n * trying to 'use' a language which isn't provided, it'll throw an error.\n *\n * You actually don't have to use this method since `$translateProvider#preferredLanguage`\n * does the job too.\n *\n * @param {string} langKey A language key.\n */\n this.use = function (langKey) {\n if (langKey) {\n if (!$translationTable[langKey] && (!$loaderFactory)) {\n // only throw an error, when not loading translation data asynchronously\n throw new Error('$translateProvider couldn\\'t find translationTable for langKey: \\'' + langKey + '\\'');\n }\n $uses = langKey;\n return this;\n }\n return $uses;\n };\n\n /**\n * @ngdoc function\n * @name pascalprecht.translate.$translateProvider#storageKey\n * @methodOf pascalprecht.translate.$translateProvider\n *\n * @description\n * Tells the module which key must represent the choosed language by a user in the storage.\n *\n * @param {string} key A key for the storage.\n */\n var storageKey = function(key) {\n if (!key) {\n if ($storagePrefix) {\n return $storagePrefix + $storageKey;\n }\n return $storageKey;\n }\n $storageKey = key;\n return this;\n };\n\n this.storageKey = storageKey;\n\n /**\n * @ngdoc function\n * @name pascalprecht.translate.$translateProvider#useUrlLoader\n * @methodOf pascalprecht.translate.$translateProvider\n *\n * @description\n * Tells angular-translate to use `$translateUrlLoader` extension service as loader.\n *\n * @param {string} url Url\n * @param {Object=} options Optional configuration object\n */\n this.useUrlLoader = function (url, options) {\n return this.useLoader('$translateUrlLoader', angular.extend({ url: url }, options));\n };\n\n /**\n * @ngdoc function\n * @name pascalprecht.translate.$translateProvider#useStaticFilesLoader\n * @methodOf pascalprecht.translate.$translateProvider\n *\n * @description\n * Tells angular-translate to use `$translateStaticFilesLoader` extension service as loader.\n *\n * @param {Object=} options Optional configuration object\n */\n this.useStaticFilesLoader = function (options) {\n return this.useLoader('$translateStaticFilesLoader', options);\n };\n\n /**\n * @ngdoc function\n * @name pascalprecht.translate.$translateProvider#useLoader\n * @methodOf pascalprecht.translate.$translateProvider\n *\n * @description\n * Tells angular-translate to use any other service as loader.\n *\n * @param {string} loaderFactory Factory name to use\n * @param {Object=} options Optional configuration object\n */\n this.useLoader = function (loaderFactory, options) {\n $loaderFactory = loaderFactory;\n $loaderOptions = options || {};\n return this;\n };\n\n /**\n * @ngdoc function\n * @name pascalprecht.translate.$translateProvider#useLocalStorage\n * @methodOf pascalprecht.translate.$translateProvider\n *\n * @description\n * Tells angular-translate to use `$translateLocalStorage` service as storage layer.\n *\n */\n this.useLocalStorage = function () {\n return this.useStorage('$translateLocalStorage');\n };\n\n /**\n * @ngdoc function\n * @name pascalprecht.translate.$translateProvider#useCookieStorage\n * @methodOf pascalprecht.translate.$translateProvider\n *\n * @description\n * Tells angular-translate to use `$translateCookieStorage` service as storage layer.\n */\n this.useCookieStorage = function () {\n return this.useStorage('$translateCookieStorage');\n };\n\n /**\n * @ngdoc function\n * @name pascalprecht.translate.$translateProvider#useStorage\n * @methodOf pascalprecht.translate.$translateProvider\n *\n * @description\n * Tells angular-translate to use custom service as storage layer.\n */\n this.useStorage = function (storageFactory) {\n $storageFactory = storageFactory;\n return this;\n };\n\n /**\n * @ngdoc function\n * @name pascalprecht.translate.$translateProvider#storagePrefix\n * @methodOf pascalprecht.translate.$translateProvider\n *\n * @description\n * Sets prefix for storage key.\n *\n * @param {string} prefix Storage key prefix\n */\n this.storagePrefix = function (prefix) {\n if (!prefix) {\n return prefix;\n }\n $storagePrefix = prefix;\n return this;\n };\n\n /**\n * @ngdoc function\n * @name pascalprecht.translate.$translateProvider#useMissingTranslationHandlerLog\n * @methodOf pascalprecht.translate.$translateProvider\n *\n * @description\n * Tells angular-translate to use built-in log handler when trying to translate\n * a translation Id which doesn't exist.\n *\n * This is actually a shortcut method for `useMissingTranslationHandler()`.\n *\n */\n this.useMissingTranslationHandlerLog = function () {\n return this.useMissingTranslationHandler('$translateMissingTranslationHandlerLog');\n };\n\n /**\n * @ngdoc function\n * @name pascalprecht.translate.$translateProvider#useMissingTranslationHandler\n * @methodOf pascalprecht.translate.$translateProvider\n *\n * @description\n * Expects a factory name which later gets instantiated with `$injector`.\n * This method can be used to tell angular-translate to use a custom\n * missingTranslationHandler. Just build a factory which returns a function\n * and expects a translation id as argument.\n *\n * Example:\n *
\n   *  app.config(function ($translateProvider) {\n   *    $translateProvider.useMissingTranslationHandler('customHandler');\n   *  });\n   *\n   *  app.factory('customHandler', function (dep1, dep2) {\n   *    return function (translationId) {\n   *      // something with translationId and dep1 and dep2\n   *    };\n   *  });\n   * 
\n *\n * @param {string} factory Factory name\n */\n this.useMissingTranslationHandler = function (factory) {\n $missingTranslationHandlerFactory = factory;\n return this;\n };\n\n /**\n * @ngdoc function\n * @name pascalprecht.translate.$translateProvider#usePostCompiling\n * @methodOf pascalprecht.translate.$translateProvider\n *\n * @description\n * If post compiling is enabled, all translated values will be processed\n * again with AngularJS' $compile.\n *\n * Example:\n *
\n   *  app.config(function ($translateProvider) {\n   *    $translateProvider.usePostCompiling(true);\n   *  });\n   * 
\n *\n * @param {string} factory Factory name\n */\n this.usePostCompiling = function (value) {\n $postCompilingEnabled = !(!value);\n return this;\n };\n\n /**\n * @ngdoc function\n * @name pascalprecht.translate.$translateProvider#forceAsyncReload\n * @methodOf pascalprecht.translate.$translateProvider\n *\n * @description\n * If force async reload is enabled, async loader will always be called\n * even if $translationTable already contains the language key, adding\n * possible new entries to the $translationTable.\n *\n * Example:\n *
\n   *  app.config(function ($translateProvider) {\n   *    $translateProvider.forceAsyncReload(true);\n   *  });\n   * 
\n *\n * @param {boolean} value - valid values are true or false\n */\n this.forceAsyncReload = function (value) {\n $forceAsyncReloadEnabled = !(!value);\n return this;\n };\n\n /**\n * @ngdoc function\n * @name pascalprecht.translate.$translateProvider#uniformLanguageTag\n * @methodOf pascalprecht.translate.$translateProvider\n *\n * @description\n * Tells angular-translate which language tag should be used as a result when determining\n * the current browser language.\n *\n * This setting must be set before invoking {@link pascalprecht.translate.$translateProvider#methods_determinePreferredLanguage determinePreferredLanguage()}.\n *\n *
\n   * $translateProvider\n   *   .uniformLanguageTag('bcp47')\n   *   .determinePreferredLanguage()\n   * 
\n *\n * The resolver currently supports:\n * * default\n * (traditionally: hyphens will be converted into underscores, i.e. en-US => en_US)\n * en-US => en_US\n * en_US => en_US\n * en-us => en_us\n * * java\n * like default, but the second part will be always in uppercase\n * en-US => en_US\n * en_US => en_US\n * en-us => en_US\n * * BCP 47 (RFC 4646 & 4647)\n * en-US => en-US\n * en_US => en-US\n * en-us => en-US\n *\n * See also:\n * * http://en.wikipedia.org/wiki/IETF_language_tag\n * * http://www.w3.org/International/core/langtags/\n * * http://tools.ietf.org/html/bcp47\n *\n * @param {string|object} options - options (or standard)\n * @param {string} options.standard - valid values are 'default', 'bcp47', 'java'\n */\n this.uniformLanguageTag = function (options) {\n\n if (!options) {\n options = {};\n } else if (angular.isString(options)) {\n options = {\n standard: options\n };\n }\n\n uniformLanguageTagResolver = options.standard;\n\n return this;\n };\n\n /**\n * @ngdoc function\n * @name pascalprecht.translate.$translateProvider#determinePreferredLanguage\n * @methodOf pascalprecht.translate.$translateProvider\n *\n * @description\n * Tells angular-translate to try to determine on its own which language key\n * to set as preferred language. When `fn` is given, angular-translate uses it\n * to determine a language key, otherwise it uses the built-in `getLocale()`\n * method.\n *\n * The `getLocale()` returns a language key in the format `[lang]_[country]` or\n * `[lang]` depending on what the browser provides.\n *\n * Use this method at your own risk, since not all browsers return a valid\n * locale (see {@link pascalprecht.translate.$translateProvider#methods_uniformLanguageTag uniformLanguageTag()}).\n *\n * @param {Function=} fn Function to determine a browser's locale\n */\n this.determinePreferredLanguage = function (fn) {\n\n var locale = (fn && angular.isFunction(fn)) ? fn() : getLocale();\n\n if (!$availableLanguageKeys.length) {\n $preferredLanguage = locale;\n } else {\n $preferredLanguage = negotiateLocale(locale) || locale;\n }\n\n return this;\n };\n\n /**\n * @ngdoc function\n * @name pascalprecht.translate.$translateProvider#registerAvailableLanguageKeys\n * @methodOf pascalprecht.translate.$translateProvider\n *\n * @description\n * Registers a set of language keys the app will work with. Use this method in\n * combination with\n * {@link pascalprecht.translate.$translateProvider#determinePreferredLanguage determinePreferredLanguage}.\n * When available languages keys are registered, angular-translate\n * tries to find the best fitting language key depending on the browsers locale,\n * considering your language key convention.\n *\n * @param {object} languageKeys Array of language keys the your app will use\n * @param {object=} aliases Alias map.\n */\n this.registerAvailableLanguageKeys = function (languageKeys, aliases) {\n if (languageKeys) {\n $availableLanguageKeys = languageKeys;\n if (aliases) {\n $languageKeyAliases = aliases;\n }\n return this;\n }\n return $availableLanguageKeys;\n };\n\n /**\n * @ngdoc function\n * @name pascalprecht.translate.$translateProvider#useLoaderCache\n * @methodOf pascalprecht.translate.$translateProvider\n *\n * @description\n * Registers a cache for internal $http based loaders.\n * {@link pascalprecht.translate.$translationCache $translationCache}.\n * When false the cache will be disabled (default). When true or undefined\n * the cache will be a default (see $cacheFactory). When an object it will\n * be treat as a cache object itself: the usage is $http({cache: cache})\n *\n * @param {object} cache boolean, string or cache-object\n */\n this.useLoaderCache = function (cache) {\n if (cache === false) {\n // disable cache\n loaderCache = undefined;\n } else if (cache === true) {\n // enable cache using AJS defaults\n loaderCache = true;\n } else if (typeof(cache) === 'undefined') {\n // enable cache using default\n loaderCache = '$translationCache';\n } else if (cache) {\n // enable cache using given one (see $cacheFactory)\n loaderCache = cache;\n }\n return this;\n };\n\n /**\n * @ngdoc function\n * @name pascalprecht.translate.$translateProvider#directivePriority\n * @methodOf pascalprecht.translate.$translateProvider\n *\n * @description\n * Sets the default priority of the translate directive. The standard value is `0`.\n * Calling this function without an argument will return the current value.\n *\n * @param {number} priority for the translate-directive\n */\n this.directivePriority = function (priority) {\n if (priority === undefined) {\n // getter\n return directivePriority;\n } else {\n // setter with chaining\n directivePriority = priority;\n return this;\n }\n };\n\n /**\n * @ngdoc function\n * @name pascalprecht.translate.$translateProvider#statefulFilter\n * @methodOf pascalprecht.translate.$translateProvider\n *\n * @description\n * Since AngularJS 1.3, filters which are not stateless (depending at the scope)\n * have to explicit define this behavior.\n * Sets whether the translate filter should be stateful or stateless. The standard value is `true`\n * meaning being stateful.\n * Calling this function without an argument will return the current value.\n *\n * @param {boolean} state - defines the state of the filter\n */\n this.statefulFilter = function (state) {\n if (state === undefined) {\n // getter\n return statefulFilter;\n } else {\n // setter with chaining\n statefulFilter = state;\n return this;\n }\n };\n\n /**\n * @ngdoc object\n * @name pascalprecht.translate.$translate\n * @requires $interpolate\n * @requires $log\n * @requires $rootScope\n * @requires $q\n *\n * @description\n * The `$translate` service is the actual core of angular-translate. It expects a translation id\n * and optional interpolate parameters to translate contents.\n *\n *
\n   *  $translate('HEADLINE_TEXT').then(function (translation) {\n   *    $scope.translatedText = translation;\n   *  });\n   * 
\n *\n * @param {string|array} translationId A token which represents a translation id\n * This can be optionally an array of translation ids which\n * results that the function returns an object where each key\n * is the translation id and the value the translation.\n * @param {object=} interpolateParams An object hash for dynamic values\n * @param {string} interpolationId The id of the interpolation to use\n * @param {string} forceLanguage A language to be used instead of the current language\n * @returns {object} promise\n */\n this.$get = [\n '$log',\n '$injector',\n '$rootScope',\n '$q',\n function ($log, $injector, $rootScope, $q) {\n\n var Storage,\n defaultInterpolator = $injector.get($interpolationFactory || '$translateDefaultInterpolation'),\n pendingLoader = false,\n interpolatorHashMap = {},\n langPromises = {},\n fallbackIndex,\n startFallbackIteration;\n\n var $translate = function (translationId, interpolateParams, interpolationId, defaultTranslationText, forceLanguage) {\n\n var uses = (forceLanguage && forceLanguage !== $uses) ? // we don't want to re-negotiate $uses\n (negotiateLocale(forceLanguage) || forceLanguage) : $uses;\n\n // Duck detection: If the first argument is an array, a bunch of translations was requested.\n // The result is an object.\n if (angular.isArray(translationId)) {\n // Inspired by Q.allSettled by Kris Kowal\n // https://github.com/kriskowal/q/blob/b0fa72980717dc202ffc3cbf03b936e10ebbb9d7/q.js#L1553-1563\n // This transforms all promises regardless resolved or rejected\n var translateAll = function (translationIds) {\n var results = {}; // storing the actual results\n var promises = []; // promises to wait for\n // Wraps the promise a) being always resolved and b) storing the link id->value\n var translate = function (translationId) {\n var deferred = $q.defer();\n var regardless = function (value) {\n results[translationId] = value;\n deferred.resolve([translationId, value]);\n };\n // we don't care whether the promise was resolved or rejected; just store the values\n $translate(translationId, interpolateParams, interpolationId, defaultTranslationText, forceLanguage).then(regardless, regardless);\n return deferred.promise;\n };\n for (var i = 0, c = translationIds.length; i < c; i++) {\n promises.push(translate(translationIds[i]));\n }\n // wait for all (including storing to results)\n return $q.all(promises).then(function () {\n // return the results\n return results;\n });\n };\n return translateAll(translationId);\n }\n\n var deferred = $q.defer();\n\n // trim off any whitespace\n if (translationId) {\n translationId = trim.apply(translationId);\n }\n\n var promiseToWaitFor = (function () {\n var promise = $preferredLanguage ?\n langPromises[$preferredLanguage] :\n langPromises[uses];\n\n fallbackIndex = 0;\n\n if ($storageFactory && !promise) {\n // looks like there's no pending promise for $preferredLanguage or\n // $uses. Maybe there's one pending for a language that comes from\n // storage.\n var langKey = Storage.get($storageKey);\n promise = langPromises[langKey];\n\n if ($fallbackLanguage && $fallbackLanguage.length) {\n var index = indexOf($fallbackLanguage, langKey);\n // maybe the language from storage is also defined as fallback language\n // we increase the fallback language index to not search in that language\n // as fallback, since it's probably the first used language\n // in that case the index starts after the first element\n fallbackIndex = (index === 0) ? 1 : 0;\n\n // but we can make sure to ALWAYS fallback to preferred language at least\n if (indexOf($fallbackLanguage, $preferredLanguage) < 0) {\n $fallbackLanguage.push($preferredLanguage);\n }\n }\n }\n return promise;\n }());\n\n if (!promiseToWaitFor) {\n // no promise to wait for? okay. Then there's no loader registered\n // nor is a one pending for language that comes from storage.\n // We can just translate.\n determineTranslation(translationId, interpolateParams, interpolationId, defaultTranslationText, uses).then(deferred.resolve, deferred.reject);\n } else {\n var promiseResolved = function () {\n // $uses may have changed while waiting\n if (!forceLanguage) {\n uses = $uses;\n }\n determineTranslation(translationId, interpolateParams, interpolationId, defaultTranslationText, uses).then(deferred.resolve, deferred.reject);\n };\n promiseResolved.displayName = 'promiseResolved';\n\n promiseToWaitFor['finally'](promiseResolved, deferred.reject);\n }\n return deferred.promise;\n };\n\n /**\n * @name applyNotFoundIndicators\n * @private\n *\n * @description\n * Applies not fount indicators to given translation id, if needed.\n * This function gets only executed, if a translation id doesn't exist,\n * which is why a translation id is expected as argument.\n *\n * @param {string} translationId Translation id.\n * @returns {string} Same as given translation id but applied with not found\n * indicators.\n */\n var applyNotFoundIndicators = function (translationId) {\n // applying notFoundIndicators\n if ($notFoundIndicatorLeft) {\n translationId = [$notFoundIndicatorLeft, translationId].join(' ');\n }\n if ($notFoundIndicatorRight) {\n translationId = [translationId, $notFoundIndicatorRight].join(' ');\n }\n return translationId;\n };\n\n /**\n * @name useLanguage\n * @private\n *\n * @description\n * Makes actual use of a language by setting a given language key as used\n * language and informs registered interpolators to also use the given\n * key as locale.\n *\n * @param {key} Locale key.\n */\n var useLanguage = function (key) {\n $uses = key;\n\n // make sure to store new language key before triggering success event\n if ($storageFactory) {\n Storage.put($translate.storageKey(), $uses);\n }\n\n $rootScope.$emit('$translateChangeSuccess', {language: key});\n\n // inform default interpolator\n defaultInterpolator.setLocale($uses);\n\n var eachInterpolator = function (interpolator, id) {\n interpolatorHashMap[id].setLocale($uses);\n };\n eachInterpolator.displayName = 'eachInterpolatorLocaleSetter';\n\n // inform all others too!\n angular.forEach(interpolatorHashMap, eachInterpolator);\n $rootScope.$emit('$translateChangeEnd', {language: key});\n };\n\n /**\n * @name loadAsync\n * @private\n *\n * @description\n * Kicks of registered async loader using `$injector` and applies existing\n * loader options. When resolved, it updates translation tables accordingly\n * or rejects with given language key.\n *\n * @param {string} key Language key.\n * @return {Promise} A promise.\n */\n var loadAsync = function (key) {\n if (!key) {\n throw 'No language key specified for loading.';\n }\n\n var deferred = $q.defer();\n\n $rootScope.$emit('$translateLoadingStart', {language: key});\n pendingLoader = true;\n\n var cache = loaderCache;\n if (typeof(cache) === 'string') {\n // getting on-demand instance of loader\n cache = $injector.get(cache);\n }\n\n var loaderOptions = angular.extend({}, $loaderOptions, {\n key: key,\n $http: angular.extend({}, {\n cache: cache\n }, $loaderOptions.$http)\n });\n\n var onLoaderSuccess = function (data) {\n var translationTable = {};\n $rootScope.$emit('$translateLoadingSuccess', {language: key});\n\n if (angular.isArray(data)) {\n angular.forEach(data, function (table) {\n angular.extend(translationTable, flatObject(table));\n });\n } else {\n angular.extend(translationTable, flatObject(data));\n }\n pendingLoader = false;\n deferred.resolve({\n key: key,\n table: translationTable\n });\n $rootScope.$emit('$translateLoadingEnd', {language: key});\n };\n onLoaderSuccess.displayName = 'onLoaderSuccess';\n\n var onLoaderError = function (key) {\n $rootScope.$emit('$translateLoadingError', {language: key});\n deferred.reject(key);\n $rootScope.$emit('$translateLoadingEnd', {language: key});\n };\n onLoaderError.displayName = 'onLoaderError';\n\n $injector.get($loaderFactory)(loaderOptions)\n .then(onLoaderSuccess, onLoaderError);\n\n return deferred.promise;\n };\n\n if ($storageFactory) {\n Storage = $injector.get($storageFactory);\n\n if (!Storage.get || !Storage.put) {\n throw new Error('Couldn\\'t use storage \\'' + $storageFactory + '\\', missing get() or put() method!');\n }\n }\n\n // if we have additional interpolations that were added via\n // $translateProvider.addInterpolation(), we have to map'em\n if ($interpolatorFactories.length) {\n var eachInterpolationFactory = function (interpolatorFactory) {\n var interpolator = $injector.get(interpolatorFactory);\n // setting initial locale for each interpolation service\n interpolator.setLocale($preferredLanguage || $uses);\n // make'em recognizable through id\n interpolatorHashMap[interpolator.getInterpolationIdentifier()] = interpolator;\n };\n eachInterpolationFactory.displayName = 'interpolationFactoryAdder';\n\n angular.forEach($interpolatorFactories, eachInterpolationFactory);\n }\n\n /**\n * @name getTranslationTable\n * @private\n *\n * @description\n * Returns a promise that resolves to the translation table\n * or is rejected if an error occurred.\n *\n * @param langKey\n * @returns {Q.promise}\n */\n var getTranslationTable = function (langKey) {\n var deferred = $q.defer();\n if (Object.prototype.hasOwnProperty.call($translationTable, langKey)) {\n deferred.resolve($translationTable[langKey]);\n } else if (langPromises[langKey]) {\n var onResolve = function (data) {\n translations(data.key, data.table);\n deferred.resolve(data.table);\n };\n onResolve.displayName = 'translationTableResolver';\n langPromises[langKey].then(onResolve, deferred.reject);\n } else {\n deferred.reject();\n }\n return deferred.promise;\n };\n\n /**\n * @name getFallbackTranslation\n * @private\n *\n * @description\n * Returns a promise that will resolve to the translation\n * or be rejected if no translation was found for the language.\n * This function is currently only used for fallback language translation.\n *\n * @param langKey The language to translate to.\n * @param translationId\n * @param interpolateParams\n * @param Interpolator\n * @returns {Q.promise}\n */\n var getFallbackTranslation = function (langKey, translationId, interpolateParams, Interpolator) {\n var deferred = $q.defer();\n\n var onResolve = function (translationTable) {\n if (Object.prototype.hasOwnProperty.call(translationTable, translationId)) {\n Interpolator.setLocale(langKey);\n var translation = translationTable[translationId];\n if (translation.substr(0, 2) === '@:') {\n getFallbackTranslation(langKey, translation.substr(2), interpolateParams, Interpolator)\n .then(deferred.resolve, deferred.reject);\n } else {\n deferred.resolve(Interpolator.interpolate(translationTable[translationId], interpolateParams));\n }\n Interpolator.setLocale($uses);\n } else {\n deferred.reject();\n }\n };\n onResolve.displayName = 'fallbackTranslationResolver';\n\n getTranslationTable(langKey).then(onResolve, deferred.reject);\n\n return deferred.promise;\n };\n\n /**\n * @name getFallbackTranslationInstant\n * @private\n *\n * @description\n * Returns a translation\n * This function is currently only used for fallback language translation.\n *\n * @param langKey The language to translate to.\n * @param translationId\n * @param interpolateParams\n * @param Interpolator\n * @returns {string} translation\n */\n var getFallbackTranslationInstant = function (langKey, translationId, interpolateParams, Interpolator) {\n var result, translationTable = $translationTable[langKey];\n\n if (translationTable && Object.prototype.hasOwnProperty.call(translationTable, translationId)) {\n Interpolator.setLocale(langKey);\n result = Interpolator.interpolate(translationTable[translationId], interpolateParams);\n if (result.substr(0, 2) === '@:') {\n return getFallbackTranslationInstant(langKey, result.substr(2), interpolateParams, Interpolator);\n }\n Interpolator.setLocale($uses);\n }\n\n return result;\n };\n\n\n /**\n * @name translateByHandler\n * @private\n *\n * Translate by missing translation handler.\n *\n * @param translationId\n * @returns translation created by $missingTranslationHandler or translationId is $missingTranslationHandler is\n * absent\n */\n var translateByHandler = function (translationId, interpolateParams) {\n // If we have a handler factory - we might also call it here to determine if it provides\n // a default text for a translationid that can't be found anywhere in our tables\n if ($missingTranslationHandlerFactory) {\n var resultString = $injector.get($missingTranslationHandlerFactory)(translationId, $uses, interpolateParams);\n if (resultString !== undefined) {\n return resultString;\n } else {\n return translationId;\n }\n } else {\n return translationId;\n }\n };\n\n /**\n * @name resolveForFallbackLanguage\n * @private\n *\n * Recursive helper function for fallbackTranslation that will sequentially look\n * for a translation in the fallbackLanguages starting with fallbackLanguageIndex.\n *\n * @param fallbackLanguageIndex\n * @param translationId\n * @param interpolateParams\n * @param Interpolator\n * @returns {Q.promise} Promise that will resolve to the translation.\n */\n var resolveForFallbackLanguage = function (fallbackLanguageIndex, translationId, interpolateParams, Interpolator, defaultTranslationText) {\n var deferred = $q.defer();\n\n if (fallbackLanguageIndex < $fallbackLanguage.length) {\n var langKey = $fallbackLanguage[fallbackLanguageIndex];\n getFallbackTranslation(langKey, translationId, interpolateParams, Interpolator).then(\n deferred.resolve,\n function () {\n // Look in the next fallback language for a translation.\n // It delays the resolving by passing another promise to resolve.\n resolveForFallbackLanguage(fallbackLanguageIndex + 1, translationId, interpolateParams, Interpolator, defaultTranslationText).then(deferred.resolve);\n }\n );\n } else {\n // No translation found in any fallback language\n // if a default translation text is set in the directive, then return this as a result\n if (defaultTranslationText) {\n deferred.resolve(defaultTranslationText);\n } else {\n // if no default translation is set and an error handler is defined, send it to the handler\n // and then return the result\n deferred.resolve(translateByHandler(translationId, interpolateParams));\n }\n }\n return deferred.promise;\n };\n\n /**\n * @name resolveForFallbackLanguageInstant\n * @private\n *\n * Recursive helper function for fallbackTranslation that will sequentially look\n * for a translation in the fallbackLanguages starting with fallbackLanguageIndex.\n *\n * @param fallbackLanguageIndex\n * @param translationId\n * @param interpolateParams\n * @param Interpolator\n * @returns {string} translation\n */\n var resolveForFallbackLanguageInstant = function (fallbackLanguageIndex, translationId, interpolateParams, Interpolator) {\n var result;\n\n if (fallbackLanguageIndex < $fallbackLanguage.length) {\n var langKey = $fallbackLanguage[fallbackLanguageIndex];\n result = getFallbackTranslationInstant(langKey, translationId, interpolateParams, Interpolator);\n if (!result) {\n result = resolveForFallbackLanguageInstant(fallbackLanguageIndex + 1, translationId, interpolateParams, Interpolator);\n }\n }\n return result;\n };\n\n /**\n * Translates with the usage of the fallback languages.\n *\n * @param translationId\n * @param interpolateParams\n * @param Interpolator\n * @returns {Q.promise} Promise, that resolves to the translation.\n */\n var fallbackTranslation = function (translationId, interpolateParams, Interpolator, defaultTranslationText) {\n // Start with the fallbackLanguage with index 0\n return resolveForFallbackLanguage((startFallbackIteration>0 ? startFallbackIteration : fallbackIndex), translationId, interpolateParams, Interpolator, defaultTranslationText);\n };\n\n /**\n * Translates with the usage of the fallback languages.\n *\n * @param translationId\n * @param interpolateParams\n * @param Interpolator\n * @returns {String} translation\n */\n var fallbackTranslationInstant = function (translationId, interpolateParams, Interpolator) {\n // Start with the fallbackLanguage with index 0\n return resolveForFallbackLanguageInstant((startFallbackIteration>0 ? startFallbackIteration : fallbackIndex), translationId, interpolateParams, Interpolator);\n };\n\n var determineTranslation = function (translationId, interpolateParams, interpolationId, defaultTranslationText, uses) {\n\n var deferred = $q.defer();\n\n var table = uses ? $translationTable[uses] : $translationTable,\n Interpolator = (interpolationId) ? interpolatorHashMap[interpolationId] : defaultInterpolator;\n\n // if the translation id exists, we can just interpolate it\n if (table && Object.prototype.hasOwnProperty.call(table, translationId)) {\n var translation = table[translationId];\n\n // If using link, rerun $translate with linked translationId and return it\n if (translation.substr(0, 2) === '@:') {\n\n $translate(translation.substr(2), interpolateParams, interpolationId, defaultTranslationText, uses)\n .then(deferred.resolve, deferred.reject);\n } else {\n deferred.resolve(Interpolator.interpolate(translation, interpolateParams));\n }\n } else {\n var missingTranslationHandlerTranslation;\n // for logging purposes only (as in $translateMissingTranslationHandlerLog), value is not returned to promise\n if ($missingTranslationHandlerFactory && !pendingLoader) {\n missingTranslationHandlerTranslation = translateByHandler(translationId, interpolateParams);\n }\n\n // since we couldn't translate the inital requested translation id,\n // we try it now with one or more fallback languages, if fallback language(s) is\n // configured.\n if (uses && $fallbackLanguage && $fallbackLanguage.length) {\n fallbackTranslation(translationId, interpolateParams, Interpolator, defaultTranslationText)\n .then(function (translation) {\n deferred.resolve(translation);\n }, function (_translationId) {\n deferred.reject(applyNotFoundIndicators(_translationId));\n });\n } else if ($missingTranslationHandlerFactory && !pendingLoader && missingTranslationHandlerTranslation) {\n // looks like the requested translation id doesn't exists.\n // Now, if there is a registered handler for missing translations and no\n // asyncLoader is pending, we execute the handler\n if (defaultTranslationText) {\n deferred.resolve(defaultTranslationText);\n } else {\n deferred.resolve(missingTranslationHandlerTranslation);\n }\n } else {\n if (defaultTranslationText) {\n deferred.resolve(defaultTranslationText);\n } else {\n deferred.reject(applyNotFoundIndicators(translationId));\n }\n }\n }\n return deferred.promise;\n };\n\n var determineTranslationInstant = function (translationId, interpolateParams, interpolationId, uses) {\n\n var result, table = uses ? $translationTable[uses] : $translationTable,\n Interpolator = defaultInterpolator;\n\n // if the interpolation id exists use custom interpolator\n if (interpolatorHashMap && Object.prototype.hasOwnProperty.call(interpolatorHashMap, interpolationId)) {\n Interpolator = interpolatorHashMap[interpolationId];\n }\n\n // if the translation id exists, we can just interpolate it\n if (table && Object.prototype.hasOwnProperty.call(table, translationId)) {\n var translation = table[translationId];\n\n // If using link, rerun $translate with linked translationId and return it\n if (translation.substr(0, 2) === '@:') {\n result = determineTranslationInstant(translation.substr(2), interpolateParams, interpolationId, uses);\n } else {\n result = Interpolator.interpolate(translation, interpolateParams);\n }\n } else {\n var missingTranslationHandlerTranslation;\n // for logging purposes only (as in $translateMissingTranslationHandlerLog), value is not returned to promise\n if ($missingTranslationHandlerFactory && !pendingLoader) {\n missingTranslationHandlerTranslation = translateByHandler(translationId, interpolateParams);\n }\n\n // since we couldn't translate the inital requested translation id,\n // we try it now with one or more fallback languages, if fallback language(s) is\n // configured.\n if (uses && $fallbackLanguage && $fallbackLanguage.length) {\n fallbackIndex = 0;\n result = fallbackTranslationInstant(translationId, interpolateParams, Interpolator);\n } else if ($missingTranslationHandlerFactory && !pendingLoader && missingTranslationHandlerTranslation) {\n // looks like the requested translation id doesn't exists.\n // Now, if there is a registered handler for missing translations and no\n // asyncLoader is pending, we execute the handler\n result = missingTranslationHandlerTranslation;\n } else {\n result = applyNotFoundIndicators(translationId);\n }\n }\n\n return result;\n };\n\n var clearNextLangAndPromise = function(key) {\n if ($nextLang === key) {\n $nextLang = undefined;\n }\n langPromises[key] = undefined;\n };\n\n /**\n * @ngdoc function\n * @name pascalprecht.translate.$translate#preferredLanguage\n * @methodOf pascalprecht.translate.$translate\n *\n * @description\n * Returns the language key for the preferred language.\n *\n * @param {string} langKey language String or Array to be used as preferredLanguage (changing at runtime)\n *\n * @return {string} preferred language key\n */\n $translate.preferredLanguage = function (langKey) {\n if(langKey) {\n setupPreferredLanguage(langKey);\n }\n return $preferredLanguage;\n };\n\n /**\n * @ngdoc function\n * @name pascalprecht.translate.$translate#cloakClassName\n * @methodOf pascalprecht.translate.$translate\n *\n * @description\n * Returns the configured class name for `translate-cloak` directive.\n *\n * @return {string} cloakClassName\n */\n $translate.cloakClassName = function () {\n return $cloakClassName;\n };\n\n /**\n * @ngdoc function\n * @name pascalprecht.translate.$translate#nestedObjectDelimeter\n * @methodOf pascalprecht.translate.$translate\n *\n * @description\n * Returns the configured delimiter for nested namespaces.\n *\n * @return {string} nestedObjectDelimeter\n */\n $translate.nestedObjectDelimeter = function () {\n return $nestedObjectDelimeter;\n };\n\n /**\n * @ngdoc function\n * @name pascalprecht.translate.$translate#fallbackLanguage\n * @methodOf pascalprecht.translate.$translate\n *\n * @description\n * Returns the language key for the fallback languages or sets a new fallback stack.\n *\n * @param {string=} langKey language String or Array of fallback languages to be used (to change stack at runtime)\n *\n * @return {string||array} fallback language key\n */\n $translate.fallbackLanguage = function (langKey) {\n if (langKey !== undefined && langKey !== null) {\n fallbackStack(langKey);\n\n // as we might have an async loader initiated and a new translation language might have been defined\n // we need to add the promise to the stack also. So - iterate.\n if ($loaderFactory) {\n if ($fallbackLanguage && $fallbackLanguage.length) {\n for (var i = 0, len = $fallbackLanguage.length; i < len; i++) {\n if (!langPromises[$fallbackLanguage[i]]) {\n langPromises[$fallbackLanguage[i]] = loadAsync($fallbackLanguage[i]);\n }\n }\n }\n }\n $translate.use($translate.use());\n }\n if ($fallbackWasString) {\n return $fallbackLanguage[0];\n } else {\n return $fallbackLanguage;\n }\n\n };\n\n /**\n * @ngdoc function\n * @name pascalprecht.translate.$translate#useFallbackLanguage\n * @methodOf pascalprecht.translate.$translate\n *\n * @description\n * Sets the first key of the fallback language stack to be used for translation.\n * Therefore all languages in the fallback array BEFORE this key will be skipped!\n *\n * @param {string=} langKey Contains the langKey the iteration shall start with. Set to false if you want to\n * get back to the whole stack\n */\n $translate.useFallbackLanguage = function (langKey) {\n if (langKey !== undefined && langKey !== null) {\n if (!langKey) {\n startFallbackIteration = 0;\n } else {\n var langKeyPosition = indexOf($fallbackLanguage, langKey);\n if (langKeyPosition > -1) {\n startFallbackIteration = langKeyPosition;\n }\n }\n\n }\n\n };\n\n /**\n * @ngdoc function\n * @name pascalprecht.translate.$translate#proposedLanguage\n * @methodOf pascalprecht.translate.$translate\n *\n * @description\n * Returns the language key of language that is currently loaded asynchronously.\n *\n * @return {string} language key\n */\n $translate.proposedLanguage = function () {\n return $nextLang;\n };\n\n /**\n * @ngdoc function\n * @name pascalprecht.translate.$translate#storage\n * @methodOf pascalprecht.translate.$translate\n *\n * @description\n * Returns registered storage.\n *\n * @return {object} Storage\n */\n $translate.storage = function () {\n return Storage;\n };\n\n /**\n * @ngdoc function\n * @name pascalprecht.translate.$translate#negotiateLocale\n * @methodOf pascalprecht.translate.$translate\n *\n * @description\n * Returns a language key based on available languages and language aliases. If a\n * language key cannot be resolved, returns undefined.\n *\n * If no or a falsy key is given, returns undefined.\n *\n * @param {string} [key] Language key\n * @return {string|undefined} Language key or undefined if no language key is found.\n */\n $translate.negotiateLocale = negotiateLocale;\n\n /**\n * @ngdoc function\n * @name pascalprecht.translate.$translate#use\n * @methodOf pascalprecht.translate.$translate\n *\n * @description\n * Tells angular-translate which language to use by given language key. This method is\n * used to change language at runtime. It also takes care of storing the language\n * key in a configured store to let your app remember the choosed language.\n *\n * When trying to 'use' a language which isn't available it tries to load it\n * asynchronously with registered loaders.\n *\n * Returns promise object with loaded language file data or string of the currently used language.\n *\n * If no or a falsy key is given it returns the currently used language key.\n * The returned string will be ```undefined``` if setting up $translate hasn't finished.\n * @example\n * $translate.use(\"en_US\").then(function(data){\n * $scope.text = $translate(\"HELLO\");\n * });\n *\n * @param {string} [key] Language key\n * @return {object|string} Promise with loaded language data or the language key if a falsy param was given.\n */\n $translate.use = function (key) {\n if (!key) {\n return $uses;\n }\n\n var deferred = $q.defer();\n\n $rootScope.$emit('$translateChangeStart', {language: key});\n\n // Try to get the aliased language key\n var aliasedKey = negotiateLocale(key);\n if (aliasedKey) {\n key = aliasedKey;\n }\n\n // if there isn't a translation table for the language we've requested,\n // we load it asynchronously\n if (($forceAsyncReloadEnabled || !$translationTable[key]) && $loaderFactory && !langPromises[key]) {\n $nextLang = key;\n langPromises[key] = loadAsync(key).then(function (translation) {\n translations(translation.key, translation.table);\n deferred.resolve(translation.key);\n if ($nextLang === key) {\n useLanguage(translation.key);\n }\n return translation;\n }, function (key) {\n $rootScope.$emit('$translateChangeError', {language: key});\n deferred.reject(key);\n $rootScope.$emit('$translateChangeEnd', {language: key});\n return $q.reject(key);\n });\n langPromises[key]['finally'](function () {\n clearNextLangAndPromise(key);\n });\n } else if ($nextLang === key && langPromises[key]) {\n // we are already loading this asynchronously\n // resolve our new deferred when the old langPromise is resolved\n langPromises[key].then(function (translation) {\n deferred.resolve(translation.key);\n return translation;\n }, function (key) {\n deferred.reject(key);\n return $q.reject(key);\n });\n } else {\n deferred.resolve(key);\n useLanguage(key);\n }\n\n return deferred.promise;\n };\n\n /**\n * @ngdoc function\n * @name pascalprecht.translate.$translate#storageKey\n * @methodOf pascalprecht.translate.$translate\n *\n * @description\n * Returns the key for the storage.\n *\n * @return {string} storage key\n */\n $translate.storageKey = function () {\n return storageKey();\n };\n\n /**\n * @ngdoc function\n * @name pascalprecht.translate.$translate#isPostCompilingEnabled\n * @methodOf pascalprecht.translate.$translate\n *\n * @description\n * Returns whether post compiling is enabled or not\n *\n * @return {bool} storage key\n */\n $translate.isPostCompilingEnabled = function () {\n return $postCompilingEnabled;\n };\n\n /**\n * @ngdoc function\n * @name pascalprecht.translate.$translate#isForceAsyncReloadEnabled\n * @methodOf pascalprecht.translate.$translate\n *\n * @description\n * Returns whether force async reload is enabled or not\n *\n * @return {boolean} forceAsyncReload value\n */\n $translate.isForceAsyncReloadEnabled = function () {\n return $forceAsyncReloadEnabled;\n };\n\n /**\n * @ngdoc function\n * @name pascalprecht.translate.$translate#refresh\n * @methodOf pascalprecht.translate.$translate\n *\n * @description\n * Refreshes a translation table pointed by the given langKey. If langKey is not specified,\n * the module will drop all existent translation tables and load new version of those which\n * are currently in use.\n *\n * Refresh means that the module will drop target translation table and try to load it again.\n *\n * In case there are no loaders registered the refresh() method will throw an Error.\n *\n * If the module is able to refresh translation tables refresh() method will broadcast\n * $translateRefreshStart and $translateRefreshEnd events.\n *\n * @example\n * // this will drop all currently existent translation tables and reload those which are\n * // currently in use\n * $translate.refresh();\n * // this will refresh a translation table for the en_US language\n * $translate.refresh('en_US');\n *\n * @param {string} langKey A language key of the table, which has to be refreshed\n *\n * @return {promise} Promise, which will be resolved in case a translation tables refreshing\n * process is finished successfully, and reject if not.\n */\n $translate.refresh = function (langKey) {\n if (!$loaderFactory) {\n throw new Error('Couldn\\'t refresh translation table, no loader registered!');\n }\n\n var deferred = $q.defer();\n\n function resolve() {\n deferred.resolve();\n $rootScope.$emit('$translateRefreshEnd', {language: langKey});\n }\n\n function reject() {\n deferred.reject();\n $rootScope.$emit('$translateRefreshEnd', {language: langKey});\n }\n\n $rootScope.$emit('$translateRefreshStart', {language: langKey});\n\n if (!langKey) {\n // if there's no language key specified we refresh ALL THE THINGS!\n var tables = [], loadingKeys = {};\n\n // reload registered fallback languages\n if ($fallbackLanguage && $fallbackLanguage.length) {\n for (var i = 0, len = $fallbackLanguage.length; i < len; i++) {\n tables.push(loadAsync($fallbackLanguage[i]));\n loadingKeys[$fallbackLanguage[i]] = true;\n }\n }\n\n // reload currently used language\n if ($uses && !loadingKeys[$uses]) {\n tables.push(loadAsync($uses));\n }\n\n var allTranslationsLoaded = function (tableData) {\n $translationTable = {};\n angular.forEach(tableData, function (data) {\n translations(data.key, data.table);\n });\n if ($uses) {\n useLanguage($uses);\n }\n resolve();\n };\n allTranslationsLoaded.displayName = 'refreshPostProcessor';\n\n $q.all(tables).then(allTranslationsLoaded, reject);\n\n } else if ($translationTable[langKey]) {\n\n var oneTranslationsLoaded = function (data) {\n translations(data.key, data.table);\n if (langKey === $uses) {\n useLanguage($uses);\n }\n resolve();\n };\n oneTranslationsLoaded.displayName = 'refreshPostProcessor';\n\n loadAsync(langKey).then(oneTranslationsLoaded, reject);\n\n } else {\n reject();\n }\n return deferred.promise;\n };\n\n /**\n * @ngdoc function\n * @name pascalprecht.translate.$translate#instant\n * @methodOf pascalprecht.translate.$translate\n *\n * @description\n * Returns a translation instantly from the internal state of loaded translation. All rules\n * regarding the current language, the preferred language of even fallback languages will be\n * used except any promise handling. If a language was not found, an asynchronous loading\n * will be invoked in the background.\n *\n * @param {string|array} translationId A token which represents a translation id\n * This can be optionally an array of translation ids which\n * results that the function's promise returns an object where\n * each key is the translation id and the value the translation.\n * @param {object} interpolateParams Params\n * @param {string} interpolationId The id of the interpolation to use\n * @param {string} forceLanguage A language to be used instead of the current language\n *\n * @return {string|object} translation\n */\n $translate.instant = function (translationId, interpolateParams, interpolationId, forceLanguage) {\n\n // we don't want to re-negotiate $uses\n var uses = (forceLanguage && forceLanguage !== $uses) ? // we don't want to re-negotiate $uses\n (negotiateLocale(forceLanguage) || forceLanguage) : $uses;\n\n // Detect undefined and null values to shorten the execution and prevent exceptions\n if (translationId === null || angular.isUndefined(translationId)) {\n return translationId;\n }\n\n // Duck detection: If the first argument is an array, a bunch of translations was requested.\n // The result is an object.\n if (angular.isArray(translationId)) {\n var results = {};\n for (var i = 0, c = translationId.length; i < c; i++) {\n results[translationId[i]] = $translate.instant(translationId[i], interpolateParams, interpolationId, forceLanguage);\n }\n return results;\n }\n\n // We discarded unacceptable values. So we just need to verify if translationId is empty String\n if (angular.isString(translationId) && translationId.length < 1) {\n return translationId;\n }\n\n // trim off any whitespace\n if (translationId) {\n translationId = trim.apply(translationId);\n }\n\n var result, possibleLangKeys = [];\n if ($preferredLanguage) {\n possibleLangKeys.push($preferredLanguage);\n }\n if (uses) {\n possibleLangKeys.push(uses);\n }\n if ($fallbackLanguage && $fallbackLanguage.length) {\n possibleLangKeys = possibleLangKeys.concat($fallbackLanguage);\n }\n for (var j = 0, d = possibleLangKeys.length; j < d; j++) {\n var possibleLangKey = possibleLangKeys[j];\n if ($translationTable[possibleLangKey]) {\n if (typeof $translationTable[possibleLangKey][translationId] !== 'undefined') {\n result = determineTranslationInstant(translationId, interpolateParams, interpolationId, uses);\n }\n }\n if (typeof result !== 'undefined') {\n break;\n }\n }\n\n if (!result && result !== '') {\n if ($notFoundIndicatorLeft || $notFoundIndicatorRight) {\n result = applyNotFoundIndicators(translationId);\n } else {\n // Return translation of default interpolator if not found anything.\n result = defaultInterpolator.interpolate(translationId, interpolateParams);\n if ($missingTranslationHandlerFactory && !pendingLoader) {\n result = translateByHandler(translationId, interpolateParams);\n }\n }\n }\n\n return result;\n };\n\n /**\n * @ngdoc function\n * @name pascalprecht.translate.$translate#versionInfo\n * @methodOf pascalprecht.translate.$translate\n *\n * @description\n * Returns the current version information for the angular-translate library\n *\n * @return {string} angular-translate version\n */\n $translate.versionInfo = function () {\n return version;\n };\n\n /**\n * @ngdoc function\n * @name pascalprecht.translate.$translate#loaderCache\n * @methodOf pascalprecht.translate.$translate\n *\n * @description\n * Returns the defined loaderCache.\n *\n * @return {boolean|string|object} current value of loaderCache\n */\n $translate.loaderCache = function () {\n return loaderCache;\n };\n\n // internal purpose only\n $translate.directivePriority = function () {\n return directivePriority;\n };\n\n // internal purpose only\n $translate.statefulFilter = function () {\n return statefulFilter;\n };\n\n /**\n * @ngdoc function\n * @name pascalprecht.translate.$translate#isReady\n * @methodOf pascalprecht.translate.$translate\n *\n * @description\n * Returns whether the service is \"ready\" to translate (i.e. loading 1st language).\n *\n * See also {@link pascalprecht.translate.$translate#methods_onReady onReady()}.\n *\n * @return {boolean} current value of ready\n */\n $translate.isReady = function () {\n return $isReady;\n };\n\n var $onReadyDeferred = $q.defer();\n $onReadyDeferred.promise.then(function () {\n $isReady = true;\n });\n\n /**\n * @ngdoc function\n * @name pascalprecht.translate.$translate#onReady\n * @methodOf pascalprecht.translate.$translate\n *\n * @description\n * Returns whether the service is \"ready\" to translate (i.e. loading 1st language).\n *\n * See also {@link pascalprecht.translate.$translate#methods_isReady isReady()}.\n *\n * @param {Function=} fn Function to invoke when service is ready\n * @return {object} Promise resolved when service is ready\n */\n $translate.onReady = function (fn) {\n var deferred = $q.defer();\n if (angular.isFunction(fn)) {\n deferred.promise.then(fn);\n }\n if ($isReady) {\n deferred.resolve();\n } else {\n $onReadyDeferred.promise.then(deferred.resolve);\n }\n return deferred.promise;\n };\n\n // Whenever $translateReady is being fired, this will ensure the state of $isReady\n var globalOnReadyListener = $rootScope.$on('$translateReady', function () {\n $onReadyDeferred.resolve();\n globalOnReadyListener(); // one time only\n globalOnReadyListener = null;\n });\n var globalOnChangeListener = $rootScope.$on('$translateChangeEnd', function () {\n $onReadyDeferred.resolve();\n globalOnChangeListener(); // one time only\n globalOnChangeListener = null;\n });\n\n if ($loaderFactory) {\n\n // If at least one async loader is defined and there are no\n // (default) translations available we should try to load them.\n if (angular.equals($translationTable, {})) {\n if ($translate.use()) {\n $translate.use($translate.use());\n }\n }\n\n // Also, if there are any fallback language registered, we start\n // loading them asynchronously as soon as we can.\n if ($fallbackLanguage && $fallbackLanguage.length) {\n var processAsyncResult = function (translation) {\n translations(translation.key, translation.table);\n $rootScope.$emit('$translateChangeEnd', { language: translation.key });\n return translation;\n };\n for (var i = 0, len = $fallbackLanguage.length; i < len; i++) {\n var fallbackLanguageId = $fallbackLanguage[i];\n if ($forceAsyncReloadEnabled || !$translationTable[fallbackLanguageId]) {\n langPromises[fallbackLanguageId] = loadAsync(fallbackLanguageId).then(processAsyncResult);\n }\n }\n }\n } else {\n $rootScope.$emit('$translateReady', { language: $translate.use() });\n }\n\n return $translate;\n }\n ];\n}\n$translate.$inject = ['$STORAGE_KEY', '$windowProvider', '$translateSanitizationProvider', 'pascalprechtTranslateOverrider'];\n\n$translate.displayName = 'displayName';\n\n/**\n * @ngdoc object\n * @name pascalprecht.translate.$translateDefaultInterpolation\n * @requires $interpolate\n *\n * @description\n * Uses angular's `$interpolate` services to interpolate strings against some values.\n *\n * Be aware to configure a proper sanitization strategy.\n *\n * See also:\n * * {@link pascalprecht.translate.$translateSanitization}\n *\n * @return {object} $translateDefaultInterpolation Interpolator service\n */\nangular.module('pascalprecht.translate').factory('$translateDefaultInterpolation', $translateDefaultInterpolation);\n\nfunction $translateDefaultInterpolation ($interpolate, $translateSanitization) {\n\n 'use strict';\n\n var $translateInterpolator = {},\n $locale,\n $identifier = 'default';\n\n /**\n * @ngdoc function\n * @name pascalprecht.translate.$translateDefaultInterpolation#setLocale\n * @methodOf pascalprecht.translate.$translateDefaultInterpolation\n *\n * @description\n * Sets current locale (this is currently not use in this interpolation).\n *\n * @param {string} locale Language key or locale.\n */\n $translateInterpolator.setLocale = function (locale) {\n $locale = locale;\n };\n\n /**\n * @ngdoc function\n * @name pascalprecht.translate.$translateDefaultInterpolation#getInterpolationIdentifier\n * @methodOf pascalprecht.translate.$translateDefaultInterpolation\n *\n * @description\n * Returns an identifier for this interpolation service.\n *\n * @returns {string} $identifier\n */\n $translateInterpolator.getInterpolationIdentifier = function () {\n return $identifier;\n };\n\n /**\n * @deprecated will be removed in 3.0\n * @see {@link pascalprecht.translate.$translateSanitization}\n */\n $translateInterpolator.useSanitizeValueStrategy = function (value) {\n $translateSanitization.useStrategy(value);\n return this;\n };\n\n /**\n * @ngdoc function\n * @name pascalprecht.translate.$translateDefaultInterpolation#interpolate\n * @methodOf pascalprecht.translate.$translateDefaultInterpolation\n *\n * @description\n * Interpolates given string agains given interpolate params using angulars\n * `$interpolate` service.\n *\n * @returns {string} interpolated string.\n */\n $translateInterpolator.interpolate = function (string, interpolationParams) {\n interpolationParams = interpolationParams || {};\n interpolationParams = $translateSanitization.sanitize(interpolationParams, 'params');\n\n var interpolatedText = $interpolate(string)(interpolationParams);\n interpolatedText = $translateSanitization.sanitize(interpolatedText, 'text');\n\n return interpolatedText;\n };\n\n return $translateInterpolator;\n}\n$translateDefaultInterpolation.$inject = ['$interpolate', '$translateSanitization'];\n\n$translateDefaultInterpolation.displayName = '$translateDefaultInterpolation';\n\nangular.module('pascalprecht.translate').constant('$STORAGE_KEY', 'NG_TRANSLATE_LANG_KEY');\n\nangular.module('pascalprecht.translate')\n/**\n * @ngdoc directive\n * @name pascalprecht.translate.directive:translate\n * @requires $compile\n * @requires $filter\n * @requires $interpolate\n * @restrict AE\n *\n * @description\n * Translates given translation id either through attribute or DOM content.\n * Internally it uses `translate` filter to translate translation id. It possible to\n * pass an optional `translate-values` object literal as string into translation id.\n *\n * @param {string=} translate Translation id which could be either string or interpolated string.\n * @param {string=} translate-values Values to pass into translation id. Can be passed as object literal string or interpolated object.\n * @param {string=} translate-attr-ATTR translate Translation id and put it into ATTR attribute.\n * @param {string=} translate-default will be used unless translation was successful\n * @param {boolean=} translate-compile (default true if present) defines locally activation of {@link pascalprecht.translate.$translateProvider#methods_usePostCompiling}\n *\n * @example\n \n \n
\n\n
\n        
TRANSLATION_ID
\n
\n        
\n        
{{translationId}}
\n
\n        
WITH_VALUES
\n
\n        
WITH_VALUES
\n
\n\n      
\n
\n \n angular.module('ngView', ['pascalprecht.translate'])\n\n .config(function ($translateProvider) {\n\n $translateProvider.translations('en',{\n 'TRANSLATION_ID': 'Hello there!',\n 'WITH_VALUES': 'The following value is dynamic: {{value}}'\n }).preferredLanguage('en');\n\n });\n\n angular.module('ngView').controller('TranslateCtrl', function ($scope) {\n $scope.translationId = 'TRANSLATION_ID';\n\n $scope.values = {\n value: 78\n };\n });\n \n \n it('should translate', function () {\n inject(function ($rootScope, $compile) {\n $rootScope.translationId = 'TRANSLATION_ID';\n\n element = $compile('

')($rootScope);\n $rootScope.$digest();\n expect(element.text()).toBe('Hello there!');\n\n element = $compile('

')($rootScope);\n $rootScope.$digest();\n expect(element.text()).toBe('Hello there!');\n\n element = $compile('

TRANSLATION_ID

')($rootScope);\n $rootScope.$digest();\n expect(element.text()).toBe('Hello there!');\n\n element = $compile('

{{translationId}}

')($rootScope);\n $rootScope.$digest();\n expect(element.text()).toBe('Hello there!');\n\n element = $compile('

')($rootScope);\n $rootScope.$digest();\n expect(element.attr('title')).toBe('Hello there!');\n });\n });\n
\n
\n */\n.directive('translate', translateDirective);\nfunction translateDirective($translate, $q, $interpolate, $compile, $parse, $rootScope) {\n\n 'use strict';\n\n /**\n * @name trim\n * @private\n *\n * @description\n * trim polyfill\n *\n * @returns {string} The string stripped of whitespace from both ends\n */\n var trim = function() {\n return this.toString().replace(/^\\s+|\\s+$/g, '');\n };\n\n return {\n restrict: 'AE',\n scope: true,\n priority: $translate.directivePriority(),\n compile: function (tElement, tAttr) {\n\n var translateValuesExist = (tAttr.translateValues) ?\n tAttr.translateValues : undefined;\n\n var translateInterpolation = (tAttr.translateInterpolation) ?\n tAttr.translateInterpolation : undefined;\n\n var translateValueExist = tElement[0].outerHTML.match(/translate-value-+/i);\n\n var interpolateRegExp = '^(.*)(' + $interpolate.startSymbol() + '.*' + $interpolate.endSymbol() + ')(.*)',\n watcherRegExp = '^(.*)' + $interpolate.startSymbol() + '(.*)' + $interpolate.endSymbol() + '(.*)';\n\n return function linkFn(scope, iElement, iAttr) {\n\n scope.interpolateParams = {};\n scope.preText = '';\n scope.postText = '';\n scope.translateNamespace = getTranslateNamespace(scope);\n var translationIds = {};\n\n var initInterpolationParams = function (interpolateParams, iAttr, tAttr) {\n // initial setup\n if (iAttr.translateValues) {\n angular.extend(interpolateParams, $parse(iAttr.translateValues)(scope.$parent));\n }\n // initially fetch all attributes if existing and fill the params\n if (translateValueExist) {\n for (var attr in tAttr) {\n if (Object.prototype.hasOwnProperty.call(iAttr, attr) && attr.substr(0, 14) === 'translateValue' && attr !== 'translateValues') {\n var attributeName = angular.lowercase(attr.substr(14, 1)) + attr.substr(15);\n interpolateParams[attributeName] = tAttr[attr];\n }\n }\n }\n };\n\n // Ensures any change of the attribute \"translate\" containing the id will\n // be re-stored to the scope's \"translationId\".\n // If the attribute has no content, the element's text value (white spaces trimmed off) will be used.\n var observeElementTranslation = function (translationId) {\n\n // Remove any old watcher\n if (angular.isFunction(observeElementTranslation._unwatchOld)) {\n observeElementTranslation._unwatchOld();\n observeElementTranslation._unwatchOld = undefined;\n }\n\n if (angular.equals(translationId , '') || !angular.isDefined(translationId)) {\n var iElementText = trim.apply(iElement.text());\n\n // Resolve translation id by inner html if required\n var interpolateMatches = iElementText.match(interpolateRegExp);\n // Interpolate translation id if required\n if (angular.isArray(interpolateMatches)) {\n scope.preText = interpolateMatches[1];\n scope.postText = interpolateMatches[3];\n translationIds.translate = $interpolate(interpolateMatches[2])(scope.$parent);\n var watcherMatches = iElementText.match(watcherRegExp);\n if (angular.isArray(watcherMatches) && watcherMatches[2] && watcherMatches[2].length) {\n observeElementTranslation._unwatchOld = scope.$watch(watcherMatches[2], function (newValue) {\n translationIds.translate = newValue;\n updateTranslations();\n });\n }\n } else {\n // do not assigne the translation id if it is empty.\n translationIds.translate = !iElementText ? undefined : iElementText;\n }\n } else {\n translationIds.translate = translationId;\n }\n updateTranslations();\n };\n\n var observeAttributeTranslation = function (translateAttr) {\n iAttr.$observe(translateAttr, function (translationId) {\n translationIds[translateAttr] = translationId;\n updateTranslations();\n });\n };\n\n // initial setup with values\n initInterpolationParams(scope.interpolateParams, iAttr, tAttr);\n\n var firstAttributeChangedEvent = true;\n iAttr.$observe('translate', function (translationId) {\n if (typeof translationId === 'undefined') {\n // case of element \"xyz\"\n observeElementTranslation('');\n } else {\n // case of regular attribute\n if (translationId !== '' || !firstAttributeChangedEvent) {\n translationIds.translate = translationId;\n updateTranslations();\n }\n }\n firstAttributeChangedEvent = false;\n });\n\n for (var translateAttr in iAttr) {\n if (iAttr.hasOwnProperty(translateAttr) && translateAttr.substr(0, 13) === 'translateAttr') {\n observeAttributeTranslation(translateAttr);\n }\n }\n\n iAttr.$observe('translateDefault', function (value) {\n scope.defaultText = value;\n updateTranslations();\n });\n\n if (translateValuesExist) {\n iAttr.$observe('translateValues', function (interpolateParams) {\n if (interpolateParams) {\n scope.$parent.$watch(function () {\n angular.extend(scope.interpolateParams, $parse(interpolateParams)(scope.$parent));\n });\n }\n });\n }\n\n if (translateValueExist) {\n var observeValueAttribute = function (attrName) {\n iAttr.$observe(attrName, function (value) {\n var attributeName = angular.lowercase(attrName.substr(14, 1)) + attrName.substr(15);\n scope.interpolateParams[attributeName] = value;\n });\n };\n for (var attr in iAttr) {\n if (Object.prototype.hasOwnProperty.call(iAttr, attr) && attr.substr(0, 14) === 'translateValue' && attr !== 'translateValues') {\n observeValueAttribute(attr);\n }\n }\n }\n\n // Master update function\n var updateTranslations = function () {\n for (var key in translationIds) {\n\n if (translationIds.hasOwnProperty(key) && translationIds[key] !== undefined) {\n updateTranslation(key, translationIds[key], scope, scope.interpolateParams, scope.defaultText, scope.translateNamespace);\n }\n }\n };\n\n // Put translation processing function outside loop\n var updateTranslation = function(translateAttr, translationId, scope, interpolateParams, defaultTranslationText, translateNamespace) {\n if (translationId) {\n // if translation id starts with '.' and translateNamespace given, prepend namespace\n if (translateNamespace && translationId.charAt(0) === '.') {\n translationId = translateNamespace + translationId;\n }\n\n $translate(translationId, interpolateParams, translateInterpolation, defaultTranslationText, scope.translateLanguage)\n .then(function (translation) {\n applyTranslation(translation, scope, true, translateAttr);\n }, function (translationId) {\n applyTranslation(translationId, scope, false, translateAttr);\n });\n } else {\n // as an empty string cannot be translated, we can solve this using successful=false\n applyTranslation(translationId, scope, false, translateAttr);\n }\n };\n\n var applyTranslation = function (value, scope, successful, translateAttr) {\n if (translateAttr === 'translate') {\n // default translate into innerHTML\n if (!successful && typeof scope.defaultText !== 'undefined') {\n value = scope.defaultText;\n }\n iElement.empty().append(scope.preText + value + scope.postText);\n var globallyEnabled = $translate.isPostCompilingEnabled();\n var locallyDefined = typeof tAttr.translateCompile !== 'undefined';\n var locallyEnabled = locallyDefined && tAttr.translateCompile !== 'false';\n if ((globallyEnabled && !locallyDefined) || locallyEnabled) {\n $compile(iElement.contents())(scope);\n }\n } else {\n // translate attribute\n if (!successful && typeof scope.defaultText !== 'undefined') {\n value = scope.defaultText;\n }\n var attributeName = iAttr.$attr[translateAttr];\n if (attributeName.substr(0, 5) === 'data-') {\n // ensure html5 data prefix is stripped\n attributeName = attributeName.substr(5);\n }\n attributeName = attributeName.substr(15);\n iElement.attr(attributeName, value);\n }\n };\n\n if (translateValuesExist || translateValueExist || iAttr.translateDefault) {\n scope.$watch('interpolateParams', updateTranslations, true);\n }\n scope.$watch('translateLanguage', updateTranslations);\n\n // Ensures the text will be refreshed after the current language was changed\n // w/ $translate.use(...)\n var unbind = $rootScope.$on('$translateChangeSuccess', updateTranslations);\n\n // ensure translation will be looked up at least one\n if (iElement.text().length) {\n if (iAttr.translate) {\n observeElementTranslation(iAttr.translate);\n } else {\n observeElementTranslation('');\n }\n } else if (iAttr.translate) {\n // ensure attribute will be not skipped\n observeElementTranslation(iAttr.translate);\n }\n updateTranslations();\n scope.$on('$destroy', unbind);\n };\n }\n };\n}\ntranslateDirective.$inject = ['$translate', '$q', '$interpolate', '$compile', '$parse', '$rootScope'];\n\n/**\n * Returns the scope's namespace.\n * @private\n * @param scope\n * @returns {string}\n */\nfunction getTranslateNamespace(scope) {\n 'use strict';\n if (scope.translateNamespace) {\n return scope.translateNamespace;\n }\n if (scope.$parent) {\n return getTranslateNamespace(scope.$parent);\n }\n}\n\ntranslateDirective.displayName = 'translateDirective';\n\nangular.module('pascalprecht.translate')\n/**\n * @ngdoc directive\n * @name pascalprecht.translate.directive:translateCloak\n * @requires $rootScope\n * @requires $translate\n * @restrict A\n *\n * $description\n * Adds a `translate-cloak` class name to the given element where this directive\n * is applied initially and removes it, once a loader has finished loading.\n *\n * This directive can be used to prevent initial flickering when loading translation\n * data asynchronously.\n *\n * The class name is defined in\n * {@link pascalprecht.translate.$translateProvider#cloakClassName $translate.cloakClassName()}.\n *\n * @param {string=} translate-cloak If a translationId is provided, it will be used for showing\n * or hiding the cloak. Basically it relies on the translation\n * resolve.\n */\n.directive('translateCloak', translateCloakDirective);\n\nfunction translateCloakDirective($translate, $rootScope) {\n\n 'use strict';\n\n return {\n compile: function (tElement) {\n var applyCloak = function () {\n tElement.addClass($translate.cloakClassName());\n },\n removeCloak = function () {\n tElement.removeClass($translate.cloakClassName());\n };\n $translate.onReady(function () {\n removeCloak();\n });\n applyCloak();\n\n return function linkFn(scope, iElement, iAttr) {\n if (iAttr.translateCloak && iAttr.translateCloak.length) {\n // Register a watcher for the defined translation allowing a fine tuned cloak\n iAttr.$observe('translateCloak', function (translationId) {\n $translate(translationId).then(removeCloak, applyCloak);\n });\n // Register for change events as this is being another indicicator revalidating the cloak)\n $rootScope.$on('$translateChangeSuccess', function () {\n $translate(iAttr.translateCloak).then(removeCloak, applyCloak);\n });\n }\n };\n }\n };\n}\ntranslateCloakDirective.$inject = ['$translate', '$rootScope'];\n\ntranslateCloakDirective.displayName = 'translateCloakDirective';\n\nangular.module('pascalprecht.translate')\n/**\n * @ngdoc directive\n * @name pascalprecht.translate.directive:translateNamespace\n * @restrict A\n *\n * @description\n * Translates given translation id either through attribute or DOM content.\n * Internally it uses `translate` filter to translate translation id. It possible to\n * pass an optional `translate-values` object literal as string into translation id.\n *\n * @param {string=} translate namespace name which could be either string or interpolated string.\n *\n * @example\n \n \n
\n\n
\n

.HEADERS.TITLE

\n

.HEADERS.WELCOME

\n
\n\n
\n

.TITLE

\n

.WELCOME

\n
\n\n
\n
\n \n angular.module('ngView', ['pascalprecht.translate'])\n\n .config(function ($translateProvider) {\n\n $translateProvider.translations('en',{\n 'TRANSLATION_ID': 'Hello there!',\n 'CONTENT': {\n 'HEADERS': {\n TITLE: 'Title'\n }\n },\n 'CONTENT.HEADERS.WELCOME': 'Welcome'\n }).preferredLanguage('en');\n\n });\n\n \n
\n */\n.directive('translateNamespace', translateNamespaceDirective);\n\nfunction translateNamespaceDirective() {\n\n 'use strict';\n\n return {\n restrict: 'A',\n scope: true,\n compile: function () {\n return {\n pre: function (scope, iElement, iAttrs) {\n scope.translateNamespace = getTranslateNamespace(scope);\n\n if (scope.translateNamespace && iAttrs.translateNamespace.charAt(0) === '.') {\n scope.translateNamespace += iAttrs.translateNamespace;\n } else {\n scope.translateNamespace = iAttrs.translateNamespace;\n }\n }\n };\n }\n };\n}\n\n/**\n * Returns the scope's namespace.\n * @private\n * @param scope\n * @returns {string}\n */\nfunction getTranslateNamespace(scope) {\n 'use strict';\n if (scope.translateNamespace) {\n return scope.translateNamespace;\n }\n if (scope.$parent) {\n return getTranslateNamespace(scope.$parent);\n }\n}\n\ntranslateNamespaceDirective.displayName = 'translateNamespaceDirective';\n\nangular.module('pascalprecht.translate')\n/**\n * @ngdoc directive\n * @name pascalprecht.translate.directive:translateLanguage\n * @restrict A\n *\n * @description\n * Forces the language to the directives in the underlying scope.\n *\n * @param {string=} translate language that will be negotiated.\n *\n * @example\n \n \n
\n\n
\n

HELLO

\n
\n\n
\n

HELLO

\n
\n\n
\n
\n \n angular.module('ngView', ['pascalprecht.translate'])\n\n .config(function ($translateProvider) {\n\n $translateProvider\n .translations('en',{\n 'HELLO': 'Hello world!'\n })\n .translations('de',{\n 'HELLO': 'Hallo Welt!'\n })\n .translations(.preferredLanguage('en');\n\n });\n\n \n
\n */\n.directive('translateLanguage', translateLanguageDirective);\n\nfunction translateLanguageDirective() {\n\n 'use strict';\n\n return {\n restrict: 'A',\n scope: true,\n compile: function () {\n return function linkFn(scope, iElement, iAttrs) {\n iAttrs.$observe('translateLanguage', function (newTranslateLanguage) {\n scope.translateLanguage = newTranslateLanguage;\n });\n };\n }\n };\n}\n\ntranslateLanguageDirective.displayName = 'translateLanguageDirective';\n\n\nangular.module('pascalprecht.translate')\n/**\n * @ngdoc filter\n * @name pascalprecht.translate.filter:translate\n * @requires $parse\n * @requires pascalprecht.translate.$translate\n * @function\n *\n * @description\n * Uses `$translate` service to translate contents. Accepts interpolate parameters\n * to pass dynamized values though translation.\n *\n * @param {string} translationId A translation id to be translated.\n * @param {*=} interpolateParams Optional object literal (as hash or string) to pass values into translation.\n *\n * @returns {string} Translated text.\n *\n * @example\n \n \n
\n\n
{{ 'TRANSLATION_ID' | translate }}
\n
{{ translationId | translate }}
\n
{{ 'WITH_VALUES' | translate:'{value: 5}' }}
\n
{{ 'WITH_VALUES' | translate:values }}
\n\n
\n
\n \n angular.module('ngView', ['pascalprecht.translate'])\n\n .config(function ($translateProvider) {\n\n $translateProvider.translations('en', {\n 'TRANSLATION_ID': 'Hello there!',\n 'WITH_VALUES': 'The following value is dynamic: {{value}}'\n });\n $translateProvider.preferredLanguage('en');\n\n });\n\n angular.module('ngView').controller('TranslateCtrl', function ($scope) {\n $scope.translationId = 'TRANSLATION_ID';\n\n $scope.values = {\n value: 78\n };\n });\n \n
\n */\n.filter('translate', translateFilterFactory);\n\nfunction translateFilterFactory($parse, $translate) {\n\n 'use strict';\n\n var translateFilter = function (translationId, interpolateParams, interpolation, forceLanguage) {\n\n if (!angular.isObject(interpolateParams)) {\n interpolateParams = $parse(interpolateParams)(this);\n }\n\n return $translate.instant(translationId, interpolateParams, interpolation, forceLanguage);\n };\n\n if ($translate.statefulFilter()) {\n translateFilter.$stateful = true;\n }\n\n return translateFilter;\n}\ntranslateFilterFactory.$inject = ['$parse', '$translate'];\n\ntranslateFilterFactory.displayName = 'translateFilterFactory';\n\nangular.module('pascalprecht.translate')\n\n/**\n * @ngdoc object\n * @name pascalprecht.translate.$translationCache\n * @requires $cacheFactory\n *\n * @description\n * The first time a translation table is used, it is loaded in the translation cache for quick retrieval. You\n * can load translation tables directly into the cache by consuming the\n * `$translationCache` service directly.\n *\n * @return {object} $cacheFactory object.\n */\n .factory('$translationCache', $translationCache);\n\nfunction $translationCache($cacheFactory) {\n\n 'use strict';\n\n return $cacheFactory('translations');\n}\n$translationCache.$inject = ['$cacheFactory'];\n\n$translationCache.displayName = '$translationCache';\nreturn 'pascalprecht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kbGVyVHJhbnNsYXRpb24pO1xuICAgICAgICAgICAgICB9XG4gICAgICAgICAgfSBlbHNlIHtcbiAgICAgICAgICAgIGlmIChkZWZhdWx0VHJhbnNsYXRpb25UZXh0KSB7XG4gICAgICAgICAgICAgIGRlZmVycmVkLnJlc29sdmUoZGVmYXVsdFRyYW5zbGF0aW9uVGV4dCk7XG4gICAgICAgICAgICB9IGVsc2Uge1xuICAgICAgICAgICAgICBkZWZlcnJlZC5yZWplY3QoYXBwbHlOb3RGb3VuZEluZGljYXRvcnModHJhbnNsYXRpb25JZCkpO1xuICAgICAgICAgICAgfVxuICAgICAgICAgIH1cbiAgICAgICAgfVxuICAgICAgICByZXR1cm4gZGVmZXJyZWQucHJvbWlzZTtcbiAgICAgIH07XG5cbiAgICAgIHZhciBkZXRlcm1pbmVUcmFuc2xhdGlvbkluc3RhbnQgPSBmdW5jdGlvbiAodHJhbnNsYXRpb25JZCwgaW50ZXJwb2xhdGVQYXJhbXMsIGludGVycG9sYXRpb25JZCwgdXNlcykge1xuXG4gICAgICAgIHZhciByZXN1bHQsIHRhYmxlID0gdXNlcyA/ICR0cmFuc2xhdGlvblRhYmxlW3VzZXNdIDogJHRyYW5zbGF0aW9uVGFibGUsXG4gICAgICAgICAgICBJbnRlcnBvbGF0b3IgPSBkZWZhdWx0SW50ZXJwb2xhdG9yO1xuXG4gICAgICAgIC8vIGlmIHRoZSBpbnRlcnBvbGF0aW9uIGlkIGV4aXN0cyB1c2UgY3VzdG9tIGludGVycG9sYXRvclxuICAgICAgICBpZiAoaW50ZXJwb2xhdG9ySGFzaE1hcCAmJiBPYmplY3QucHJvdG90eXBlLmhhc093blByb3BlcnR5LmNhbGwoaW50ZXJwb2xhdG9ySGFzaE1hcCwgaW50ZXJwb2xhdGlvbklkKSkge1xuICAgICAgICAgIEludGVycG9sYXRvciA9IGludGVycG9sYXRvckhhc2hNYXBbaW50ZXJwb2xhdGlvbklkXTtcbiAgICAgICAgfVxuXG4gICAgICAgIC8vIGl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ZCBpdCBhc3luY2hyb25vdXNseVxuICAgICAgICBpZiAoKCRmb3JjZUFzeW5jUmVsb2FkRW5hYmxlZCB8fCAhJHRyYW5zbGF0aW9uVGFibGVba2V5XSkgJiYgJGxvYWRlckZhY3RvcnkgJiYgIWxhbmdQcm9taXNlc1trZXldKSB7XG4gICAgICAgICAgJG5leHRMYW5nID0ga2V5O1xuICAgICAgICAgIGxhbmdQcm9taXNlc1trZXldID0gbG9hZEFzeW5jKGtleSkudGhlbihmdW5jdGlvbiAodHJhbnNsYXRpb24pIHtcbiAgICAgICAgICAgIHRyYW5zbGF0aW9ucyh0cmFuc2xhdGlvbi5rZXksIHRyYW5zbGF0aW9uLnRhYmxlKTtcbiAgICAgICAgICAgIGRlZmVycmVkLnJlc29sdmUodHJhbnNsYXRpb24ua2V5KTtcbiAgICAgICAgICAgIGlmICgkbmV4dExhbmcgPT09IGtleSkge1xuICAgICAgICAgICAgICB1c2VMYW5ndWFnZSh0cmFuc2xhdGlvbi5rZXkpO1xuICAgICAgICAgICAgfVxuICAgICAgICAgICAgcmV0dXJuIHRyYW5zbGF0aW9uO1xuICAgICAgICAgIH0sIGZ1bmN0aW9uIChrZXkpIHtcbiAgICAgICAgICAgICRyb290U2NvcGUuJGVtaXQoJyR0cmFuc2xhdGVDaGFuZ2VFcnJvcicsIHtsYW5ndWFnZToga2V5fSk7XG4gICAgICAgICAgICBkZWZlcnJlZC5yZWplY3Qoa2V5KTtcbiAgICAgICAgICAgICRyb290U2NvcGUuJGVtaXQoJyR0cmFuc2xhdGVDaGFuZ2VFbmQnLCB7bGFuZ3VhZ2U6IGtleX0pO1xuICAgICAgICAgICAgcmV0dXJuICRxLnJlamVjdChrZXkpO1xuICAgICAgICAgIH0pO1xuICAgICAgICAgIGxhbmdQcm9taXNlc1trZXldWydmaW5hbGx5J10oZnVuY3Rpb24gKCkge1xuICAgICAgICAgICAgY2xlYXJOZXh0TGFuZ0FuZFByb21pc2Uoa2V5KTtcbiAgICAgICAgICB9KT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QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTsiLCJzb3VyY2VSb290IjoiIn0=\n//# sourceURL=webpack-internal:///./node_modules/angular-translate/dist/angular-translate.js\n" + ); + + /***/ + }, + + /***/ "./node_modules/angular/angular.js": + /*!*****************************************!*\ + !*** ./node_modules/angular/angular.js ***! + \*****************************************/ + /*! no static exports found */ + /***/ function(module, exports, __webpack_require__) { + eval( + "/* WEBPACK VAR INJECTION */(function(__webpack_provided_window_dot_jQuery) {/**\n * @license AngularJS v1.6.0\n * (c) 2010-2016 Google, Inc. http://angularjs.org\n * License: MIT\n */\n(function(window) {'use strict';\n\n/**\n * @description\n *\n * This object provides a utility for producing rich Error messages within\n * Angular. It can be called as follows:\n *\n * var exampleMinErr = minErr('example');\n * throw exampleMinErr('one', 'This {0} is {1}', foo, bar);\n *\n * The above creates an instance of minErr in the example namespace. The\n * resulting error will have a namespaced error code of example.one. The\n * resulting error will replace {0} with the value of foo, and {1} with the\n * value of bar. The object is not restricted in the number of arguments it can\n * take.\n *\n * If fewer arguments are specified than necessary for interpolation, the extra\n * interpolation markers will be preserved in the final string.\n *\n * Since data will be parsed statically during a build step, some restrictions\n * are applied with respect to how minErr instances are created and called.\n * Instances should have names of the form namespaceMinErr for a minErr created\n * using minErr('namespace') . Error codes, namespaces and template strings\n * should all be static strings, not variables or general expressions.\n *\n * @param {string} module The namespace to use for the new minErr instance.\n * @param {function} ErrorConstructor Custom error constructor to be instantiated when returning\n * error from returned function, for cases when a particular type of error is useful.\n * @returns {function(code:string, template:string, ...templateArgs): Error} minErr instance\n */\n\nfunction minErr(module, ErrorConstructor) {\n ErrorConstructor = ErrorConstructor || Error;\n return function() {\n var SKIP_INDEXES = 2;\n\n var templateArgs = arguments,\n code = templateArgs[0],\n message = '[' + (module ? module + ':' : '') + code + '] ',\n template = templateArgs[1],\n paramPrefix, i;\n\n message += template.replace(/\\{\\d+\\}/g, function(match) {\n var index = +match.slice(1, -1),\n shiftedIndex = index + SKIP_INDEXES;\n\n if (shiftedIndex < templateArgs.length) {\n return toDebugString(templateArgs[shiftedIndex]);\n }\n\n return match;\n });\n\n message += '\\nhttp://errors.angularjs.org/1.6.0/' +\n (module ? module + '/' : '') + code;\n\n for (i = SKIP_INDEXES, paramPrefix = '?'; i < templateArgs.length; i++, paramPrefix = '&') {\n message += paramPrefix + 'p' + (i - SKIP_INDEXES) + '=' +\n encodeURIComponent(toDebugString(templateArgs[i]));\n }\n\n return new ErrorConstructor(message);\n };\n}\n\n/* We need to tell ESLint what variables are being exported */\n/* exported\n angular,\n msie,\n jqLite,\n jQuery,\n slice,\n splice,\n push,\n toString,\n ngMinErr,\n angularModule,\n uid,\n REGEX_STRING_REGEXP,\n VALIDITY_STATE_PROPERTY,\n\n lowercase,\n uppercase,\n manualLowercase,\n manualUppercase,\n nodeName_,\n isArrayLike,\n forEach,\n forEachSorted,\n reverseParams,\n nextUid,\n setHashKey,\n extend,\n toInt,\n inherit,\n merge,\n noop,\n identity,\n valueFn,\n isUndefined,\n isDefined,\n isObject,\n isBlankObject,\n isString,\n isNumber,\n isNumberNaN,\n isDate,\n isArray,\n isFunction,\n isRegExp,\n isWindow,\n isScope,\n isFile,\n isFormData,\n isBlob,\n isBoolean,\n isPromiseLike,\n trim,\n escapeForRegexp,\n isElement,\n makeMap,\n includes,\n arrayRemove,\n copy,\n equals,\n csp,\n jq,\n concat,\n sliceArgs,\n bind,\n toJsonReplacer,\n toJson,\n fromJson,\n convertTimezoneToLocal,\n timezoneToOffset,\n startingTag,\n tryDecodeURIComponent,\n parseKeyValue,\n toKeyValue,\n encodeUriSegment,\n encodeUriQuery,\n angularInit,\n bootstrap,\n getTestability,\n snake_case,\n bindJQuery,\n assertArg,\n assertArgFn,\n assertNotHasOwnProperty,\n getter,\n getBlockNodes,\n hasOwnProperty,\n createMap,\n stringify,\n\n NODE_TYPE_ELEMENT,\n NODE_TYPE_ATTRIBUTE,\n NODE_TYPE_TEXT,\n NODE_TYPE_COMMENT,\n NODE_TYPE_DOCUMENT,\n NODE_TYPE_DOCUMENT_FRAGMENT\n*/\n\n////////////////////////////////////\n\n/**\n * @ngdoc module\n * @name ng\n * @module ng\n * @installation\n * @description\n *\n * # ng (core module)\n * The ng module is loaded by default when an AngularJS application is started. The module itself\n * contains the essential components for an AngularJS application to function. The table below\n * lists a high level breakdown of each of the services/factories, filters, directives and testing\n * components available within this core module.\n *\n *
\n */\n\nvar REGEX_STRING_REGEXP = /^\\/(.+)\\/([a-z]*)$/;\n\n// The name of a form control's ValidityState property.\n// This is used so that it's possible for internal tests to create mock ValidityStates.\nvar VALIDITY_STATE_PROPERTY = 'validity';\n\n\nvar hasOwnProperty = Object.prototype.hasOwnProperty;\n\n/**\n * @ngdoc function\n * @name angular.lowercase\n * @module ng\n * @kind function\n *\n * @deprecated\n * sinceVersion=\"1.5.0\"\n * removeVersion=\"1.7.0\"\n * Use [String.prototype.toLowerCase](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/String/toLowerCase) instead.\n *\n * @description Converts the specified string to lowercase.\n * @param {string} string String to be converted to lowercase.\n * @returns {string} Lowercased string.\n */\nvar lowercase = function(string) {return isString(string) ? string.toLowerCase() : string;};\n\n/**\n * @ngdoc function\n * @name angular.uppercase\n * @module ng\n * @kind function\n *\n * @deprecated\n * sinceVersion=\"1.5.0\"\n * removeVersion=\"1.7.0\"\n * Use [String.prototype.toUpperCase](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/String/toUpperCase) instead.\n *\n * @description Converts the specified string to uppercase.\n * @param {string} string String to be converted to uppercase.\n * @returns {string} Uppercased string.\n */\nvar uppercase = function(string) {return isString(string) ? string.toUpperCase() : string;};\n\n\nvar manualLowercase = function(s) {\n /* eslint-disable no-bitwise */\n return isString(s)\n ? s.replace(/[A-Z]/g, function(ch) {return String.fromCharCode(ch.charCodeAt(0) | 32);})\n : s;\n /* eslint-enable */\n};\nvar manualUppercase = function(s) {\n /* eslint-disable no-bitwise */\n return isString(s)\n ? s.replace(/[a-z]/g, function(ch) {return String.fromCharCode(ch.charCodeAt(0) & ~32);})\n : s;\n /* eslint-enable */\n};\n\n\n// String#toLowerCase and String#toUpperCase don't produce correct results in browsers with Turkish\n// locale, for this reason we need to detect this case and redefine lowercase/uppercase methods\n// with correct but slower alternatives. See https://github.com/angular/angular.js/issues/11387\nif ('i' !== 'I'.toLowerCase()) {\n lowercase = manualLowercase;\n uppercase = manualUppercase;\n}\n\n\nvar\n msie, // holds major version number for IE, or NaN if UA is not IE.\n jqLite, // delay binding since jQuery could be loaded after us.\n jQuery, // delay binding\n slice = [].slice,\n splice = [].splice,\n push = [].push,\n toString = Object.prototype.toString,\n getPrototypeOf = Object.getPrototypeOf,\n ngMinErr = minErr('ng'),\n\n /** @name angular */\n angular = window.angular || (window.angular = {}),\n angularModule,\n uid = 0;\n\n// Support: IE 9-11 only\n/**\n * documentMode is an IE-only property\n * http://msdn.microsoft.com/en-us/library/ie/cc196988(v=vs.85).aspx\n */\nmsie = window.document.documentMode;\n\n\n/**\n * @private\n * @param {*} obj\n * @return {boolean} Returns true if `obj` is an array or array-like object (NodeList, Arguments,\n * String ...)\n */\nfunction isArrayLike(obj) {\n\n // `null`, `undefined` and `window` are not array-like\n if (obj == null || isWindow(obj)) return false;\n\n // arrays, strings and jQuery/jqLite objects are array like\n // * jqLite is either the jQuery or jqLite constructor function\n // * we have to check the existence of jqLite first as this method is called\n // via the forEach method when constructing the jqLite object in the first place\n if (isArray(obj) || isString(obj) || (jqLite && obj instanceof jqLite)) return true;\n\n // Support: iOS 8.2 (not reproducible in simulator)\n // \"length\" in obj used to prevent JIT error (gh-11508)\n var length = 'length' in Object(obj) && obj.length;\n\n // NodeList objects (with `item` method) and\n // other objects with suitable length characteristics are array-like\n return isNumber(length) &&\n (length >= 0 && ((length - 1) in obj || obj instanceof Array) || typeof obj.item === 'function');\n\n}\n\n/**\n * @ngdoc function\n * @name angular.forEach\n * @module ng\n * @kind function\n *\n * @description\n * Invokes the `iterator` function once for each item in `obj` collection, which can be either an\n * object or an array. The `iterator` function is invoked with `iterator(value, key, obj)`, where `value`\n * is the value of an object property or an array element, `key` is the object property key or\n * array element index and obj is the `obj` itself. Specifying a `context` for the function is optional.\n *\n * It is worth noting that `.forEach` does not iterate over inherited properties because it filters\n * using the `hasOwnProperty` method.\n *\n * Unlike ES262's\n * [Array.prototype.forEach](http://www.ecma-international.org/ecma-262/5.1/#sec-15.4.4.18),\n * providing 'undefined' or 'null' values for `obj` will not throw a TypeError, but rather just\n * return the value provided.\n *\n ```js\n var values = {name: 'misko', gender: 'male'};\n var log = [];\n angular.forEach(values, function(value, key) {\n this.push(key + ': ' + value);\n }, log);\n expect(log).toEqual(['name: misko', 'gender: male']);\n ```\n *\n * @param {Object|Array} obj Object to iterate over.\n * @param {Function} iterator Iterator function.\n * @param {Object=} context Object to become context (`this`) for the iterator function.\n * @returns {Object|Array} Reference to `obj`.\n */\n\nfunction forEach(obj, iterator, context) {\n var key, length;\n if (obj) {\n if (isFunction(obj)) {\n for (key in obj) {\n if (key !== 'prototype' && key !== 'length' && key !== 'name' && obj.hasOwnProperty(key)) {\n iterator.call(context, obj[key], key, obj);\n }\n }\n } else if (isArray(obj) || isArrayLike(obj)) {\n var isPrimitive = typeof obj !== 'object';\n for (key = 0, length = obj.length; key < length; key++) {\n if (isPrimitive || key in obj) {\n iterator.call(context, obj[key], key, obj);\n }\n }\n } else if (obj.forEach && obj.forEach !== forEach) {\n obj.forEach(iterator, context, obj);\n } else if (isBlankObject(obj)) {\n // createMap() fast path --- Safe to avoid hasOwnProperty check because prototype chain is empty\n for (key in obj) {\n iterator.call(context, obj[key], key, obj);\n }\n } else if (typeof obj.hasOwnProperty === 'function') {\n // Slow path for objects inheriting Object.prototype, hasOwnProperty check needed\n for (key in obj) {\n if (obj.hasOwnProperty(key)) {\n iterator.call(context, obj[key], key, obj);\n }\n }\n } else {\n // Slow path for objects which do not have a method `hasOwnProperty`\n for (key in obj) {\n if (hasOwnProperty.call(obj, key)) {\n iterator.call(context, obj[key], key, obj);\n }\n }\n }\n }\n return obj;\n}\n\nfunction forEachSorted(obj, iterator, context) {\n var keys = Object.keys(obj).sort();\n for (var i = 0; i < keys.length; i++) {\n iterator.call(context, obj[keys[i]], keys[i]);\n }\n return keys;\n}\n\n\n/**\n * when using forEach the params are value, key, but it is often useful to have key, value.\n * @param {function(string, *)} iteratorFn\n * @returns {function(*, string)}\n */\nfunction reverseParams(iteratorFn) {\n return function(value, key) {iteratorFn(key, value);};\n}\n\n/**\n * A consistent way of creating unique IDs in angular.\n *\n * Using simple numbers allows us to generate 28.6 million unique ids per second for 10 years before\n * we hit number precision issues in JavaScript.\n *\n * Math.pow(2,53) / 60 / 60 / 24 / 365 / 10 = 28.6M\n *\n * @returns {number} an unique alpha-numeric string\n */\nfunction nextUid() {\n return ++uid;\n}\n\n\n/**\n * Set or clear the hashkey for an object.\n * @param obj object\n * @param h the hashkey (!truthy to delete the hashkey)\n */\nfunction setHashKey(obj, h) {\n if (h) {\n obj.$$hashKey = h;\n } else {\n delete obj.$$hashKey;\n }\n}\n\n\nfunction baseExtend(dst, objs, deep) {\n var h = dst.$$hashKey;\n\n for (var i = 0, ii = objs.length; i < ii; ++i) {\n var obj = objs[i];\n if (!isObject(obj) && !isFunction(obj)) continue;\n var keys = Object.keys(obj);\n for (var j = 0, jj = keys.length; j < jj; j++) {\n var key = keys[j];\n var src = obj[key];\n\n if (deep && isObject(src)) {\n if (isDate(src)) {\n dst[key] = new Date(src.valueOf());\n } else if (isRegExp(src)) {\n dst[key] = new RegExp(src);\n } else if (src.nodeName) {\n dst[key] = src.cloneNode(true);\n } else if (isElement(src)) {\n dst[key] = src.clone();\n } else {\n if (!isObject(dst[key])) dst[key] = isArray(src) ? [] : {};\n baseExtend(dst[key], [src], true);\n }\n } else {\n dst[key] = src;\n }\n }\n }\n\n setHashKey(dst, h);\n return dst;\n}\n\n/**\n * @ngdoc function\n * @name angular.extend\n * @module ng\n * @kind function\n *\n * @description\n * Extends the destination object `dst` by copying own enumerable properties from the `src` object(s)\n * to `dst`. You can specify multiple `src` objects. If you want to preserve original objects, you can do so\n * by passing an empty object as the target: `var object = angular.extend({}, object1, object2)`.\n *\n * **Note:** Keep in mind that `angular.extend` does not support recursive merge (deep copy). Use\n * {@link angular.merge} for this.\n *\n * @param {Object} dst Destination object.\n * @param {...Object} src Source object(s).\n * @returns {Object} Reference to `dst`.\n */\nfunction extend(dst) {\n return baseExtend(dst, slice.call(arguments, 1), false);\n}\n\n\n/**\n* @ngdoc function\n* @name angular.merge\n* @module ng\n* @kind function\n*\n* @description\n* Deeply extends the destination object `dst` by copying own enumerable properties from the `src` object(s)\n* to `dst`. You can specify multiple `src` objects. If you want to preserve original objects, you can do so\n* by passing an empty object as the target: `var object = angular.merge({}, object1, object2)`.\n*\n* Unlike {@link angular.extend extend()}, `merge()` recursively descends into object properties of source\n* objects, performing a deep copy.\n*\n* @param {Object} dst Destination object.\n* @param {...Object} src Source object(s).\n* @returns {Object} Reference to `dst`.\n*/\nfunction merge(dst) {\n return baseExtend(dst, slice.call(arguments, 1), true);\n}\n\n\n\nfunction toInt(str) {\n return parseInt(str, 10);\n}\n\nvar isNumberNaN = Number.isNaN || function isNumberNaN(num) {\n // eslint-disable-next-line no-self-compare\n return num !== num;\n};\n\n\nfunction inherit(parent, extra) {\n return extend(Object.create(parent), extra);\n}\n\n/**\n * @ngdoc function\n * @name angular.noop\n * @module ng\n * @kind function\n *\n * @description\n * A function that performs no operations. This function can be useful when writing code in the\n * functional style.\n ```js\n function foo(callback) {\n var result = calculateResult();\n (callback || angular.noop)(result);\n }\n ```\n */\nfunction noop() {}\nnoop.$inject = [];\n\n\n/**\n * @ngdoc function\n * @name angular.identity\n * @module ng\n * @kind function\n *\n * @description\n * A function that returns its first argument. This function is useful when writing code in the\n * functional style.\n *\n ```js\n function transformer(transformationFn, value) {\n return (transformationFn || angular.identity)(value);\n };\n\n // E.g.\n function getResult(fn, input) {\n return (fn || angular.identity)(input);\n };\n\n getResult(function(n) { return n * 2; }, 21); // returns 42\n getResult(null, 21); // returns 21\n getResult(undefined, 21); // returns 21\n ```\n *\n * @param {*} value to be returned.\n * @returns {*} the value passed in.\n */\nfunction identity($) {return $;}\nidentity.$inject = [];\n\n\nfunction valueFn(value) {return function valueRef() {return value;};}\n\nfunction hasCustomToString(obj) {\n return isFunction(obj.toString) && obj.toString !== toString;\n}\n\n\n/**\n * @ngdoc function\n * @name angular.isUndefined\n * @module ng\n * @kind function\n *\n * @description\n * Determines if a reference is undefined.\n *\n * @param {*} value Reference to check.\n * @returns {boolean} True if `value` is undefined.\n */\nfunction isUndefined(value) {return typeof value === 'undefined';}\n\n\n/**\n * @ngdoc function\n * @name angular.isDefined\n * @module ng\n * @kind function\n *\n * @description\n * Determines if a reference is defined.\n *\n * @param {*} value Reference to check.\n * @returns {boolean} True if `value` is defined.\n */\nfunction isDefined(value) {return typeof value !== 'undefined';}\n\n\n/**\n * @ngdoc function\n * @name angular.isObject\n * @module ng\n * @kind function\n *\n * @description\n * Determines if a reference is an `Object`. Unlike `typeof` in JavaScript, `null`s are not\n * considered to be objects. Note that JavaScript arrays are objects.\n *\n * @param {*} value Reference to check.\n * @returns {boolean} True if `value` is an `Object` but not `null`.\n */\nfunction isObject(value) {\n // http://jsperf.com/isobject4\n return value !== null && typeof value === 'object';\n}\n\n\n/**\n * Determine if a value is an object with a null prototype\n *\n * @returns {boolean} True if `value` is an `Object` with a null prototype\n */\nfunction isBlankObject(value) {\n return value !== null && typeof value === 'object' && !getPrototypeOf(value);\n}\n\n\n/**\n * @ngdoc function\n * @name angular.isString\n * @module ng\n * @kind function\n *\n * @description\n * Determines if a reference is a `String`.\n *\n * @param {*} value Reference to check.\n * @returns {boolean} True if `value` is a `String`.\n */\nfunction isString(value) {return typeof value === 'string';}\n\n\n/**\n * @ngdoc function\n * @name angular.isNumber\n * @module ng\n * @kind function\n *\n * @description\n * Determines if a reference is a `Number`.\n *\n * This includes the \"special\" numbers `NaN`, `+Infinity` and `-Infinity`.\n *\n * If you wish to exclude these then you can use the native\n * [`isFinite'](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/isFinite)\n * method.\n *\n * @param {*} value Reference to check.\n * @returns {boolean} True if `value` is a `Number`.\n */\nfunction isNumber(value) {return typeof value === 'number';}\n\n\n/**\n * @ngdoc function\n * @name angular.isDate\n * @module ng\n * @kind function\n *\n * @description\n * Determines if a value is a date.\n *\n * @param {*} value Reference to check.\n * @returns {boolean} True if `value` is a `Date`.\n */\nfunction isDate(value) {\n return toString.call(value) === '[object Date]';\n}\n\n\n/**\n * @ngdoc function\n * @name angular.isArray\n * @module ng\n * @kind function\n *\n * @description\n * Determines if a reference is an `Array`. Alias of Array.isArray.\n *\n * @param {*} value Reference to check.\n * @returns {boolean} True if `value` is an `Array`.\n */\nvar isArray = Array.isArray;\n\n/**\n * @ngdoc function\n * @name angular.isFunction\n * @module ng\n * @kind function\n *\n * @description\n * Determines if a reference is a `Function`.\n *\n * @param {*} value Reference to check.\n * @returns {boolean} True if `value` is a `Function`.\n */\nfunction isFunction(value) {return typeof value === 'function';}\n\n\n/**\n * Determines if a value is a regular expression object.\n *\n * @private\n * @param {*} value Reference to check.\n * @returns {boolean} True if `value` is a `RegExp`.\n */\nfunction isRegExp(value) {\n return toString.call(value) === '[object RegExp]';\n}\n\n\n/**\n * Checks if `obj` is a window object.\n *\n * @private\n * @param {*} obj Object to check\n * @returns {boolean} True if `obj` is a window obj.\n */\nfunction isWindow(obj) {\n return obj && obj.window === obj;\n}\n\n\nfunction isScope(obj) {\n return obj && obj.$evalAsync && obj.$watch;\n}\n\n\nfunction isFile(obj) {\n return toString.call(obj) === '[object File]';\n}\n\n\nfunction isFormData(obj) {\n return toString.call(obj) === '[object FormData]';\n}\n\n\nfunction isBlob(obj) {\n return toString.call(obj) === '[object Blob]';\n}\n\n\nfunction isBoolean(value) {\n return typeof value === 'boolean';\n}\n\n\nfunction isPromiseLike(obj) {\n return obj && isFunction(obj.then);\n}\n\n\nvar TYPED_ARRAY_REGEXP = /^\\[object (?:Uint8|Uint8Clamped|Uint16|Uint32|Int8|Int16|Int32|Float32|Float64)Array]$/;\nfunction isTypedArray(value) {\n return value && isNumber(value.length) && TYPED_ARRAY_REGEXP.test(toString.call(value));\n}\n\nfunction isArrayBuffer(obj) {\n return toString.call(obj) === '[object ArrayBuffer]';\n}\n\n\nvar trim = function(value) {\n return isString(value) ? value.trim() : value;\n};\n\n// Copied from:\n// http://docs.closure-library.googlecode.com/git/local_closure_goog_string_string.js.source.html#line1021\n// Prereq: s is a string.\nvar escapeForRegexp = function(s) {\n return s\n .replace(/([-()[\\]{}+?*.$^|,:#= 0) {\n array.splice(index, 1);\n }\n return index;\n}\n\n/**\n * @ngdoc function\n * @name angular.copy\n * @module ng\n * @kind function\n *\n * @description\n * Creates a deep copy of `source`, which should be an object or an array.\n *\n * * If no destination is supplied, a copy of the object or array is created.\n * * If a destination is provided, all of its elements (for arrays) or properties (for objects)\n * are deleted and then all elements/properties from the source are copied to it.\n * * If `source` is not an object or array (inc. `null` and `undefined`), `source` is returned.\n * * If `source` is identical to `destination` an exception will be thrown.\n *\n *
\n *
\n * Only enumerable properties are taken into account. Non-enumerable properties (both on `source`\n * and on `destination`) will be ignored.\n *
\n *\n * @param {*} source The source that will be used to make a copy.\n * Can be any type, including primitives, `null`, and `undefined`.\n * @param {(Object|Array)=} destination Destination into which the source is copied. If\n * provided, must be of the same type as `source`.\n * @returns {*} The copy or updated `destination`, if `destination` was specified.\n *\n * @example\n \n \n
\n
\n
\n
\n Gender: \n
\n \n \n
\n
form = {{user | json}}
\n
master = {{master | json}}
\n
\n
\n \n // Module: copyExample\n angular.\n module('copyExample', []).\n controller('ExampleController', ['$scope', function($scope) {\n $scope.master = {};\n\n $scope.reset = function() {\n // Example with 1 argument\n $scope.user = angular.copy($scope.master);\n };\n\n $scope.update = function(user) {\n // Example with 2 arguments\n angular.copy(user, $scope.master);\n };\n\n $scope.reset();\n }]);\n \n
\n */\nfunction copy(source, destination) {\n var stackSource = [];\n var stackDest = [];\n\n if (destination) {\n if (isTypedArray(destination) || isArrayBuffer(destination)) {\n throw ngMinErr('cpta', 'Can\\'t copy! TypedArray destination cannot be mutated.');\n }\n if (source === destination) {\n throw ngMinErr('cpi', 'Can\\'t copy! Source and destination are identical.');\n }\n\n // Empty the destination object\n if (isArray(destination)) {\n destination.length = 0;\n } else {\n forEach(destination, function(value, key) {\n if (key !== '$$hashKey') {\n delete destination[key];\n }\n });\n }\n\n stackSource.push(source);\n stackDest.push(destination);\n return copyRecurse(source, destination);\n }\n\n return copyElement(source);\n\n function copyRecurse(source, destination) {\n var h = destination.$$hashKey;\n var key;\n if (isArray(source)) {\n for (var i = 0, ii = source.length; i < ii; i++) {\n destination.push(copyElement(source[i]));\n }\n } else if (isBlankObject(source)) {\n // createMap() fast path --- Safe to avoid hasOwnProperty check because prototype chain is empty\n for (key in source) {\n destination[key] = copyElement(source[key]);\n }\n } else if (source && typeof source.hasOwnProperty === 'function') {\n // Slow path, which must rely on hasOwnProperty\n for (key in source) {\n if (source.hasOwnProperty(key)) {\n destination[key] = copyElement(source[key]);\n }\n }\n } else {\n // Slowest path --- hasOwnProperty can't be called as a method\n for (key in source) {\n if (hasOwnProperty.call(source, key)) {\n destination[key] = copyElement(source[key]);\n }\n }\n }\n setHashKey(destination, h);\n return destination;\n }\n\n function copyElement(source) {\n // Simple values\n if (!isObject(source)) {\n return source;\n }\n\n // Already copied values\n var index = stackSource.indexOf(source);\n if (index !== -1) {\n return stackDest[index];\n }\n\n if (isWindow(source) || isScope(source)) {\n throw ngMinErr('cpws',\n 'Can\\'t copy! Making copies of Window or Scope instances is not supported.');\n }\n\n var needsRecurse = false;\n var destination = copyType(source);\n\n if (destination === undefined) {\n destination = isArray(source) ? [] : Object.create(getPrototypeOf(source));\n needsRecurse = true;\n }\n\n stackSource.push(source);\n stackDest.push(destination);\n\n return needsRecurse\n ? copyRecurse(source, destination)\n : destination;\n }\n\n function copyType(source) {\n switch (toString.call(source)) {\n case '[object Int8Array]':\n case '[object Int16Array]':\n case '[object Int32Array]':\n case '[object Float32Array]':\n case '[object Float64Array]':\n case '[object Uint8Array]':\n case '[object Uint8ClampedArray]':\n case '[object Uint16Array]':\n case '[object Uint32Array]':\n return new source.constructor(copyElement(source.buffer), source.byteOffset, source.length);\n\n case '[object ArrayBuffer]':\n // Support: IE10\n if (!source.slice) {\n // If we're in this case we know the environment supports ArrayBuffer\n /* eslint-disable no-undef */\n var copied = new ArrayBuffer(source.byteLength);\n new Uint8Array(copied).set(new Uint8Array(source));\n /* eslint-enable */\n return copied;\n }\n return source.slice(0);\n\n case '[object Boolean]':\n case '[object Number]':\n case '[object String]':\n case '[object Date]':\n return new source.constructor(source.valueOf());\n\n case '[object RegExp]':\n var re = new RegExp(source.source, source.toString().match(/[^/]*$/)[0]);\n re.lastIndex = source.lastIndex;\n return re;\n\n case '[object Blob]':\n return new source.constructor([source], {type: source.type});\n }\n\n if (isFunction(source.cloneNode)) {\n return source.cloneNode(true);\n }\n }\n}\n\n\n/**\n * @ngdoc function\n * @name angular.equals\n * @module ng\n * @kind function\n *\n * @description\n * Determines if two objects or two values are equivalent. Supports value types, regular\n * expressions, arrays and objects.\n *\n * Two objects or values are considered equivalent if at least one of the following is true:\n *\n * * Both objects or values pass `===` comparison.\n * * Both objects or values are of the same type and all of their properties are equal by\n * comparing them with `angular.equals`.\n * * Both values are NaN. (In JavaScript, NaN == NaN => false. But we consider two NaN as equal)\n * * Both values represent the same regular expression (In JavaScript,\n * /abc/ == /abc/ => false. But we consider two regular expressions as equal when their textual\n * representation matches).\n *\n * During a property comparison, properties of `function` type and properties with names\n * that begin with `$` are ignored.\n *\n * Scope and DOMWindow objects are being compared only by identify (`===`).\n *\n * @param {*} o1 Object or value to compare.\n * @param {*} o2 Object or value to compare.\n * @returns {boolean} True if arguments are equal.\n *\n * @example\n \n \n
\n
\n

User 1

\n Name: \n Age: \n\n

User 2

\n Name: \n Age: \n\n
\n
\n \n
\n User 1:
{{user1 | json}}
\n User 2:
{{user2 | json}}
\n Equal:
{{result}}
\n
\n
\n
\n \n angular.module('equalsExample', []).controller('ExampleController', ['$scope', function($scope) {\n $scope.user1 = {};\n $scope.user2 = {};\n $scope.compare = function() {\n $scope.result = angular.equals($scope.user1, $scope.user2);\n };\n }]);\n \n
\n */\nfunction equals(o1, o2) {\n if (o1 === o2) return true;\n if (o1 === null || o2 === null) return false;\n // eslint-disable-next-line no-self-compare\n if (o1 !== o1 && o2 !== o2) return true; // NaN === NaN\n var t1 = typeof o1, t2 = typeof o2, length, key, keySet;\n if (t1 === t2 && t1 === 'object') {\n if (isArray(o1)) {\n if (!isArray(o2)) return false;\n if ((length = o1.length) === o2.length) {\n for (key = 0; key < length; key++) {\n if (!equals(o1[key], o2[key])) return false;\n }\n return true;\n }\n } else if (isDate(o1)) {\n if (!isDate(o2)) return false;\n return equals(o1.getTime(), o2.getTime());\n } else if (isRegExp(o1)) {\n if (!isRegExp(o2)) return false;\n return o1.toString() === o2.toString();\n } else {\n if (isScope(o1) || isScope(o2) || isWindow(o1) || isWindow(o2) ||\n isArray(o2) || isDate(o2) || isRegExp(o2)) return false;\n keySet = createMap();\n for (key in o1) {\n if (key.charAt(0) === '$' || isFunction(o1[key])) continue;\n if (!equals(o1[key], o2[key])) return false;\n keySet[key] = true;\n }\n for (key in o2) {\n if (!(key in keySet) &&\n key.charAt(0) !== '$' &&\n isDefined(o2[key]) &&\n !isFunction(o2[key])) return false;\n }\n return true;\n }\n }\n return false;\n}\n\nvar csp = function() {\n if (!isDefined(csp.rules)) {\n\n\n var ngCspElement = (window.document.querySelector('[ng-csp]') ||\n window.document.querySelector('[data-ng-csp]'));\n\n if (ngCspElement) {\n var ngCspAttribute = ngCspElement.getAttribute('ng-csp') ||\n ngCspElement.getAttribute('data-ng-csp');\n csp.rules = {\n noUnsafeEval: !ngCspAttribute || (ngCspAttribute.indexOf('no-unsafe-eval') !== -1),\n noInlineStyle: !ngCspAttribute || (ngCspAttribute.indexOf('no-inline-style') !== -1)\n };\n } else {\n csp.rules = {\n noUnsafeEval: noUnsafeEval(),\n noInlineStyle: false\n };\n }\n }\n\n return csp.rules;\n\n function noUnsafeEval() {\n try {\n // eslint-disable-next-line no-new, no-new-func\n new Function('');\n return false;\n } catch (e) {\n return true;\n }\n }\n};\n\n/**\n * @ngdoc directive\n * @module ng\n * @name ngJq\n *\n * @element ANY\n * @param {string=} ngJq the name of the library available under `window`\n * to be used for angular.element\n * @description\n * Use this directive to force the angular.element library. This should be\n * used to force either jqLite by leaving ng-jq blank or setting the name of\n * the jquery variable under window (eg. jQuery).\n *\n * Since angular looks for this directive when it is loaded (doesn't wait for the\n * DOMContentLoaded event), it must be placed on an element that comes before the script\n * which loads angular. Also, only the first instance of `ng-jq` will be used and all\n * others ignored.\n *\n * @example\n * This example shows how to force jqLite using the `ngJq` directive to the `html` tag.\n ```html\n \n \n ...\n ...\n \n ```\n * @example\n * This example shows how to use a jQuery based library of a different name.\n * The library name must be available at the top most 'window'.\n ```html\n \n \n ...\n ...\n \n ```\n */\nvar jq = function() {\n if (isDefined(jq.name_)) return jq.name_;\n var el;\n var i, ii = ngAttrPrefixes.length, prefix, name;\n for (i = 0; i < ii; ++i) {\n prefix = ngAttrPrefixes[i];\n el = window.document.querySelector('[' + prefix.replace(':', '\\\\:') + 'jq]');\n if (el) {\n name = el.getAttribute(prefix + 'jq');\n break;\n }\n }\n\n return (jq.name_ = name);\n};\n\nfunction concat(array1, array2, index) {\n return array1.concat(slice.call(array2, index));\n}\n\nfunction sliceArgs(args, startIndex) {\n return slice.call(args, startIndex || 0);\n}\n\n\n/**\n * @ngdoc function\n * @name angular.bind\n * @module ng\n * @kind function\n *\n * @description\n * Returns a function which calls function `fn` bound to `self` (`self` becomes the `this` for\n * `fn`). You can supply optional `args` that are prebound to the function. This feature is also\n * known as [partial application](http://en.wikipedia.org/wiki/Partial_application), as\n * distinguished from [function currying](http://en.wikipedia.org/wiki/Currying#Contrast_with_partial_function_application).\n *\n * @param {Object} self Context which `fn` should be evaluated in.\n * @param {function()} fn Function to be bound.\n * @param {...*} args Optional arguments to be prebound to the `fn` function call.\n * @returns {function()} Function that wraps the `fn` with all the specified bindings.\n */\nfunction bind(self, fn) {\n var curryArgs = arguments.length > 2 ? sliceArgs(arguments, 2) : [];\n if (isFunction(fn) && !(fn instanceof RegExp)) {\n return curryArgs.length\n ? function() {\n return arguments.length\n ? fn.apply(self, concat(curryArgs, arguments, 0))\n : fn.apply(self, curryArgs);\n }\n : function() {\n return arguments.length\n ? fn.apply(self, arguments)\n : fn.call(self);\n };\n } else {\n // In IE, native methods are not functions so they cannot be bound (note: they don't need to be).\n return fn;\n }\n}\n\n\nfunction toJsonReplacer(key, value) {\n var val = value;\n\n if (typeof key === 'string' && key.charAt(0) === '$' && key.charAt(1) === '$') {\n val = undefined;\n } else if (isWindow(value)) {\n val = '$WINDOW';\n } else if (value && window.document === value) {\n val = '$DOCUMENT';\n } else if (isScope(value)) {\n val = '$SCOPE';\n }\n\n return val;\n}\n\n\n/**\n * @ngdoc function\n * @name angular.toJson\n * @module ng\n * @kind function\n *\n * @description\n * Serializes input into a JSON-formatted string. Properties with leading $$ characters will be\n * stripped since angular uses this notation internally.\n *\n * @param {Object|Array|Date|string|number|boolean} obj Input to be serialized into JSON.\n * @param {boolean|number} [pretty=2] If set to true, the JSON output will contain newlines and whitespace.\n * If set to an integer, the JSON output will contain that many spaces per indentation.\n * @returns {string|undefined} JSON-ified string representing `obj`.\n * @knownIssue\n *\n * The Safari browser throws a `RangeError` instead of returning `null` when it tries to stringify a `Date`\n * object with an invalid date value. The only reliable way to prevent this is to monkeypatch the\n * `Date.prototype.toJSON` method as follows:\n *\n * ```\n * var _DatetoJSON = Date.prototype.toJSON;\n * Date.prototype.toJSON = function() {\n * try {\n * return _DatetoJSON.call(this);\n * } catch(e) {\n * if (e instanceof RangeError) {\n * return null;\n * }\n * throw e;\n * }\n * };\n * ```\n *\n * See https://github.com/angular/angular.js/pull/14221 for more information.\n */\nfunction toJson(obj, pretty) {\n if (isUndefined(obj)) return undefined;\n if (!isNumber(pretty)) {\n pretty = pretty ? 2 : null;\n }\n return JSON.stringify(obj, toJsonReplacer, pretty);\n}\n\n\n/**\n * @ngdoc function\n * @name angular.fromJson\n * @module ng\n * @kind function\n *\n * @description\n * Deserializes a JSON string.\n *\n * @param {string} json JSON string to deserialize.\n * @returns {Object|Array|string|number} Deserialized JSON string.\n */\nfunction fromJson(json) {\n return isString(json)\n ? JSON.parse(json)\n : json;\n}\n\n\nvar ALL_COLONS = /:/g;\nfunction timezoneToOffset(timezone, fallback) {\n // Support: IE 9-11 only, Edge 13-14+\n // IE/Edge do not \"understand\" colon (`:`) in timezone\n timezone = timezone.replace(ALL_COLONS, '');\n var requestedTimezoneOffset = Date.parse('Jan 01, 1970 00:00:00 ' + timezone) / 60000;\n return isNumberNaN(requestedTimezoneOffset) ? fallback : requestedTimezoneOffset;\n}\n\n\nfunction addDateMinutes(date, minutes) {\n date = new Date(date.getTime());\n date.setMinutes(date.getMinutes() + minutes);\n return date;\n}\n\n\nfunction convertTimezoneToLocal(date, timezone, reverse) {\n reverse = reverse ? -1 : 1;\n var dateTimezoneOffset = date.getTimezoneOffset();\n var timezoneOffset = timezoneToOffset(timezone, dateTimezoneOffset);\n return addDateMinutes(date, reverse * (timezoneOffset - dateTimezoneOffset));\n}\n\n\n/**\n * @returns {string} Returns the string representation of the element.\n */\nfunction startingTag(element) {\n element = jqLite(element).clone();\n try {\n // turns out IE does not let you set .html() on elements which\n // are not allowed to have children. So we just ignore it.\n element.empty();\n } catch (e) { /* empty */ }\n var elemHtml = jqLite('
').append(element).html();\n try {\n return element[0].nodeType === NODE_TYPE_TEXT ? lowercase(elemHtml) :\n elemHtml.\n match(/^(<[^>]+>)/)[1].\n replace(/^<([\\w-]+)/, function(match, nodeName) {return '<' + lowercase(nodeName);});\n } catch (e) {\n return lowercase(elemHtml);\n }\n\n}\n\n\n/////////////////////////////////////////////////\n\n/**\n * Tries to decode the URI component without throwing an exception.\n *\n * @private\n * @param str value potential URI component to check.\n * @returns {boolean} True if `value` can be decoded\n * with the decodeURIComponent function.\n */\nfunction tryDecodeURIComponent(value) {\n try {\n return decodeURIComponent(value);\n } catch (e) {\n // Ignore any invalid uri component.\n }\n}\n\n\n/**\n * Parses an escaped url query string into key-value pairs.\n * @returns {Object.}\n */\nfunction parseKeyValue(/**string*/keyValue) {\n var obj = {};\n forEach((keyValue || '').split('&'), function(keyValue) {\n var splitPoint, key, val;\n if (keyValue) {\n key = keyValue = keyValue.replace(/\\+/g,'%20');\n splitPoint = keyValue.indexOf('=');\n if (splitPoint !== -1) {\n key = keyValue.substring(0, splitPoint);\n val = keyValue.substring(splitPoint + 1);\n }\n key = tryDecodeURIComponent(key);\n if (isDefined(key)) {\n val = isDefined(val) ? tryDecodeURIComponent(val) : true;\n if (!hasOwnProperty.call(obj, key)) {\n obj[key] = val;\n } else if (isArray(obj[key])) {\n obj[key].push(val);\n } else {\n obj[key] = [obj[key],val];\n }\n }\n }\n });\n return obj;\n}\n\nfunction toKeyValue(obj) {\n var parts = [];\n forEach(obj, function(value, key) {\n if (isArray(value)) {\n forEach(value, function(arrayValue) {\n parts.push(encodeUriQuery(key, true) +\n (arrayValue === true ? '' : '=' + encodeUriQuery(arrayValue, true)));\n });\n } else {\n parts.push(encodeUriQuery(key, true) +\n (value === true ? '' : '=' + encodeUriQuery(value, true)));\n }\n });\n return parts.length ? parts.join('&') : '';\n}\n\n\n/**\n * We need our custom method because encodeURIComponent is too aggressive and doesn't follow\n * http://www.ietf.org/rfc/rfc3986.txt with regards to the character set (pchar) allowed in path\n * segments:\n * segment = *pchar\n * pchar = unreserved / pct-encoded / sub-delims / \":\" / \"@\"\n * pct-encoded = \"%\" HEXDIG HEXDIG\n * unreserved = ALPHA / DIGIT / \"-\" / \".\" / \"_\" / \"~\"\n * sub-delims = \"!\" / \"$\" / \"&\" / \"'\" / \"(\" / \")\"\n * / \"*\" / \"+\" / \",\" / \";\" / \"=\"\n */\nfunction encodeUriSegment(val) {\n return encodeUriQuery(val, true).\n replace(/%26/gi, '&').\n replace(/%3D/gi, '=').\n replace(/%2B/gi, '+');\n}\n\n\n/**\n * This method is intended for encoding *key* or *value* parts of query component. We need a custom\n * method because encodeURIComponent is too aggressive and encodes stuff that doesn't have to be\n * encoded per http://tools.ietf.org/html/rfc3986:\n * query = *( pchar / \"/\" / \"?\" )\n * pchar = unreserved / pct-encoded / sub-delims / \":\" / \"@\"\n * unreserved = ALPHA / DIGIT / \"-\" / \".\" / \"_\" / \"~\"\n * pct-encoded = \"%\" HEXDIG HEXDIG\n * sub-delims = \"!\" / \"$\" / \"&\" / \"'\" / \"(\" / \")\"\n * / \"*\" / \"+\" / \",\" / \";\" / \"=\"\n */\nfunction encodeUriQuery(val, pctEncodeSpaces) {\n return encodeURIComponent(val).\n replace(/%40/gi, '@').\n replace(/%3A/gi, ':').\n replace(/%24/g, '$').\n replace(/%2C/gi, ',').\n replace(/%3B/gi, ';').\n replace(/%20/g, (pctEncodeSpaces ? '%20' : '+'));\n}\n\nvar ngAttrPrefixes = ['ng-', 'data-ng-', 'ng:', 'x-ng-'];\n\nfunction getNgAttribute(element, ngAttr) {\n var attr, i, ii = ngAttrPrefixes.length;\n for (i = 0; i < ii; ++i) {\n attr = ngAttrPrefixes[i] + ngAttr;\n if (isString(attr = element.getAttribute(attr))) {\n return attr;\n }\n }\n return null;\n}\n\nfunction allowAutoBootstrap(document) {\n if (!document.currentScript) {\n return true;\n }\n var src = document.currentScript.getAttribute('src');\n var link = document.createElement('a');\n link.href = src;\n if (document.location.origin === link.origin) {\n // Same-origin resources are always allowed, even for non-whitelisted schemes.\n return true;\n }\n // Disabled bootstrapping unless angular.js was loaded from a known scheme used on the web.\n // This is to prevent angular.js bundled with browser extensions from being used to bypass the\n // content security policy in web pages and other browser extensions.\n switch (link.protocol) {\n case 'http:':\n case 'https:':\n case 'ftp:':\n case 'blob:':\n case 'file:':\n case 'data:':\n return true;\n default:\n return false;\n }\n}\n\n// Cached as it has to run during loading so that document.currentScript is available.\nvar isAutoBootstrapAllowed = allowAutoBootstrap(window.document);\n\n/**\n * @ngdoc directive\n * @name ngApp\n * @module ng\n *\n * @element ANY\n * @param {angular.Module} ngApp an optional application\n * {@link angular.module module} name to load.\n * @param {boolean=} ngStrictDi if this attribute is present on the app element, the injector will be\n * created in \"strict-di\" mode. This means that the application will fail to invoke functions which\n * do not use explicit function annotation (and are thus unsuitable for minification), as described\n * in {@link guide/di the Dependency Injection guide}, and useful debugging info will assist in\n * tracking down the root of these bugs.\n *\n * @description\n *\n * Use this directive to **auto-bootstrap** an AngularJS application. The `ngApp` directive\n * designates the **root element** of the application and is typically placed near the root element\n * of the page - e.g. on the `` or `` tags.\n *\n * There are a few things to keep in mind when using `ngApp`:\n * - only one AngularJS application can be auto-bootstrapped per HTML document. The first `ngApp`\n * found in the document will be used to define the root element to auto-bootstrap as an\n * application. To run multiple applications in an HTML document you must manually bootstrap them using\n * {@link angular.bootstrap} instead.\n * - AngularJS applications cannot be nested within each other.\n * - Do not use a directive that uses {@link ng.$compile#transclusion transclusion} on the same element as `ngApp`.\n * This includes directives such as {@link ng.ngIf `ngIf`}, {@link ng.ngInclude `ngInclude`} and\n * {@link ngRoute.ngView `ngView`}.\n * Doing this misplaces the app {@link ng.$rootElement `$rootElement`} and the app's {@link auto.$injector injector},\n * causing animations to stop working and making the injector inaccessible from outside the app.\n *\n * You can specify an **AngularJS module** to be used as the root module for the application. This\n * module will be loaded into the {@link auto.$injector} when the application is bootstrapped. It\n * should contain the application code needed or have dependencies on other modules that will\n * contain the code. See {@link angular.module} for more information.\n *\n * In the example below if the `ngApp` directive were not placed on the `html` element then the\n * document would not be compiled, the `AppController` would not be instantiated and the `{{ a+b }}`\n * would not be resolved to `3`.\n *\n * `ngApp` is the easiest, and most common way to bootstrap an application.\n *\n \n \n
\n I can add: {{a}} + {{b}} = {{ a+b }}\n
\n
\n \n angular.module('ngAppDemo', []).controller('ngAppDemoController', function($scope) {\n $scope.a = 1;\n $scope.b = 2;\n });\n \n
\n *\n * Using `ngStrictDi`, you would see something like this:\n *\n \n \n
\n
\n I can add: {{a}} + {{b}} = {{ a+b }}\n\n

This renders because the controller does not fail to\n instantiate, by using explicit annotation style (see\n script.js for details)\n

\n
\n\n
\n Name:
\n Hello, {{name}}!\n\n

This renders because the controller does not fail to\n instantiate, by using explicit annotation style\n (see script.js for details)\n

\n
\n\n
\n I can add: {{a}} + {{b}} = {{ a+b }}\n\n

The controller could not be instantiated, due to relying\n on automatic function annotations (which are disabled in\n strict mode). As such, the content of this section is not\n interpolated, and there should be an error in your web console.\n

\n
\n
\n
\n \n angular.module('ngAppStrictDemo', [])\n // BadController will fail to instantiate, due to relying on automatic function annotation,\n // rather than an explicit annotation\n .controller('BadController', function($scope) {\n $scope.a = 1;\n $scope.b = 2;\n })\n // Unlike BadController, GoodController1 and GoodController2 will not fail to be instantiated,\n // due to using explicit annotations using the array style and $inject property, respectively.\n .controller('GoodController1', ['$scope', function($scope) {\n $scope.a = 1;\n $scope.b = 2;\n }])\n .controller('GoodController2', GoodController2);\n function GoodController2($scope) {\n $scope.name = 'World';\n }\n GoodController2.$inject = ['$scope'];\n \n \n div[ng-controller] {\n margin-bottom: 1em;\n -webkit-border-radius: 4px;\n border-radius: 4px;\n border: 1px solid;\n padding: .5em;\n }\n div[ng-controller^=Good] {\n border-color: #d6e9c6;\n background-color: #dff0d8;\n color: #3c763d;\n }\n div[ng-controller^=Bad] {\n border-color: #ebccd1;\n background-color: #f2dede;\n color: #a94442;\n margin-bottom: 0;\n }\n \n
\n */\nfunction angularInit(element, bootstrap) {\n var appElement,\n module,\n config = {};\n\n // The element `element` has priority over any other element.\n forEach(ngAttrPrefixes, function(prefix) {\n var name = prefix + 'app';\n\n if (!appElement && element.hasAttribute && element.hasAttribute(name)) {\n appElement = element;\n module = element.getAttribute(name);\n }\n });\n forEach(ngAttrPrefixes, function(prefix) {\n var name = prefix + 'app';\n var candidate;\n\n if (!appElement && (candidate = element.querySelector('[' + name.replace(':', '\\\\:') + ']'))) {\n appElement = candidate;\n module = candidate.getAttribute(name);\n }\n });\n if (appElement) {\n if (!isAutoBootstrapAllowed) {\n window.console.error('Angular: disabling automatic bootstrap. \n * \n * \n * \n * ```\n *\n * @param {DOMElement} element DOM element which is the root of angular application.\n * @param {Array=} modules an array of modules to load into the application.\n * Each item in the array should be the name of a predefined module or a (DI annotated)\n * function that will be invoked by the injector as a `config` block.\n * See: {@link angular.module modules}\n * @param {Object=} config an object for defining configuration options for the application. The\n * following keys are supported:\n *\n * * `strictDi` - disable automatic function annotation for the application. This is meant to\n * assist in finding bugs which break minified code. Defaults to `false`.\n *\n * @returns {auto.$injector} Returns the newly created injector for this app.\n */\nfunction bootstrap(element, modules, config) {\n if (!isObject(config)) config = {};\n var defaultConfig = {\n strictDi: false\n };\n config = extend(defaultConfig, config);\n var doBootstrap = function() {\n element = jqLite(element);\n\n if (element.injector()) {\n var tag = (element[0] === window.document) ? 'document' : startingTag(element);\n // Encode angle brackets to prevent input from being sanitized to empty string #8683.\n throw ngMinErr(\n 'btstrpd',\n 'App already bootstrapped with this element \\'{0}\\'',\n tag.replace(//,'>'));\n }\n\n modules = modules || [];\n modules.unshift(['$provide', function($provide) {\n $provide.value('$rootElement', element);\n }]);\n\n if (config.debugInfoEnabled) {\n // Pushing so that this overrides `debugInfoEnabled` setting defined in user's `modules`.\n modules.push(['$compileProvider', function($compileProvider) {\n $compileProvider.debugInfoEnabled(true);\n }]);\n }\n\n modules.unshift('ng');\n var injector = createInjector(modules, config.strictDi);\n injector.invoke(['$rootScope', '$rootElement', '$compile', '$injector',\n function bootstrapApply(scope, element, compile, injector) {\n scope.$apply(function() {\n element.data('$injector', injector);\n compile(element)(scope);\n });\n }]\n );\n return injector;\n };\n\n var NG_ENABLE_DEBUG_INFO = /^NG_ENABLE_DEBUG_INFO!/;\n var NG_DEFER_BOOTSTRAP = /^NG_DEFER_BOOTSTRAP!/;\n\n if (window && NG_ENABLE_DEBUG_INFO.test(window.name)) {\n config.debugInfoEnabled = true;\n window.name = window.name.replace(NG_ENABLE_DEBUG_INFO, '');\n }\n\n if (window && !NG_DEFER_BOOTSTRAP.test(window.name)) {\n return doBootstrap();\n }\n\n window.name = window.name.replace(NG_DEFER_BOOTSTRAP, '');\n angular.resumeBootstrap = function(extraModules) {\n forEach(extraModules, function(module) {\n modules.push(module);\n });\n return doBootstrap();\n };\n\n if (isFunction(angular.resumeDeferredBootstrap)) {\n angular.resumeDeferredBootstrap();\n }\n}\n\n/**\n * @ngdoc function\n * @name angular.reloadWithDebugInfo\n * @module ng\n * @description\n * Use this function to reload the current application with debug information turned on.\n * This takes precedence over a call to `$compileProvider.debugInfoEnabled(false)`.\n *\n * See {@link ng.$compileProvider#debugInfoEnabled} for more.\n */\nfunction reloadWithDebugInfo() {\n window.name = 'NG_ENABLE_DEBUG_INFO!' + window.name;\n window.location.reload();\n}\n\n/**\n * @name angular.getTestability\n * @module ng\n * @description\n * Get the testability service for the instance of Angular on the given\n * element.\n * @param {DOMElement} element DOM element which is the root of angular application.\n */\nfunction getTestability(rootElement) {\n var injector = angular.element(rootElement).injector();\n if (!injector) {\n throw ngMinErr('test',\n 'no injector found for element argument to getTestability');\n }\n return injector.get('$$testability');\n}\n\nvar SNAKE_CASE_REGEXP = /[A-Z]/g;\nfunction snake_case(name, separator) {\n separator = separator || '_';\n return name.replace(SNAKE_CASE_REGEXP, function(letter, pos) {\n return (pos ? separator : '') + letter.toLowerCase();\n });\n}\n\nvar bindJQueryFired = false;\nfunction bindJQuery() {\n var originalCleanData;\n\n if (bindJQueryFired) {\n return;\n }\n\n // bind to jQuery if present;\n var jqName = jq();\n jQuery = isUndefined(jqName) ? __webpack_provided_window_dot_jQuery : // use jQuery (if present)\n !jqName ? undefined : // use jqLite\n window[jqName]; // use jQuery specified by `ngJq`\n\n // Use jQuery if it exists with proper functionality, otherwise default to us.\n // Angular 1.2+ requires jQuery 1.7+ for on()/off() support.\n // Angular 1.3+ technically requires at least jQuery 2.1+ but it may work with older\n // versions. It will not work for sure with jQuery <1.7, though.\n if (jQuery && jQuery.fn.on) {\n jqLite = jQuery;\n extend(jQuery.fn, {\n scope: JQLitePrototype.scope,\n isolateScope: JQLitePrototype.isolateScope,\n controller: JQLitePrototype.controller,\n injector: JQLitePrototype.injector,\n inheritedData: JQLitePrototype.inheritedData\n });\n\n // All nodes removed from the DOM via various jQuery APIs like .remove()\n // are passed through jQuery.cleanData. Monkey-patch this method to fire\n // the $destroy event on all removed nodes.\n originalCleanData = jQuery.cleanData;\n jQuery.cleanData = function(elems) {\n var events;\n for (var i = 0, elem; (elem = elems[i]) != null; i++) {\n events = jQuery._data(elem, 'events');\n if (events && events.$destroy) {\n jQuery(elem).triggerHandler('$destroy');\n }\n }\n originalCleanData(elems);\n };\n } else {\n jqLite = JQLite;\n }\n\n angular.element = jqLite;\n\n // Prevent double-proxying.\n bindJQueryFired = true;\n}\n\n/**\n * throw error if the argument is falsy.\n */\nfunction assertArg(arg, name, reason) {\n if (!arg) {\n throw ngMinErr('areq', 'Argument \\'{0}\\' is {1}', (name || '?'), (reason || 'required'));\n }\n return arg;\n}\n\nfunction assertArgFn(arg, name, acceptArrayAnnotation) {\n if (acceptArrayAnnotation && isArray(arg)) {\n arg = arg[arg.length - 1];\n }\n\n assertArg(isFunction(arg), name, 'not a function, got ' +\n (arg && typeof arg === 'object' ? arg.constructor.name || 'Object' : typeof arg));\n return arg;\n}\n\n/**\n * throw error if the name given is hasOwnProperty\n * @param {String} name the name to test\n * @param {String} context the context in which the name is used, such as module or directive\n */\nfunction assertNotHasOwnProperty(name, context) {\n if (name === 'hasOwnProperty') {\n throw ngMinErr('badname', 'hasOwnProperty is not a valid {0} name', context);\n }\n}\n\n/**\n * Return the value accessible from the object by path. Any undefined traversals are ignored\n * @param {Object} obj starting object\n * @param {String} path path to traverse\n * @param {boolean} [bindFnToScope=true]\n * @returns {Object} value as accessible by path\n */\n//TODO(misko): this function needs to be removed\nfunction getter(obj, path, bindFnToScope) {\n if (!path) return obj;\n var keys = path.split('.');\n var key;\n var lastInstance = obj;\n var len = keys.length;\n\n for (var i = 0; i < len; i++) {\n key = keys[i];\n if (obj) {\n obj = (lastInstance = obj)[key];\n }\n }\n if (!bindFnToScope && isFunction(obj)) {\n return bind(lastInstance, obj);\n }\n return obj;\n}\n\n/**\n * Return the DOM siblings between the first and last node in the given array.\n * @param {Array} array like object\n * @returns {Array} the inputted object or a jqLite collection containing the nodes\n */\nfunction getBlockNodes(nodes) {\n // TODO(perf): update `nodes` instead of creating a new object?\n var node = nodes[0];\n var endNode = nodes[nodes.length - 1];\n var blockNodes;\n\n for (var i = 1; node !== endNode && (node = node.nextSibling); i++) {\n if (blockNodes || nodes[i] !== node) {\n if (!blockNodes) {\n blockNodes = jqLite(slice.call(nodes, 0, i));\n }\n blockNodes.push(node);\n }\n }\n\n return blockNodes || nodes;\n}\n\n\n/**\n * Creates a new object without a prototype. This object is useful for lookup without having to\n * guard against prototypically inherited properties via hasOwnProperty.\n *\n * Related micro-benchmarks:\n * - http://jsperf.com/object-create2\n * - http://jsperf.com/proto-map-lookup/2\n * - http://jsperf.com/for-in-vs-object-keys2\n *\n * @returns {Object}\n */\nfunction createMap() {\n return Object.create(null);\n}\n\nfunction stringify(value) {\n if (value == null) { // null || undefined\n return '';\n }\n switch (typeof value) {\n case 'string':\n break;\n case 'number':\n value = '' + value;\n break;\n default:\n if (hasCustomToString(value) && !isArray(value) && !isDate(value)) {\n value = value.toString();\n } else {\n value = toJson(value);\n }\n }\n\n return value;\n}\n\nvar NODE_TYPE_ELEMENT = 1;\nvar NODE_TYPE_ATTRIBUTE = 2;\nvar NODE_TYPE_TEXT = 3;\nvar NODE_TYPE_COMMENT = 8;\nvar NODE_TYPE_DOCUMENT = 9;\nvar NODE_TYPE_DOCUMENT_FRAGMENT = 11;\n\n/**\n * @ngdoc type\n * @name angular.Module\n * @module ng\n * @description\n *\n * Interface for configuring angular {@link angular.module modules}.\n */\n\nfunction setupModuleLoader(window) {\n\n var $injectorMinErr = minErr('$injector');\n var ngMinErr = minErr('ng');\n\n function ensure(obj, name, factory) {\n return obj[name] || (obj[name] = factory());\n }\n\n var angular = ensure(window, 'angular', Object);\n\n // We need to expose `angular.$$minErr` to modules such as `ngResource` that reference it during bootstrap\n angular.$$minErr = angular.$$minErr || minErr;\n\n return ensure(angular, 'module', function() {\n /** @type {Object.} */\n var modules = {};\n\n /**\n * @ngdoc function\n * @name angular.module\n * @module ng\n * @description\n *\n * The `angular.module` is a global place for creating, registering and retrieving Angular\n * modules.\n * All modules (angular core or 3rd party) that should be available to an application must be\n * registered using this mechanism.\n *\n * Passing one argument retrieves an existing {@link angular.Module},\n * whereas passing more than one argument creates a new {@link angular.Module}\n *\n *\n * # Module\n *\n * A module is a collection of services, directives, controllers, filters, and configuration information.\n * `angular.module` is used to configure the {@link auto.$injector $injector}.\n *\n * ```js\n * // Create a new module\n * var myModule = angular.module('myModule', []);\n *\n * // register a new service\n * myModule.value('appName', 'MyCoolApp');\n *\n * // configure existing services inside initialization blocks.\n * myModule.config(['$locationProvider', function($locationProvider) {\n * // Configure existing providers\n * $locationProvider.hashPrefix('!');\n * }]);\n * ```\n *\n * Then you can create an injector and load your modules like this:\n *\n * ```js\n * var injector = angular.injector(['ng', 'myModule'])\n * ```\n *\n * However it's more likely that you'll just use\n * {@link ng.directive:ngApp ngApp} or\n * {@link angular.bootstrap} to simplify this process for you.\n *\n * @param {!string} name The name of the module to create or retrieve.\n * @param {!Array.=} requires If specified then new module is being created. If\n * unspecified then the module is being retrieved for further configuration.\n * @param {Function=} configFn Optional configuration function for the module. Same as\n * {@link angular.Module#config Module#config()}.\n * @returns {angular.Module} new module with the {@link angular.Module} api.\n */\n return function module(name, requires, configFn) {\n var assertNotHasOwnProperty = function(name, context) {\n if (name === 'hasOwnProperty') {\n throw ngMinErr('badname', 'hasOwnProperty is not a valid {0} name', context);\n }\n };\n\n assertNotHasOwnProperty(name, 'module');\n if (requires && modules.hasOwnProperty(name)) {\n modules[name] = null;\n }\n return ensure(modules, name, function() {\n if (!requires) {\n throw $injectorMinErr('nomod', 'Module \\'{0}\\' is not available! You either misspelled ' +\n 'the module name or forgot to load it. If registering a module ensure that you ' +\n 'specify the dependencies as the second argument.', name);\n }\n\n /** @type {!Array.>} */\n var invokeQueue = [];\n\n /** @type {!Array.} */\n var configBlocks = [];\n\n /** @type {!Array.} */\n var runBlocks = [];\n\n var config = invokeLater('$injector', 'invoke', 'push', configBlocks);\n\n /** @type {angular.Module} */\n var moduleInstance = {\n // Private state\n _invokeQueue: invokeQueue,\n _configBlocks: configBlocks,\n _runBlocks: runBlocks,\n\n /**\n * @ngdoc property\n * @name angular.Module#requires\n * @module ng\n *\n * @description\n * Holds the list of modules which the injector will load before the current module is\n * loaded.\n */\n requires: requires,\n\n /**\n * @ngdoc property\n * @name angular.Module#name\n * @module ng\n *\n * @description\n * Name of the module.\n */\n name: name,\n\n\n /**\n * @ngdoc method\n * @name angular.Module#provider\n * @module ng\n * @param {string} name service name\n * @param {Function} providerType Construction function for creating new instance of the\n * service.\n * @description\n * See {@link auto.$provide#provider $provide.provider()}.\n */\n provider: invokeLaterAndSetModuleName('$provide', 'provider'),\n\n /**\n * @ngdoc method\n * @name angular.Module#factory\n * @module ng\n * @param {string} name service name\n * @param {Function} providerFunction Function for creating new instance of the service.\n * @description\n * See {@link auto.$provide#factory $provide.factory()}.\n */\n factory: invokeLaterAndSetModuleName('$provide', 'factory'),\n\n /**\n * @ngdoc method\n * @name angular.Module#service\n * @module ng\n * @param {string} name service name\n * @param {Function} constructor A constructor function that will be instantiated.\n * @description\n * See {@link auto.$provide#service $provide.service()}.\n */\n service: invokeLaterAndSetModuleName('$provide', 'service'),\n\n /**\n * @ngdoc method\n * @name angular.Module#value\n * @module ng\n * @param {string} name service name\n * @param {*} object Service instance object.\n * @description\n * See {@link auto.$provide#value $provide.value()}.\n */\n value: invokeLater('$provide', 'value'),\n\n /**\n * @ngdoc method\n * @name angular.Module#constant\n * @module ng\n * @param {string} name constant name\n * @param {*} object Constant value.\n * @description\n * Because the constants are fixed, they get applied before other provide methods.\n * See {@link auto.$provide#constant $provide.constant()}.\n */\n constant: invokeLater('$provide', 'constant', 'unshift'),\n\n /**\n * @ngdoc method\n * @name angular.Module#decorator\n * @module ng\n * @param {string} name The name of the service to decorate.\n * @param {Function} decorFn This function will be invoked when the service needs to be\n * instantiated and should return the decorated service instance.\n * @description\n * See {@link auto.$provide#decorator $provide.decorator()}.\n */\n decorator: invokeLaterAndSetModuleName('$provide', 'decorator', configBlocks),\n\n /**\n * @ngdoc method\n * @name angular.Module#animation\n * @module ng\n * @param {string} name animation name\n * @param {Function} animationFactory Factory function for creating new instance of an\n * animation.\n * @description\n *\n * **NOTE**: animations take effect only if the **ngAnimate** module is loaded.\n *\n *\n * Defines an animation hook that can be later used with\n * {@link $animate $animate} service and directives that use this service.\n *\n * ```js\n * module.animation('.animation-name', function($inject1, $inject2) {\n * return {\n * eventName : function(element, done) {\n * //code to run the animation\n * //once complete, then run done()\n * return function cancellationFunction(element) {\n * //code to cancel the animation\n * }\n * }\n * }\n * })\n * ```\n *\n * See {@link ng.$animateProvider#register $animateProvider.register()} and\n * {@link ngAnimate ngAnimate module} for more information.\n */\n animation: invokeLaterAndSetModuleName('$animateProvider', 'register'),\n\n /**\n * @ngdoc method\n * @name angular.Module#filter\n * @module ng\n * @param {string} name Filter name - this must be a valid angular expression identifier\n * @param {Function} filterFactory Factory function for creating new instance of filter.\n * @description\n * See {@link ng.$filterProvider#register $filterProvider.register()}.\n *\n *
\n * **Note:** Filter names must be valid angular {@link expression} identifiers, such as `uppercase` or `orderBy`.\n * Names with special characters, such as hyphens and dots, are not allowed. If you wish to namespace\n * your filters, then you can use capitalization (`myappSubsectionFilterx`) or underscores\n * (`myapp_subsection_filterx`).\n *
\n */\n filter: invokeLaterAndSetModuleName('$filterProvider', 'register'),\n\n /**\n * @ngdoc method\n * @name angular.Module#controller\n * @module ng\n * @param {string|Object} name Controller name, or an object map of controllers where the\n * keys are the names and the values are the constructors.\n * @param {Function} constructor Controller constructor function.\n * @description\n * See {@link ng.$controllerProvider#register $controllerProvider.register()}.\n */\n controller: invokeLaterAndSetModuleName('$controllerProvider', 'register'),\n\n /**\n * @ngdoc method\n * @name angular.Module#directive\n * @module ng\n * @param {string|Object} name Directive name, or an object map of directives where the\n * keys are the names and the values are the factories.\n * @param {Function} directiveFactory Factory function for creating new instance of\n * directives.\n * @description\n * See {@link ng.$compileProvider#directive $compileProvider.directive()}.\n */\n directive: invokeLaterAndSetModuleName('$compileProvider', 'directive'),\n\n /**\n * @ngdoc method\n * @name angular.Module#component\n * @module ng\n * @param {string} name Name of the component in camel-case (i.e. myComp which will match as my-comp)\n * @param {Object} options Component definition object (a simplified\n * {@link ng.$compile#directive-definition-object directive definition object})\n *\n * @description\n * See {@link ng.$compileProvider#component $compileProvider.component()}.\n */\n component: invokeLaterAndSetModuleName('$compileProvider', 'component'),\n\n /**\n * @ngdoc method\n * @name angular.Module#config\n * @module ng\n * @param {Function} configFn Execute this function on module load. Useful for service\n * configuration.\n * @description\n * Use this method to register work which needs to be performed on module loading.\n * For more about how to configure services, see\n * {@link providers#provider-recipe Provider Recipe}.\n */\n config: config,\n\n /**\n * @ngdoc method\n * @name angular.Module#run\n * @module ng\n * @param {Function} initializationFn Execute this function after injector creation.\n * Useful for application initialization.\n * @description\n * Use this method to register work which should be performed when the injector is done\n * loading all modules.\n */\n run: function(block) {\n runBlocks.push(block);\n return this;\n }\n };\n\n if (configFn) {\n config(configFn);\n }\n\n return moduleInstance;\n\n /**\n * @param {string} provider\n * @param {string} method\n * @param {String=} insertMethod\n * @returns {angular.Module}\n */\n function invokeLater(provider, method, insertMethod, queue) {\n if (!queue) queue = invokeQueue;\n return function() {\n queue[insertMethod || 'push']([provider, method, arguments]);\n return moduleInstance;\n };\n }\n\n /**\n * @param {string} provider\n * @param {string} method\n * @returns {angular.Module}\n */\n function invokeLaterAndSetModuleName(provider, method, queue) {\n if (!queue) queue = invokeQueue;\n return function(recipeName, factoryFunction) {\n if (factoryFunction && isFunction(factoryFunction)) factoryFunction.$$moduleName = name;\n queue.push([provider, method, arguments]);\n return moduleInstance;\n };\n }\n });\n };\n });\n\n}\n\n/* global shallowCopy: true */\n\n/**\n * Creates a shallow copy of an object, an array or a primitive.\n *\n * Assumes that there are no proto properties for objects.\n */\nfunction shallowCopy(src, dst) {\n if (isArray(src)) {\n dst = dst || [];\n\n for (var i = 0, ii = src.length; i < ii; i++) {\n dst[i] = src[i];\n }\n } else if (isObject(src)) {\n dst = dst || {};\n\n for (var key in src) {\n if (!(key.charAt(0) === '$' && key.charAt(1) === '$')) {\n dst[key] = src[key];\n }\n }\n }\n\n return dst || src;\n}\n\n/* global toDebugString: true */\n\nfunction serializeObject(obj) {\n var seen = [];\n\n return JSON.stringify(obj, function(key, val) {\n val = toJsonReplacer(key, val);\n if (isObject(val)) {\n\n if (seen.indexOf(val) >= 0) return '...';\n\n seen.push(val);\n }\n return val;\n });\n}\n\nfunction toDebugString(obj) {\n if (typeof obj === 'function') {\n return obj.toString().replace(/ \\{[\\s\\S]*$/, '');\n } else if (isUndefined(obj)) {\n return 'undefined';\n } else if (typeof obj !== 'string') {\n return serializeObject(obj);\n }\n return obj;\n}\n\n/* global angularModule: true,\n version: true,\n\n $CompileProvider,\n\n htmlAnchorDirective,\n inputDirective,\n inputDirective,\n formDirective,\n scriptDirective,\n selectDirective,\n optionDirective,\n ngBindDirective,\n ngBindHtmlDirective,\n ngBindTemplateDirective,\n ngClassDirective,\n ngClassEvenDirective,\n ngClassOddDirective,\n ngCloakDirective,\n ngControllerDirective,\n ngFormDirective,\n ngHideDirective,\n ngIfDirective,\n ngIncludeDirective,\n ngIncludeFillContentDirective,\n ngInitDirective,\n ngNonBindableDirective,\n ngPluralizeDirective,\n ngRepeatDirective,\n ngShowDirective,\n ngStyleDirective,\n ngSwitchDirective,\n ngSwitchWhenDirective,\n ngSwitchDefaultDirective,\n ngOptionsDirective,\n ngTranscludeDirective,\n ngModelDirective,\n ngListDirective,\n ngChangeDirective,\n patternDirective,\n patternDirective,\n requiredDirective,\n requiredDirective,\n minlengthDirective,\n minlengthDirective,\n maxlengthDirective,\n maxlengthDirective,\n ngValueDirective,\n ngModelOptionsDirective,\n ngAttributeAliasDirectives,\n ngEventDirectives,\n\n $AnchorScrollProvider,\n $AnimateProvider,\n $CoreAnimateCssProvider,\n $$CoreAnimateJsProvider,\n $$CoreAnimateQueueProvider,\n $$AnimateRunnerFactoryProvider,\n $$AnimateAsyncRunFactoryProvider,\n $BrowserProvider,\n $CacheFactoryProvider,\n $ControllerProvider,\n $DateProvider,\n $DocumentProvider,\n $$IsDocumentHiddenProvider,\n $ExceptionHandlerProvider,\n $FilterProvider,\n $$ForceReflowProvider,\n $InterpolateProvider,\n $IntervalProvider,\n $$HashMapProvider,\n $HttpProvider,\n $HttpParamSerializerProvider,\n $HttpParamSerializerJQLikeProvider,\n $HttpBackendProvider,\n $xhrFactoryProvider,\n $jsonpCallbacksProvider,\n $LocationProvider,\n $LogProvider,\n $ParseProvider,\n $RootScopeProvider,\n $QProvider,\n $$QProvider,\n $$SanitizeUriProvider,\n $SceProvider,\n $SceDelegateProvider,\n $SnifferProvider,\n $TemplateCacheProvider,\n $TemplateRequestProvider,\n $$TestabilityProvider,\n $TimeoutProvider,\n $$RAFProvider,\n $WindowProvider,\n $$jqLiteProvider,\n $$CookieReaderProvider\n*/\n\n\n/**\n * @ngdoc object\n * @name angular.version\n * @module ng\n * @description\n * An object that contains information about the current AngularJS version.\n *\n * This object has the following properties:\n *\n * - `full` – `{string}` – Full version string, such as \"0.9.18\".\n * - `major` – `{number}` – Major version number, such as \"0\".\n * - `minor` – `{number}` – Minor version number, such as \"9\".\n * - `dot` – `{number}` – Dot version number, such as \"18\".\n * - `codeName` – `{string}` – Code name of the release, such as \"jiggling-armfat\".\n */\nvar version = {\n // These placeholder strings will be replaced by grunt's `build` task.\n // They need to be double- or single-quoted.\n full: '1.6.0',\n major: 1,\n minor: 6,\n dot: 0,\n codeName: 'rainbow-tsunami'\n};\n\n\nfunction publishExternalAPI(angular) {\n extend(angular, {\n 'bootstrap': bootstrap,\n 'copy': copy,\n 'extend': extend,\n 'merge': merge,\n 'equals': equals,\n 'element': jqLite,\n 'forEach': forEach,\n 'injector': createInjector,\n 'noop': noop,\n 'bind': bind,\n 'toJson': toJson,\n 'fromJson': fromJson,\n 'identity': identity,\n 'isUndefined': isUndefined,\n 'isDefined': isDefined,\n 'isString': isString,\n 'isFunction': isFunction,\n 'isObject': isObject,\n 'isNumber': isNumber,\n 'isElement': isElement,\n 'isArray': isArray,\n 'version': version,\n 'isDate': isDate,\n 'lowercase': lowercase,\n 'uppercase': uppercase,\n 'callbacks': {$$counter: 0},\n 'getTestability': getTestability,\n 'reloadWithDebugInfo': reloadWithDebugInfo,\n '$$minErr': minErr,\n '$$csp': csp,\n '$$encodeUriSegment': encodeUriSegment,\n '$$encodeUriQuery': encodeUriQuery,\n '$$stringify': stringify\n });\n\n angularModule = setupModuleLoader(window);\n\n angularModule('ng', ['ngLocale'], ['$provide',\n function ngModule($provide) {\n // $$sanitizeUriProvider needs to be before $compileProvider as it is used by it.\n $provide.provider({\n $$sanitizeUri: $$SanitizeUriProvider\n });\n $provide.provider('$compile', $CompileProvider).\n directive({\n a: htmlAnchorDirective,\n input: inputDirective,\n textarea: inputDirective,\n form: formDirective,\n script: scriptDirective,\n select: selectDirective,\n option: optionDirective,\n ngBind: ngBindDirective,\n ngBindHtml: ngBindHtmlDirective,\n ngBindTemplate: ngBindTemplateDirective,\n ngClass: ngClassDirective,\n ngClassEven: ngClassEvenDirective,\n ngClassOdd: ngClassOddDirective,\n ngCloak: ngCloakDirective,\n ngController: ngControllerDirective,\n ngForm: ngFormDirective,\n ngHide: ngHideDirective,\n ngIf: ngIfDirective,\n ngInclude: ngIncludeDirective,\n ngInit: ngInitDirective,\n ngNonBindable: ngNonBindableDirective,\n ngPluralize: ngPluralizeDirective,\n ngRepeat: ngRepeatDirective,\n ngShow: ngShowDirective,\n ngStyle: ngStyleDirective,\n ngSwitch: ngSwitchDirective,\n ngSwitchWhen: ngSwitchWhenDirective,\n ngSwitchDefault: ngSwitchDefaultDirective,\n ngOptions: ngOptionsDirective,\n ngTransclude: ngTranscludeDirective,\n ngModel: ngModelDirective,\n ngList: ngListDirective,\n ngChange: ngChangeDirective,\n pattern: patternDirective,\n ngPattern: patternDirective,\n required: requiredDirective,\n ngRequired: requiredDirective,\n minlength: minlengthDirective,\n ngMinlength: minlengthDirective,\n maxlength: maxlengthDirective,\n ngMaxlength: maxlengthDirective,\n ngValue: ngValueDirective,\n ngModelOptions: ngModelOptionsDirective\n }).\n directive({\n ngInclude: ngIncludeFillContentDirective\n }).\n directive(ngAttributeAliasDirectives).\n directive(ngEventDirectives);\n $provide.provider({\n $anchorScroll: $AnchorScrollProvider,\n $animate: $AnimateProvider,\n $animateCss: $CoreAnimateCssProvider,\n $$animateJs: $$CoreAnimateJsProvider,\n $$animateQueue: $$CoreAnimateQueueProvider,\n $$AnimateRunner: $$AnimateRunnerFactoryProvider,\n $$animateAsyncRun: $$AnimateAsyncRunFactoryProvider,\n $browser: $BrowserProvider,\n $cacheFactory: $CacheFactoryProvider,\n $controller: $ControllerProvider,\n $document: $DocumentProvider,\n $$isDocumentHidden: $$IsDocumentHiddenProvider,\n $exceptionHandler: $ExceptionHandlerProvider,\n $filter: $FilterProvider,\n $$forceReflow: $$ForceReflowProvider,\n $interpolate: $InterpolateProvider,\n $interval: $IntervalProvider,\n $http: $HttpProvider,\n $httpParamSerializer: $HttpParamSerializerProvider,\n $httpParamSerializerJQLike: $HttpParamSerializerJQLikeProvider,\n $httpBackend: $HttpBackendProvider,\n $xhrFactory: $xhrFactoryProvider,\n $jsonpCallbacks: $jsonpCallbacksProvider,\n $location: $LocationProvider,\n $log: $LogProvider,\n $parse: $ParseProvider,\n $rootScope: $RootScopeProvider,\n $q: $QProvider,\n $$q: $$QProvider,\n $sce: $SceProvider,\n $sceDelegate: $SceDelegateProvider,\n $sniffer: $SnifferProvider,\n $templateCache: $TemplateCacheProvider,\n $templateRequest: $TemplateRequestProvider,\n $$testability: $$TestabilityProvider,\n $timeout: $TimeoutProvider,\n $window: $WindowProvider,\n $$rAF: $$RAFProvider,\n $$jqLite: $$jqLiteProvider,\n $$HashMap: $$HashMapProvider,\n $$cookieReader: $$CookieReaderProvider\n });\n }\n ]);\n}\n\n/* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *\n * Any commits to this file should be reviewed with security in mind. *\n * Changes to this file can potentially create security vulnerabilities. *\n * An approval from 2 Core members with history of modifying *\n * this file is required. *\n * *\n * Does the change somehow allow for arbitrary javascript to be executed? *\n * Or allows for someone to change the prototype of built-in objects? *\n * Or gives undesired access to variables likes document or window? *\n * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */\n\n/* global\n JQLitePrototype: true,\n BOOLEAN_ATTR: true,\n ALIASED_ATTR: true\n*/\n\n//////////////////////////////////\n//JQLite\n//////////////////////////////////\n\n/**\n * @ngdoc function\n * @name angular.element\n * @module ng\n * @kind function\n *\n * @description\n * Wraps a raw DOM element or HTML string as a [jQuery](http://jquery.com) element.\n *\n * If jQuery is available, `angular.element` is an alias for the\n * [jQuery](http://api.jquery.com/jQuery/) function. If jQuery is not available, `angular.element`\n * delegates to Angular's built-in subset of jQuery, called \"jQuery lite\" or **jqLite**.\n *\n * jqLite is a tiny, API-compatible subset of jQuery that allows\n * Angular to manipulate the DOM in a cross-browser compatible way. jqLite implements only the most\n * commonly needed functionality with the goal of having a very small footprint.\n *\n * To use `jQuery`, simply ensure it is loaded before the `angular.js` file. You can also use the\n * {@link ngJq `ngJq`} directive to specify that jqlite should be used over jQuery, or to use a\n * specific version of jQuery if multiple versions exist on the page.\n *\n *
**Note:** All element references in Angular are always wrapped with jQuery or\n * jqLite (such as the element argument in a directive's compile / link function). They are never raw DOM references.
\n *\n *
**Note:** Keep in mind that this function will not find elements\n * by tag name / CSS selector. For lookups by tag name, try instead `angular.element(document).find(...)`\n * or `$document.find()`, or use the standard DOM APIs, e.g. `document.querySelectorAll()`.
\n *\n * ## Angular's jqLite\n * jqLite provides only the following jQuery methods:\n *\n * - [`addClass()`](http://api.jquery.com/addClass/) - Does not support a function as first argument\n * - [`after()`](http://api.jquery.com/after/)\n * - [`append()`](http://api.jquery.com/append/)\n * - [`attr()`](http://api.jquery.com/attr/) - Does not support functions as parameters\n * - [`bind()`](http://api.jquery.com/bind/) (_deprecated_, use [`on()`](http://api.jquery.com/on/)) - Does not support namespaces, selectors or eventData\n * - [`children()`](http://api.jquery.com/children/) - Does not support selectors\n * - [`clone()`](http://api.jquery.com/clone/)\n * - [`contents()`](http://api.jquery.com/contents/)\n * - [`css()`](http://api.jquery.com/css/) - Only retrieves inline-styles, does not call `getComputedStyle()`.\n * As a setter, does not convert numbers to strings or append 'px', and also does not have automatic property prefixing.\n * - [`data()`](http://api.jquery.com/data/)\n * - [`detach()`](http://api.jquery.com/detach/)\n * - [`empty()`](http://api.jquery.com/empty/)\n * - [`eq()`](http://api.jquery.com/eq/)\n * - [`find()`](http://api.jquery.com/find/) - Limited to lookups by tag name\n * - [`hasClass()`](http://api.jquery.com/hasClass/)\n * - [`html()`](http://api.jquery.com/html/)\n * - [`next()`](http://api.jquery.com/next/) - Does not support selectors\n * - [`on()`](http://api.jquery.com/on/) - Does not support namespaces, selectors or eventData\n * - [`off()`](http://api.jquery.com/off/) - Does not support namespaces, selectors or event object as parameter\n * - [`one()`](http://api.jquery.com/one/) - Does not support namespaces or selectors\n * - [`parent()`](http://api.jquery.com/parent/) - Does not support selectors\n * - [`prepend()`](http://api.jquery.com/prepend/)\n * - [`prop()`](http://api.jquery.com/prop/)\n * - [`ready()`](http://api.jquery.com/ready/) (_deprecated_, use `angular.element(callback)` instead of `angular.element(document).ready(callback)`)\n * - [`remove()`](http://api.jquery.com/remove/)\n * - [`removeAttr()`](http://api.jquery.com/removeAttr/) - Does not support multiple attributes\n * - [`removeClass()`](http://api.jquery.com/removeClass/) - Does not support a function as first argument\n * - [`removeData()`](http://api.jquery.com/removeData/)\n * - [`replaceWith()`](http://api.jquery.com/replaceWith/)\n * - [`text()`](http://api.jquery.com/text/)\n * - [`toggleClass()`](http://api.jquery.com/toggleClass/) - Does not support a function as first argument\n * - [`triggerHandler()`](http://api.jquery.com/triggerHandler/) - Passes a dummy event object to handlers\n * - [`unbind()`](http://api.jquery.com/unbind/) (_deprecated_, use [`off()`](http://api.jquery.com/off/)) - Does not support namespaces or event object as parameter\n * - [`val()`](http://api.jquery.com/val/)\n * - [`wrap()`](http://api.jquery.com/wrap/)\n *\n * ## jQuery/jqLite Extras\n * Angular also provides the following additional methods and events to both jQuery and jqLite:\n *\n * ### Events\n * - `$destroy` - AngularJS intercepts all jqLite/jQuery's DOM destruction apis and fires this event\n * on all DOM nodes being removed. This can be used to clean up any 3rd party bindings to the DOM\n * element before it is removed.\n *\n * ### Methods\n * - `controller(name)` - retrieves the controller of the current element or its parent. By default\n * retrieves controller associated with the `ngController` directive. If `name` is provided as\n * camelCase directive name, then the controller for this directive will be retrieved (e.g.\n * `'ngModel'`).\n * - `injector()` - retrieves the injector of the current element or its parent.\n * - `scope()` - retrieves the {@link ng.$rootScope.Scope scope} of the current\n * element or its parent. Requires {@link guide/production#disabling-debug-data Debug Data} to\n * be enabled.\n * - `isolateScope()` - retrieves an isolate {@link ng.$rootScope.Scope scope} if one is attached directly to the\n * current element. This getter should be used only on elements that contain a directive which starts a new isolate\n * scope. Calling `scope()` on this element always returns the original non-isolate scope.\n * Requires {@link guide/production#disabling-debug-data Debug Data} to be enabled.\n * - `inheritedData()` - same as `data()`, but walks up the DOM until a value is found or the top\n * parent element is reached.\n *\n * @knownIssue You cannot spy on `angular.element` if you are using Jasmine version 1.x. See\n * https://github.com/angular/angular.js/issues/14251 for more information.\n *\n * @param {string|DOMElement} element HTML string or DOMElement to be wrapped into jQuery.\n * @returns {Object} jQuery object.\n */\n\nJQLite.expando = 'ng339';\n\nvar jqCache = JQLite.cache = {},\n jqId = 1;\n\n/*\n * !!! This is an undocumented \"private\" function !!!\n */\nJQLite._data = function(node) {\n //jQuery always returns an object on cache miss\n return this.cache[node[this.expando]] || {};\n};\n\nfunction jqNextId() { return ++jqId; }\n\n\nvar DASH_LOWERCASE_REGEXP = /-([a-z])/g;\nvar MS_HACK_REGEXP = /^-ms-/;\nvar MOUSE_EVENT_MAP = { mouseleave: 'mouseout', mouseenter: 'mouseover' };\nvar jqLiteMinErr = minErr('jqLite');\n\n/**\n * Converts kebab-case to camelCase.\n * There is also a special case for the ms prefix starting with a lowercase letter.\n * @param name Name to normalize\n */\nfunction cssKebabToCamel(name) {\n return kebabToCamel(name.replace(MS_HACK_REGEXP, 'ms-'));\n}\n\nfunction fnCamelCaseReplace(all, letter) {\n return letter.toUpperCase();\n}\n\n/**\n * Converts kebab-case to camelCase.\n * @param name Name to normalize\n */\nfunction kebabToCamel(name) {\n return name\n .replace(DASH_LOWERCASE_REGEXP, fnCamelCaseReplace);\n}\n\nvar SINGLE_TAG_REGEXP = /^<([\\w-]+)\\s*\\/?>(?:<\\/\\1>|)$/;\nvar HTML_REGEXP = /<|&#?\\w+;/;\nvar TAG_NAME_REGEXP = /<([\\w:-]+)/;\nvar XHTML_TAG_REGEXP = /<(?!area|br|col|embed|hr|img|input|link|meta|param)(([\\w:-]+)[^>]*)\\/>/gi;\n\nvar wrapMap = {\n 'option': [1, ''],\n\n 'thead': [1, '', '
'],\n 'col': [2, '', '
'],\n 'tr': [2, '', '
'],\n 'td': [3, '', '
'],\n '_default': [0, '', '']\n};\n\nwrapMap.optgroup = wrapMap.option;\nwrapMap.tbody = wrapMap.tfoot = wrapMap.colgroup = wrapMap.caption = wrapMap.thead;\nwrapMap.th = wrapMap.td;\n\n\nfunction jqLiteIsTextNode(html) {\n return !HTML_REGEXP.test(html);\n}\n\nfunction jqLiteAcceptsData(node) {\n // The window object can accept data but has no nodeType\n // Otherwise we are only interested in elements (1) and documents (9)\n var nodeType = node.nodeType;\n return nodeType === NODE_TYPE_ELEMENT || !nodeType || nodeType === NODE_TYPE_DOCUMENT;\n}\n\nfunction jqLiteHasData(node) {\n for (var key in jqCache[node.ng339]) {\n return true;\n }\n return false;\n}\n\nfunction jqLiteCleanData(nodes) {\n for (var i = 0, ii = nodes.length; i < ii; i++) {\n jqLiteRemoveData(nodes[i]);\n }\n}\n\nfunction jqLiteBuildFragment(html, context) {\n var tmp, tag, wrap,\n fragment = context.createDocumentFragment(),\n nodes = [], i;\n\n if (jqLiteIsTextNode(html)) {\n // Convert non-html into a text node\n nodes.push(context.createTextNode(html));\n } else {\n // Convert html into DOM nodes\n tmp = fragment.appendChild(context.createElement('div'));\n tag = (TAG_NAME_REGEXP.exec(html) || ['', ''])[1].toLowerCase();\n wrap = wrapMap[tag] || wrapMap._default;\n tmp.innerHTML = wrap[1] + html.replace(XHTML_TAG_REGEXP, '<$1>') + wrap[2];\n\n // Descend through wrappers to the right content\n i = wrap[0];\n while (i--) {\n tmp = tmp.lastChild;\n }\n\n nodes = concat(nodes, tmp.childNodes);\n\n tmp = fragment.firstChild;\n tmp.textContent = '';\n }\n\n // Remove wrapper from fragment\n fragment.textContent = '';\n fragment.innerHTML = ''; // Clear inner HTML\n forEach(nodes, function(node) {\n fragment.appendChild(node);\n });\n\n return fragment;\n}\n\nfunction jqLiteParseHTML(html, context) {\n context = context || window.document;\n var parsed;\n\n if ((parsed = SINGLE_TAG_REGEXP.exec(html))) {\n return [context.createElement(parsed[1])];\n }\n\n if ((parsed = jqLiteBuildFragment(html, context))) {\n return parsed.childNodes;\n }\n\n return [];\n}\n\nfunction jqLiteWrapNode(node, wrapper) {\n var parent = node.parentNode;\n\n if (parent) {\n parent.replaceChild(wrapper, node);\n }\n\n wrapper.appendChild(node);\n}\n\n\n// IE9-11 has no method \"contains\" in SVG element and in Node.prototype. Bug #10259.\nvar jqLiteContains = window.Node.prototype.contains || /** @this */ function(arg) {\n // eslint-disable-next-line no-bitwise\n return !!(this.compareDocumentPosition(arg) & 16);\n};\n\n/////////////////////////////////////////////\nfunction JQLite(element) {\n if (element instanceof JQLite) {\n return element;\n }\n\n var argIsString;\n\n if (isString(element)) {\n element = trim(element);\n argIsString = true;\n }\n if (!(this instanceof JQLite)) {\n if (argIsString && element.charAt(0) !== '<') {\n throw jqLiteMinErr('nosel', 'Looking up elements via selectors is not supported by jqLite! See: http://docs.angularjs.org/api/angular.element');\n }\n return new JQLite(element);\n }\n\n if (argIsString) {\n jqLiteAddNodes(this, jqLiteParseHTML(element));\n } else if (isFunction(element)) {\n jqLiteReady(element);\n } else {\n jqLiteAddNodes(this, element);\n }\n}\n\nfunction jqLiteClone(element) {\n return element.cloneNode(true);\n}\n\nfunction jqLiteDealoc(element, onlyDescendants) {\n if (!onlyDescendants) jqLiteRemoveData(element);\n\n if (element.querySelectorAll) {\n var descendants = element.querySelectorAll('*');\n for (var i = 0, l = descendants.length; i < l; i++) {\n jqLiteRemoveData(descendants[i]);\n }\n }\n}\n\nfunction jqLiteOff(element, type, fn, unsupported) {\n if (isDefined(unsupported)) throw jqLiteMinErr('offargs', 'jqLite#off() does not support the `selector` argument');\n\n var expandoStore = jqLiteExpandoStore(element);\n var events = expandoStore && expandoStore.events;\n var handle = expandoStore && expandoStore.handle;\n\n if (!handle) return; //no listeners registered\n\n if (!type) {\n for (type in events) {\n if (type !== '$destroy') {\n element.removeEventListener(type, handle);\n }\n delete events[type];\n }\n } else {\n\n var removeHandler = function(type) {\n var listenerFns = events[type];\n if (isDefined(fn)) {\n arrayRemove(listenerFns || [], fn);\n }\n if (!(isDefined(fn) && listenerFns && listenerFns.length > 0)) {\n element.removeEventListener(type, handle);\n delete events[type];\n }\n };\n\n forEach(type.split(' '), function(type) {\n removeHandler(type);\n if (MOUSE_EVENT_MAP[type]) {\n removeHandler(MOUSE_EVENT_MAP[type]);\n }\n });\n }\n}\n\nfunction jqLiteRemoveData(element, name) {\n var expandoId = element.ng339;\n var expandoStore = expandoId && jqCache[expandoId];\n\n if (expandoStore) {\n if (name) {\n delete expandoStore.data[name];\n return;\n }\n\n if (expandoStore.handle) {\n if (expandoStore.events.$destroy) {\n expandoStore.handle({}, '$destroy');\n }\n jqLiteOff(element);\n }\n delete jqCache[expandoId];\n element.ng339 = undefined; // don't delete DOM expandos. IE and Chrome don't like it\n }\n}\n\n\nfunction jqLiteExpandoStore(element, createIfNecessary) {\n var expandoId = element.ng339,\n expandoStore = expandoId && jqCache[expandoId];\n\n if (createIfNecessary && !expandoStore) {\n element.ng339 = expandoId = jqNextId();\n expandoStore = jqCache[expandoId] = {events: {}, data: {}, handle: undefined};\n }\n\n return expandoStore;\n}\n\n\nfunction jqLiteData(element, key, value) {\n if (jqLiteAcceptsData(element)) {\n var prop;\n\n var isSimpleSetter = isDefined(value);\n var isSimpleGetter = !isSimpleSetter && key && !isObject(key);\n var massGetter = !key;\n var expandoStore = jqLiteExpandoStore(element, !isSimpleGetter);\n var data = expandoStore && expandoStore.data;\n\n if (isSimpleSetter) { // data('key', value)\n data[kebabToCamel(key)] = value;\n } else {\n if (massGetter) { // data()\n return data;\n } else {\n if (isSimpleGetter) { // data('key')\n // don't force creation of expandoStore if it doesn't exist yet\n return data && data[kebabToCamel(key)];\n } else { // mass-setter: data({key1: val1, key2: val2})\n for (prop in key) {\n data[kebabToCamel(prop)] = key[prop];\n }\n }\n }\n }\n }\n}\n\nfunction jqLiteHasClass(element, selector) {\n if (!element.getAttribute) return false;\n return ((' ' + (element.getAttribute('class') || '') + ' ').replace(/[\\n\\t]/g, ' ').\n indexOf(' ' + selector + ' ') > -1);\n}\n\nfunction jqLiteRemoveClass(element, cssClasses) {\n if (cssClasses && element.setAttribute) {\n forEach(cssClasses.split(' '), function(cssClass) {\n element.setAttribute('class', trim(\n (' ' + (element.getAttribute('class') || '') + ' ')\n .replace(/[\\n\\t]/g, ' ')\n .replace(' ' + trim(cssClass) + ' ', ' '))\n );\n });\n }\n}\n\nfunction jqLiteAddClass(element, cssClasses) {\n if (cssClasses && element.setAttribute) {\n var existingClasses = (' ' + (element.getAttribute('class') || '') + ' ')\n .replace(/[\\n\\t]/g, ' ');\n\n forEach(cssClasses.split(' '), function(cssClass) {\n cssClass = trim(cssClass);\n if (existingClasses.indexOf(' ' + cssClass + ' ') === -1) {\n existingClasses += cssClass + ' ';\n }\n });\n\n element.setAttribute('class', trim(existingClasses));\n }\n}\n\n\nfunction jqLiteAddNodes(root, elements) {\n // THIS CODE IS VERY HOT. Don't make changes without benchmarking.\n\n if (elements) {\n\n // if a Node (the most common case)\n if (elements.nodeType) {\n root[root.length++] = elements;\n } else {\n var length = elements.length;\n\n // if an Array or NodeList and not a Window\n if (typeof length === 'number' && elements.window !== elements) {\n if (length) {\n for (var i = 0; i < length; i++) {\n root[root.length++] = elements[i];\n }\n }\n } else {\n root[root.length++] = elements;\n }\n }\n }\n}\n\n\nfunction jqLiteController(element, name) {\n return jqLiteInheritedData(element, '$' + (name || 'ngController') + 'Controller');\n}\n\nfunction jqLiteInheritedData(element, name, value) {\n // if element is the document object work with the html element instead\n // this makes $(document).scope() possible\n if (element.nodeType === NODE_TYPE_DOCUMENT) {\n element = element.documentElement;\n }\n var names = isArray(name) ? name : [name];\n\n while (element) {\n for (var i = 0, ii = names.length; i < ii; i++) {\n if (isDefined(value = jqLite.data(element, names[i]))) return value;\n }\n\n // If dealing with a document fragment node with a host element, and no parent, use the host\n // element as the parent. This enables directives within a Shadow DOM or polyfilled Shadow DOM\n // to lookup parent controllers.\n element = element.parentNode || (element.nodeType === NODE_TYPE_DOCUMENT_FRAGMENT && element.host);\n }\n}\n\nfunction jqLiteEmpty(element) {\n jqLiteDealoc(element, true);\n while (element.firstChild) {\n element.removeChild(element.firstChild);\n }\n}\n\nfunction jqLiteRemove(element, keepData) {\n if (!keepData) jqLiteDealoc(element);\n var parent = element.parentNode;\n if (parent) parent.removeChild(element);\n}\n\n\nfunction jqLiteDocumentLoaded(action, win) {\n win = win || window;\n if (win.document.readyState === 'complete') {\n // Force the action to be run async for consistent behavior\n // from the action's point of view\n // i.e. it will definitely not be in a $apply\n win.setTimeout(action);\n } else {\n // No need to unbind this handler as load is only ever called once\n jqLite(win).on('load', action);\n }\n}\n\nfunction jqLiteReady(fn) {\n function trigger() {\n window.document.removeEventListener('DOMContentLoaded', trigger);\n window.removeEventListener('load', trigger);\n fn();\n }\n\n // check if document is already loaded\n if (window.document.readyState === 'complete') {\n window.setTimeout(fn);\n } else {\n // We can not use jqLite since we are not done loading and jQuery could be loaded later.\n\n // Works for modern browsers and IE9\n window.document.addEventListener('DOMContentLoaded', trigger);\n\n // Fallback to window.onload for others\n window.addEventListener('load', trigger);\n }\n}\n\n//////////////////////////////////////////\n// Functions which are declared directly.\n//////////////////////////////////////////\nvar JQLitePrototype = JQLite.prototype = {\n ready: jqLiteReady,\n toString: function() {\n var value = [];\n forEach(this, function(e) { value.push('' + e);});\n return '[' + value.join(', ') + ']';\n },\n\n eq: function(index) {\n return (index >= 0) ? jqLite(this[index]) : jqLite(this[this.length + index]);\n },\n\n length: 0,\n push: push,\n sort: [].sort,\n splice: [].splice\n};\n\n//////////////////////////////////////////\n// Functions iterating getter/setters.\n// these functions return self on setter and\n// value on get.\n//////////////////////////////////////////\nvar BOOLEAN_ATTR = {};\nforEach('multiple,selected,checked,disabled,readOnly,required,open'.split(','), function(value) {\n BOOLEAN_ATTR[lowercase(value)] = value;\n});\nvar BOOLEAN_ELEMENTS = {};\nforEach('input,select,option,textarea,button,form,details'.split(','), function(value) {\n BOOLEAN_ELEMENTS[value] = true;\n});\nvar ALIASED_ATTR = {\n 'ngMinlength': 'minlength',\n 'ngMaxlength': 'maxlength',\n 'ngMin': 'min',\n 'ngMax': 'max',\n 'ngPattern': 'pattern',\n 'ngStep': 'step'\n};\n\nfunction getBooleanAttrName(element, name) {\n // check dom last since we will most likely fail on name\n var booleanAttr = BOOLEAN_ATTR[name.toLowerCase()];\n\n // booleanAttr is here twice to minimize DOM access\n return booleanAttr && BOOLEAN_ELEMENTS[nodeName_(element)] && booleanAttr;\n}\n\nfunction getAliasedAttrName(name) {\n return ALIASED_ATTR[name];\n}\n\nforEach({\n data: jqLiteData,\n removeData: jqLiteRemoveData,\n hasData: jqLiteHasData,\n cleanData: jqLiteCleanData\n}, function(fn, name) {\n JQLite[name] = fn;\n});\n\nforEach({\n data: jqLiteData,\n inheritedData: jqLiteInheritedData,\n\n scope: function(element) {\n // Can't use jqLiteData here directly so we stay compatible with jQuery!\n return jqLite.data(element, '$scope') || jqLiteInheritedData(element.parentNode || element, ['$isolateScope', '$scope']);\n },\n\n isolateScope: function(element) {\n // Can't use jqLiteData here directly so we stay compatible with jQuery!\n return jqLite.data(element, '$isolateScope') || jqLite.data(element, '$isolateScopeNoTemplate');\n },\n\n controller: jqLiteController,\n\n injector: function(element) {\n return jqLiteInheritedData(element, '$injector');\n },\n\n removeAttr: function(element, name) {\n element.removeAttribute(name);\n },\n\n hasClass: jqLiteHasClass,\n\n css: function(element, name, value) {\n name = cssKebabToCamel(name);\n\n if (isDefined(value)) {\n element.style[name] = value;\n } else {\n return element.style[name];\n }\n },\n\n attr: function(element, name, value) {\n var ret;\n var nodeType = element.nodeType;\n if (nodeType === NODE_TYPE_TEXT || nodeType === NODE_TYPE_ATTRIBUTE || nodeType === NODE_TYPE_COMMENT ||\n !element.getAttribute) {\n return;\n }\n\n var lowercasedName = lowercase(name);\n var isBooleanAttr = BOOLEAN_ATTR[lowercasedName];\n\n if (isDefined(value)) {\n // setter\n\n if (value === null || (value === false && isBooleanAttr)) {\n element.removeAttribute(name);\n } else {\n element.setAttribute(name, isBooleanAttr ? lowercasedName : value);\n }\n } else {\n // getter\n\n ret = element.getAttribute(name);\n\n if (isBooleanAttr && ret !== null) {\n ret = lowercasedName;\n }\n // Normalize non-existing attributes to undefined (as jQuery).\n return ret === null ? undefined : ret;\n }\n },\n\n prop: function(element, name, value) {\n if (isDefined(value)) {\n element[name] = value;\n } else {\n return element[name];\n }\n },\n\n text: (function() {\n getText.$dv = '';\n return getText;\n\n function getText(element, value) {\n if (isUndefined(value)) {\n var nodeType = element.nodeType;\n return (nodeType === NODE_TYPE_ELEMENT || nodeType === NODE_TYPE_TEXT) ? element.textContent : '';\n }\n element.textContent = value;\n }\n })(),\n\n val: function(element, value) {\n if (isUndefined(value)) {\n if (element.multiple && nodeName_(element) === 'select') {\n var result = [];\n forEach(element.options, function(option) {\n if (option.selected) {\n result.push(option.value || option.text);\n }\n });\n return result;\n }\n return element.value;\n }\n element.value = value;\n },\n\n html: function(element, value) {\n if (isUndefined(value)) {\n return element.innerHTML;\n }\n jqLiteDealoc(element, true);\n element.innerHTML = value;\n },\n\n empty: jqLiteEmpty\n}, function(fn, name) {\n /**\n * Properties: writes return selection, reads return first value\n */\n JQLite.prototype[name] = function(arg1, arg2) {\n var i, key;\n var nodeCount = this.length;\n\n // jqLiteHasClass has only two arguments, but is a getter-only fn, so we need to special-case it\n // in a way that survives minification.\n // jqLiteEmpty takes no arguments but is a setter.\n if (fn !== jqLiteEmpty &&\n (isUndefined((fn.length === 2 && (fn !== jqLiteHasClass && fn !== jqLiteController)) ? arg1 : arg2))) {\n if (isObject(arg1)) {\n\n // we are a write, but the object properties are the key/values\n for (i = 0; i < nodeCount; i++) {\n if (fn === jqLiteData) {\n // data() takes the whole object in jQuery\n fn(this[i], arg1);\n } else {\n for (key in arg1) {\n fn(this[i], key, arg1[key]);\n }\n }\n }\n // return self for chaining\n return this;\n } else {\n // we are a read, so read the first child.\n // TODO: do we still need this?\n var value = fn.$dv;\n // Only if we have $dv do we iterate over all, otherwise it is just the first element.\n var jj = (isUndefined(value)) ? Math.min(nodeCount, 1) : nodeCount;\n for (var j = 0; j < jj; j++) {\n var nodeValue = fn(this[j], arg1, arg2);\n value = value ? value + nodeValue : nodeValue;\n }\n return value;\n }\n } else {\n // we are a write, so apply to all children\n for (i = 0; i < nodeCount; i++) {\n fn(this[i], arg1, arg2);\n }\n // return self for chaining\n return this;\n }\n };\n});\n\nfunction createEventHandler(element, events) {\n var eventHandler = function(event, type) {\n // jQuery specific api\n event.isDefaultPrevented = function() {\n return event.defaultPrevented;\n };\n\n var eventFns = events[type || event.type];\n var eventFnsLength = eventFns ? eventFns.length : 0;\n\n if (!eventFnsLength) return;\n\n if (isUndefined(event.immediatePropagationStopped)) {\n var originalStopImmediatePropagation = event.stopImmediatePropagation;\n event.stopImmediatePropagation = function() {\n event.immediatePropagationStopped = true;\n\n if (event.stopPropagation) {\n event.stopPropagation();\n }\n\n if (originalStopImmediatePropagation) {\n originalStopImmediatePropagation.call(event);\n }\n };\n }\n\n event.isImmediatePropagationStopped = function() {\n return event.immediatePropagationStopped === true;\n };\n\n // Some events have special handlers that wrap the real handler\n var handlerWrapper = eventFns.specialHandlerWrapper || defaultHandlerWrapper;\n\n // Copy event handlers in case event handlers array is modified during execution.\n if ((eventFnsLength > 1)) {\n eventFns = shallowCopy(eventFns);\n }\n\n for (var i = 0; i < eventFnsLength; i++) {\n if (!event.isImmediatePropagationStopped()) {\n handlerWrapper(element, event, eventFns[i]);\n }\n }\n };\n\n // TODO: this is a hack for angularMocks/clearDataCache that makes it possible to deregister all\n // events on `element`\n eventHandler.elem = element;\n return eventHandler;\n}\n\nfunction defaultHandlerWrapper(element, event, handler) {\n handler.call(element, event);\n}\n\nfunction specialMouseHandlerWrapper(target, event, handler) {\n // Refer to jQuery's implementation of mouseenter & mouseleave\n // Read about mouseenter and mouseleave:\n // http://www.quirksmode.org/js/events_mouse.html#link8\n var related = event.relatedTarget;\n // For mousenter/leave call the handler if related is outside the target.\n // NB: No relatedTarget if the mouse left/entered the browser window\n if (!related || (related !== target && !jqLiteContains.call(target, related))) {\n handler.call(target, event);\n }\n}\n\n//////////////////////////////////////////\n// Functions iterating traversal.\n// These functions chain results into a single\n// selector.\n//////////////////////////////////////////\nforEach({\n removeData: jqLiteRemoveData,\n\n on: function jqLiteOn(element, type, fn, unsupported) {\n if (isDefined(unsupported)) throw jqLiteMinErr('onargs', 'jqLite#on() does not support the `selector` or `eventData` parameters');\n\n // Do not add event handlers to non-elements because they will not be cleaned up.\n if (!jqLiteAcceptsData(element)) {\n return;\n }\n\n var expandoStore = jqLiteExpandoStore(element, true);\n var events = expandoStore.events;\n var handle = expandoStore.handle;\n\n if (!handle) {\n handle = expandoStore.handle = createEventHandler(element, events);\n }\n\n // http://jsperf.com/string-indexof-vs-split\n var types = type.indexOf(' ') >= 0 ? type.split(' ') : [type];\n var i = types.length;\n\n var addHandler = function(type, specialHandlerWrapper, noEventListener) {\n var eventFns = events[type];\n\n if (!eventFns) {\n eventFns = events[type] = [];\n eventFns.specialHandlerWrapper = specialHandlerWrapper;\n if (type !== '$destroy' && !noEventListener) {\n element.addEventListener(type, handle);\n }\n }\n\n eventFns.push(fn);\n };\n\n while (i--) {\n type = types[i];\n if (MOUSE_EVENT_MAP[type]) {\n addHandler(MOUSE_EVENT_MAP[type], specialMouseHandlerWrapper);\n addHandler(type, undefined, true);\n } else {\n addHandler(type);\n }\n }\n },\n\n off: jqLiteOff,\n\n one: function(element, type, fn) {\n element = jqLite(element);\n\n //add the listener twice so that when it is called\n //you can remove the original function and still be\n //able to call element.off(ev, fn) normally\n element.on(type, function onFn() {\n element.off(type, fn);\n element.off(type, onFn);\n });\n element.on(type, fn);\n },\n\n replaceWith: function(element, replaceNode) {\n var index, parent = element.parentNode;\n jqLiteDealoc(element);\n forEach(new JQLite(replaceNode), function(node) {\n if (index) {\n parent.insertBefore(node, index.nextSibling);\n } else {\n parent.replaceChild(node, element);\n }\n index = node;\n });\n },\n\n children: function(element) {\n var children = [];\n forEach(element.childNodes, function(element) {\n if (element.nodeType === NODE_TYPE_ELEMENT) {\n children.push(element);\n }\n });\n return children;\n },\n\n contents: function(element) {\n return element.contentDocument || element.childNodes || [];\n },\n\n append: function(element, node) {\n var nodeType = element.nodeType;\n if (nodeType !== NODE_TYPE_ELEMENT && nodeType !== NODE_TYPE_DOCUMENT_FRAGMENT) return;\n\n node = new JQLite(node);\n\n for (var i = 0, ii = node.length; i < ii; i++) {\n var child = node[i];\n element.appendChild(child);\n }\n },\n\n prepend: function(element, node) {\n if (element.nodeType === NODE_TYPE_ELEMENT) {\n var index = element.firstChild;\n forEach(new JQLite(node), function(child) {\n element.insertBefore(child, index);\n });\n }\n },\n\n wrap: function(element, wrapNode) {\n jqLiteWrapNode(element, jqLite(wrapNode).eq(0).clone()[0]);\n },\n\n remove: jqLiteRemove,\n\n detach: function(element) {\n jqLiteRemove(element, true);\n },\n\n after: function(element, newElement) {\n var index = element, parent = element.parentNode;\n newElement = new JQLite(newElement);\n\n for (var i = 0, ii = newElement.length; i < ii; i++) {\n var node = newElement[i];\n parent.insertBefore(node, index.nextSibling);\n index = node;\n }\n },\n\n addClass: jqLiteAddClass,\n removeClass: jqLiteRemoveClass,\n\n toggleClass: function(element, selector, condition) {\n if (selector) {\n forEach(selector.split(' '), function(className) {\n var classCondition = condition;\n if (isUndefined(classCondition)) {\n classCondition = !jqLiteHasClass(element, className);\n }\n (classCondition ? jqLiteAddClass : jqLiteRemoveClass)(element, className);\n });\n }\n },\n\n parent: function(element) {\n var parent = element.parentNode;\n return parent && parent.nodeType !== NODE_TYPE_DOCUMENT_FRAGMENT ? parent : null;\n },\n\n next: function(element) {\n return element.nextElementSibling;\n },\n\n find: function(element, selector) {\n if (element.getElementsByTagName) {\n return element.getElementsByTagName(selector);\n } else {\n return [];\n }\n },\n\n clone: jqLiteClone,\n\n triggerHandler: function(element, event, extraParameters) {\n\n var dummyEvent, eventFnsCopy, handlerArgs;\n var eventName = event.type || event;\n var expandoStore = jqLiteExpandoStore(element);\n var events = expandoStore && expandoStore.events;\n var eventFns = events && events[eventName];\n\n if (eventFns) {\n // Create a dummy event to pass to the handlers\n dummyEvent = {\n preventDefault: function() { this.defaultPrevented = true; },\n isDefaultPrevented: function() { return this.defaultPrevented === true; },\n stopImmediatePropagation: function() { this.immediatePropagationStopped = true; },\n isImmediatePropagationStopped: function() { return this.immediatePropagationStopped === true; },\n stopPropagation: noop,\n type: eventName,\n target: element\n };\n\n // If a custom event was provided then extend our dummy event with it\n if (event.type) {\n dummyEvent = extend(dummyEvent, event);\n }\n\n // Copy event handlers in case event handlers array is modified during execution.\n eventFnsCopy = shallowCopy(eventFns);\n handlerArgs = extraParameters ? [dummyEvent].concat(extraParameters) : [dummyEvent];\n\n forEach(eventFnsCopy, function(fn) {\n if (!dummyEvent.isImmediatePropagationStopped()) {\n fn.apply(element, handlerArgs);\n }\n });\n }\n }\n}, function(fn, name) {\n /**\n * chaining functions\n */\n JQLite.prototype[name] = function(arg1, arg2, arg3) {\n var value;\n\n for (var i = 0, ii = this.length; i < ii; i++) {\n if (isUndefined(value)) {\n value = fn(this[i], arg1, arg2, arg3);\n if (isDefined(value)) {\n // any function which returns a value needs to be wrapped\n value = jqLite(value);\n }\n } else {\n jqLiteAddNodes(value, fn(this[i], arg1, arg2, arg3));\n }\n }\n return isDefined(value) ? value : this;\n };\n});\n\n// bind legacy bind/unbind to on/off\nJQLite.prototype.bind = JQLite.prototype.on;\nJQLite.prototype.unbind = JQLite.prototype.off;\n\n\n// Provider for private $$jqLite service\n/** @this */\nfunction $$jqLiteProvider() {\n this.$get = function $$jqLite() {\n return extend(JQLite, {\n hasClass: function(node, classes) {\n if (node.attr) node = node[0];\n return jqLiteHasClass(node, classes);\n },\n addClass: function(node, classes) {\n if (node.attr) node = node[0];\n return jqLiteAddClass(node, classes);\n },\n removeClass: function(node, classes) {\n if (node.attr) node = node[0];\n return jqLiteRemoveClass(node, classes);\n }\n });\n };\n}\n\n/**\n * Computes a hash of an 'obj'.\n * Hash of a:\n * string is string\n * number is number as string\n * object is either result of calling $$hashKey function on the object or uniquely generated id,\n * that is also assigned to the $$hashKey property of the object.\n *\n * @param obj\n * @returns {string} hash string such that the same input will have the same hash string.\n * The resulting string key is in 'type:hashKey' format.\n */\nfunction hashKey(obj, nextUidFn) {\n var key = obj && obj.$$hashKey;\n\n if (key) {\n if (typeof key === 'function') {\n key = obj.$$hashKey();\n }\n return key;\n }\n\n var objType = typeof obj;\n if (objType === 'function' || (objType === 'object' && obj !== null)) {\n key = obj.$$hashKey = objType + ':' + (nextUidFn || nextUid)();\n } else {\n key = objType + ':' + obj;\n }\n\n return key;\n}\n\n/**\n * HashMap which can use objects as keys\n */\nfunction HashMap(array, isolatedUid) {\n if (isolatedUid) {\n var uid = 0;\n this.nextUid = function() {\n return ++uid;\n };\n }\n forEach(array, this.put, this);\n}\nHashMap.prototype = {\n /**\n * Store key value pair\n * @param key key to store can be any type\n * @param value value to store can be any type\n */\n put: function(key, value) {\n this[hashKey(key, this.nextUid)] = value;\n },\n\n /**\n * @param key\n * @returns {Object} the value for the key\n */\n get: function(key) {\n return this[hashKey(key, this.nextUid)];\n },\n\n /**\n * Remove the key/value pair\n * @param key\n */\n remove: function(key) {\n var value = this[key = hashKey(key, this.nextUid)];\n delete this[key];\n return value;\n }\n};\n\nvar $$HashMapProvider = [/** @this */function() {\n this.$get = [function() {\n return HashMap;\n }];\n}];\n\n/**\n * @ngdoc function\n * @module ng\n * @name angular.injector\n * @kind function\n *\n * @description\n * Creates an injector object that can be used for retrieving services as well as for\n * dependency injection (see {@link guide/di dependency injection}).\n *\n * @param {Array.} modules A list of module functions or their aliases. See\n * {@link angular.module}. The `ng` module must be explicitly added.\n * @param {boolean=} [strictDi=false] Whether the injector should be in strict mode, which\n * disallows argument name annotation inference.\n * @returns {injector} Injector object. See {@link auto.$injector $injector}.\n *\n * @example\n * Typical usage\n * ```js\n * // create an injector\n * var $injector = angular.injector(['ng']);\n *\n * // use the injector to kick off your application\n * // use the type inference to auto inject arguments, or use implicit injection\n * $injector.invoke(function($rootScope, $compile, $document) {\n * $compile($document)($rootScope);\n * $rootScope.$digest();\n * });\n * ```\n *\n * Sometimes you want to get access to the injector of a currently running Angular app\n * from outside Angular. Perhaps, you want to inject and compile some markup after the\n * application has been bootstrapped. You can do this using the extra `injector()` added\n * to JQuery/jqLite elements. See {@link angular.element}.\n *\n * *This is fairly rare but could be the case if a third party library is injecting the\n * markup.*\n *\n * In the following example a new block of HTML containing a `ng-controller`\n * directive is added to the end of the document body by JQuery. We then compile and link\n * it into the current AngularJS scope.\n *\n * ```js\n * var $div = $('
{{content.label}}
');\n * $(document.body).append($div);\n *\n * angular.element(document).injector().invoke(function($compile) {\n * var scope = angular.element($div).scope();\n * $compile($div)(scope);\n * });\n * ```\n */\n\n\n/**\n * @ngdoc module\n * @name auto\n * @installation\n * @description\n *\n * Implicit module which gets automatically added to each {@link auto.$injector $injector}.\n */\n\nvar ARROW_ARG = /^([^(]+?)=>/;\nvar FN_ARGS = /^[^(]*\\(\\s*([^)]*)\\)/m;\nvar FN_ARG_SPLIT = /,/;\nvar FN_ARG = /^\\s*(_?)(\\S+?)\\1\\s*$/;\nvar STRIP_COMMENTS = /((\\/\\/.*$)|(\\/\\*[\\s\\S]*?\\*\\/))/mg;\nvar $injectorMinErr = minErr('$injector');\n\nfunction stringifyFn(fn) {\n // Support: Chrome 50-51 only\n // Creating a new string by adding `' '` at the end, to hack around some bug in Chrome v50/51\n // (See https://github.com/angular/angular.js/issues/14487.)\n // TODO (gkalpak): Remove workaround when Chrome v52 is released\n return Function.prototype.toString.call(fn) + ' ';\n}\n\nfunction extractArgs(fn) {\n var fnText = stringifyFn(fn).replace(STRIP_COMMENTS, ''),\n args = fnText.match(ARROW_ARG) || fnText.match(FN_ARGS);\n return args;\n}\n\nfunction anonFn(fn) {\n // For anonymous functions, showing at the very least the function signature can help in\n // debugging.\n var args = extractArgs(fn);\n if (args) {\n return 'function(' + (args[1] || '').replace(/[\\s\\r\\n]+/, ' ') + ')';\n }\n return 'fn';\n}\n\nfunction annotate(fn, strictDi, name) {\n var $inject,\n argDecl,\n last;\n\n if (typeof fn === 'function') {\n if (!($inject = fn.$inject)) {\n $inject = [];\n if (fn.length) {\n if (strictDi) {\n if (!isString(name) || !name) {\n name = fn.name || anonFn(fn);\n }\n throw $injectorMinErr('strictdi',\n '{0} is not using explicit annotation and cannot be invoked in strict mode', name);\n }\n argDecl = extractArgs(fn);\n forEach(argDecl[1].split(FN_ARG_SPLIT), function(arg) {\n arg.replace(FN_ARG, function(all, underscore, name) {\n $inject.push(name);\n });\n });\n }\n fn.$inject = $inject;\n }\n } else if (isArray(fn)) {\n last = fn.length - 1;\n assertArgFn(fn[last], 'fn');\n $inject = fn.slice(0, last);\n } else {\n assertArgFn(fn, 'fn', true);\n }\n return $inject;\n}\n\n///////////////////////////////////////\n\n/**\n * @ngdoc service\n * @name $injector\n *\n * @description\n *\n * `$injector` is used to retrieve object instances as defined by\n * {@link auto.$provide provider}, instantiate types, invoke methods,\n * and load modules.\n *\n * The following always holds true:\n *\n * ```js\n * var $injector = angular.injector();\n * expect($injector.get('$injector')).toBe($injector);\n * expect($injector.invoke(function($injector) {\n * return $injector;\n * })).toBe($injector);\n * ```\n *\n * # Injection Function Annotation\n *\n * JavaScript does not have annotations, and annotations are needed for dependency injection. The\n * following are all valid ways of annotating function with injection arguments and are equivalent.\n *\n * ```js\n * // inferred (only works if code not minified/obfuscated)\n * $injector.invoke(function(serviceA){});\n *\n * // annotated\n * function explicit(serviceA) {};\n * explicit.$inject = ['serviceA'];\n * $injector.invoke(explicit);\n *\n * // inline\n * $injector.invoke(['serviceA', function(serviceA){}]);\n * ```\n *\n * ## Inference\n *\n * In JavaScript calling `toString()` on a function returns the function definition. The definition\n * can then be parsed and the function arguments can be extracted. This method of discovering\n * annotations is disallowed when the injector is in strict mode.\n * *NOTE:* This does not work with minification, and obfuscation tools since these tools change the\n * argument names.\n *\n * ## `$inject` Annotation\n * By adding an `$inject` property onto a function the injection parameters can be specified.\n *\n * ## Inline\n * As an array of injection names, where the last item in the array is the function to call.\n */\n\n/**\n * @ngdoc method\n * @name $injector#get\n *\n * @description\n * Return an instance of the service.\n *\n * @param {string} name The name of the instance to retrieve.\n * @param {string=} caller An optional string to provide the origin of the function call for error messages.\n * @return {*} The instance.\n */\n\n/**\n * @ngdoc method\n * @name $injector#invoke\n *\n * @description\n * Invoke the method and supply the method arguments from the `$injector`.\n *\n * @param {Function|Array.} fn The injectable function to invoke. Function parameters are\n * injected according to the {@link guide/di $inject Annotation} rules.\n * @param {Object=} self The `this` for the invoked method.\n * @param {Object=} locals Optional object. If preset then any argument names are read from this\n * object first, before the `$injector` is consulted.\n * @returns {*} the value returned by the invoked `fn` function.\n */\n\n/**\n * @ngdoc method\n * @name $injector#has\n *\n * @description\n * Allows the user to query if the particular service exists.\n *\n * @param {string} name Name of the service to query.\n * @returns {boolean} `true` if injector has given service.\n */\n\n/**\n * @ngdoc method\n * @name $injector#instantiate\n * @description\n * Create a new instance of JS type. The method takes a constructor function, invokes the new\n * operator, and supplies all of the arguments to the constructor function as specified by the\n * constructor annotation.\n *\n * @param {Function} Type Annotated constructor function.\n * @param {Object=} locals Optional object. If preset then any argument names are read from this\n * object first, before the `$injector` is consulted.\n * @returns {Object} new instance of `Type`.\n */\n\n/**\n * @ngdoc method\n * @name $injector#annotate\n *\n * @description\n * Returns an array of service names which the function is requesting for injection. This API is\n * used by the injector to determine which services need to be injected into the function when the\n * function is invoked. There are three ways in which the function can be annotated with the needed\n * dependencies.\n *\n * # Argument names\n *\n * The simplest form is to extract the dependencies from the arguments of the function. This is done\n * by converting the function into a string using `toString()` method and extracting the argument\n * names.\n * ```js\n * // Given\n * function MyController($scope, $route) {\n * // ...\n * }\n *\n * // Then\n * expect(injector.annotate(MyController)).toEqual(['$scope', '$route']);\n * ```\n *\n * You can disallow this method by using strict injection mode.\n *\n * This method does not work with code minification / obfuscation. For this reason the following\n * annotation strategies are supported.\n *\n * # The `$inject` property\n *\n * If a function has an `$inject` property and its value is an array of strings, then the strings\n * represent names of services to be injected into the function.\n * ```js\n * // Given\n * var MyController = function(obfuscatedScope, obfuscatedRoute) {\n * // ...\n * }\n * // Define function dependencies\n * MyController['$inject'] = ['$scope', '$route'];\n *\n * // Then\n * expect(injector.annotate(MyController)).toEqual(['$scope', '$route']);\n * ```\n *\n * # The array notation\n *\n * It is often desirable to inline Injected functions and that's when setting the `$inject` property\n * is very inconvenient. In these situations using the array notation to specify the dependencies in\n * a way that survives minification is a better choice:\n *\n * ```js\n * // We wish to write this (not minification / obfuscation safe)\n * injector.invoke(function($compile, $rootScope) {\n * // ...\n * });\n *\n * // We are forced to write break inlining\n * var tmpFn = function(obfuscatedCompile, obfuscatedRootScope) {\n * // ...\n * };\n * tmpFn.$inject = ['$compile', '$rootScope'];\n * injector.invoke(tmpFn);\n *\n * // To better support inline function the inline annotation is supported\n * injector.invoke(['$compile', '$rootScope', function(obfCompile, obfRootScope) {\n * // ...\n * }]);\n *\n * // Therefore\n * expect(injector.annotate(\n * ['$compile', '$rootScope', function(obfus_$compile, obfus_$rootScope) {}])\n * ).toEqual(['$compile', '$rootScope']);\n * ```\n *\n * @param {Function|Array.} fn Function for which dependent service names need to\n * be retrieved as described above.\n *\n * @param {boolean=} [strictDi=false] Disallow argument name annotation inference.\n *\n * @returns {Array.} The names of the services which the function requires.\n */\n\n\n\n/**\n * @ngdoc service\n * @name $provide\n *\n * @description\n *\n * The {@link auto.$provide $provide} service has a number of methods for registering components\n * with the {@link auto.$injector $injector}. Many of these functions are also exposed on\n * {@link angular.Module}.\n *\n * An Angular **service** is a singleton object created by a **service factory**. These **service\n * factories** are functions which, in turn, are created by a **service provider**.\n * The **service providers** are constructor functions. When instantiated they must contain a\n * property called `$get`, which holds the **service factory** function.\n *\n * When you request a service, the {@link auto.$injector $injector} is responsible for finding the\n * correct **service provider**, instantiating it and then calling its `$get` **service factory**\n * function to get the instance of the **service**.\n *\n * Often services have no configuration options and there is no need to add methods to the service\n * provider. The provider will be no more than a constructor function with a `$get` property. For\n * these cases the {@link auto.$provide $provide} service has additional helper methods to register\n * services without specifying a provider.\n *\n * * {@link auto.$provide#provider provider(name, provider)} - registers a **service provider** with the\n * {@link auto.$injector $injector}\n * * {@link auto.$provide#constant constant(name, obj)} - registers a value/object that can be accessed by\n * providers and services.\n * * {@link auto.$provide#value value(name, obj)} - registers a value/object that can only be accessed by\n * services, not providers.\n * * {@link auto.$provide#factory factory(name, fn)} - registers a service **factory function**\n * that will be wrapped in a **service provider** object, whose `$get` property will contain the\n * given factory function.\n * * {@link auto.$provide#service service(name, Fn)} - registers a **constructor function**\n * that will be wrapped in a **service provider** object, whose `$get` property will instantiate\n * a new object using the given constructor function.\n * * {@link auto.$provide#decorator decorator(name, decorFn)} - registers a **decorator function** that\n * will be able to modify or replace the implementation of another service.\n *\n * See the individual methods for more information and examples.\n */\n\n/**\n * @ngdoc method\n * @name $provide#provider\n * @description\n *\n * Register a **provider function** with the {@link auto.$injector $injector}. Provider functions\n * are constructor functions, whose instances are responsible for \"providing\" a factory for a\n * service.\n *\n * Service provider names start with the name of the service they provide followed by `Provider`.\n * For example, the {@link ng.$log $log} service has a provider called\n * {@link ng.$logProvider $logProvider}.\n *\n * Service provider objects can have additional methods which allow configuration of the provider\n * and its service. Importantly, you can configure what kind of service is created by the `$get`\n * method, or how that service will act. For example, the {@link ng.$logProvider $logProvider} has a\n * method {@link ng.$logProvider#debugEnabled debugEnabled}\n * which lets you specify whether the {@link ng.$log $log} service will log debug messages to the\n * console or not.\n *\n * @param {string} name The name of the instance. NOTE: the provider will be available under `name +\n 'Provider'` key.\n * @param {(Object|function())} provider If the provider is:\n *\n * - `Object`: then it should have a `$get` method. The `$get` method will be invoked using\n * {@link auto.$injector#invoke $injector.invoke()} when an instance needs to be created.\n * - `Constructor`: a new instance of the provider will be created using\n * {@link auto.$injector#instantiate $injector.instantiate()}, then treated as `object`.\n *\n * @returns {Object} registered provider instance\n\n * @example\n *\n * The following example shows how to create a simple event tracking service and register it using\n * {@link auto.$provide#provider $provide.provider()}.\n *\n * ```js\n * // Define the eventTracker provider\n * function EventTrackerProvider() {\n * var trackingUrl = '/track';\n *\n * // A provider method for configuring where the tracked events should been saved\n * this.setTrackingUrl = function(url) {\n * trackingUrl = url;\n * };\n *\n * // The service factory function\n * this.$get = ['$http', function($http) {\n * var trackedEvents = {};\n * return {\n * // Call this to track an event\n * event: function(event) {\n * var count = trackedEvents[event] || 0;\n * count += 1;\n * trackedEvents[event] = count;\n * return count;\n * },\n * // Call this to save the tracked events to the trackingUrl\n * save: function() {\n * $http.post(trackingUrl, trackedEvents);\n * }\n * };\n * }];\n * }\n *\n * describe('eventTracker', function() {\n * var postSpy;\n *\n * beforeEach(module(function($provide) {\n * // Register the eventTracker provider\n * $provide.provider('eventTracker', EventTrackerProvider);\n * }));\n *\n * beforeEach(module(function(eventTrackerProvider) {\n * // Configure eventTracker provider\n * eventTrackerProvider.setTrackingUrl('/custom-track');\n * }));\n *\n * it('tracks events', inject(function(eventTracker) {\n * expect(eventTracker.event('login')).toEqual(1);\n * expect(eventTracker.event('login')).toEqual(2);\n * }));\n *\n * it('saves to the tracking url', inject(function(eventTracker, $http) {\n * postSpy = spyOn($http, 'post');\n * eventTracker.event('login');\n * eventTracker.save();\n * expect(postSpy).toHaveBeenCalled();\n * expect(postSpy.mostRecentCall.args[0]).not.toEqual('/track');\n * expect(postSpy.mostRecentCall.args[0]).toEqual('/custom-track');\n * expect(postSpy.mostRecentCall.args[1]).toEqual({ 'login': 1 });\n * }));\n * });\n * ```\n */\n\n/**\n * @ngdoc method\n * @name $provide#factory\n * @description\n *\n * Register a **service factory**, which will be called to return the service instance.\n * This is short for registering a service where its provider consists of only a `$get` property,\n * which is the given service factory function.\n * You should use {@link auto.$provide#factory $provide.factory(getFn)} if you do not need to\n * configure your service in a provider.\n *\n * @param {string} name The name of the instance.\n * @param {Function|Array.} $getFn The injectable $getFn for the instance creation.\n * Internally this is a short hand for `$provide.provider(name, {$get: $getFn})`.\n * @returns {Object} registered provider instance\n *\n * @example\n * Here is an example of registering a service\n * ```js\n * $provide.factory('ping', ['$http', function($http) {\n * return function ping() {\n * return $http.send('/ping');\n * };\n * }]);\n * ```\n * You would then inject and use this service like this:\n * ```js\n * someModule.controller('Ctrl', ['ping', function(ping) {\n * ping();\n * }]);\n * ```\n */\n\n\n/**\n * @ngdoc method\n * @name $provide#service\n * @description\n *\n * Register a **service constructor**, which will be invoked with `new` to create the service\n * instance.\n * This is short for registering a service where its provider's `$get` property is a factory\n * function that returns an instance instantiated by the injector from the service constructor\n * function.\n *\n * Internally it looks a bit like this:\n *\n * ```\n * {\n * $get: function() {\n * return $injector.instantiate(constructor);\n * }\n * }\n * ```\n *\n *\n * You should use {@link auto.$provide#service $provide.service(class)} if you define your service\n * as a type/class.\n *\n * @param {string} name The name of the instance.\n * @param {Function|Array.} constructor An injectable class (constructor function)\n * that will be instantiated.\n * @returns {Object} registered provider instance\n *\n * @example\n * Here is an example of registering a service using\n * {@link auto.$provide#service $provide.service(class)}.\n * ```js\n * var Ping = function($http) {\n * this.$http = $http;\n * };\n *\n * Ping.$inject = ['$http'];\n *\n * Ping.prototype.send = function() {\n * return this.$http.get('/ping');\n * };\n * $provide.service('ping', Ping);\n * ```\n * You would then inject and use this service like this:\n * ```js\n * someModule.controller('Ctrl', ['ping', function(ping) {\n * ping.send();\n * }]);\n * ```\n */\n\n\n/**\n * @ngdoc method\n * @name $provide#value\n * @description\n *\n * Register a **value service** with the {@link auto.$injector $injector}, such as a string, a\n * number, an array, an object or a function. This is short for registering a service where its\n * provider's `$get` property is a factory function that takes no arguments and returns the **value\n * service**. That also means it is not possible to inject other services into a value service.\n *\n * Value services are similar to constant services, except that they cannot be injected into a\n * module configuration function (see {@link angular.Module#config}) but they can be overridden by\n * an Angular {@link auto.$provide#decorator decorator}.\n *\n * @param {string} name The name of the instance.\n * @param {*} value The value.\n * @returns {Object} registered provider instance\n *\n * @example\n * Here are some examples of creating value services.\n * ```js\n * $provide.value('ADMIN_USER', 'admin');\n *\n * $provide.value('RoleLookup', { admin: 0, writer: 1, reader: 2 });\n *\n * $provide.value('halfOf', function(value) {\n * return value / 2;\n * });\n * ```\n */\n\n\n/**\n * @ngdoc method\n * @name $provide#constant\n * @description\n *\n * Register a **constant service** with the {@link auto.$injector $injector}, such as a string,\n * a number, an array, an object or a function. Like the {@link auto.$provide#value value}, it is not\n * possible to inject other services into a constant.\n *\n * But unlike {@link auto.$provide#value value}, a constant can be\n * injected into a module configuration function (see {@link angular.Module#config}) and it cannot\n * be overridden by an Angular {@link auto.$provide#decorator decorator}.\n *\n * @param {string} name The name of the constant.\n * @param {*} value The constant value.\n * @returns {Object} registered instance\n *\n * @example\n * Here a some examples of creating constants:\n * ```js\n * $provide.constant('SHARD_HEIGHT', 306);\n *\n * $provide.constant('MY_COLOURS', ['red', 'blue', 'grey']);\n *\n * $provide.constant('double', function(value) {\n * return value * 2;\n * });\n * ```\n */\n\n\n/**\n * @ngdoc method\n * @name $provide#decorator\n * @description\n *\n * Register a **decorator function** with the {@link auto.$injector $injector}. A decorator function\n * intercepts the creation of a service, allowing it to override or modify the behavior of the\n * service. The return value of the decorator function may be the original service, or a new service\n * that replaces (or wraps and delegates to) the original service.\n *\n * You can find out more about using decorators in the {@link guide/decorators} guide.\n *\n * @param {string} name The name of the service to decorate.\n * @param {Function|Array.} decorator This function will be invoked when the service needs to be\n * provided and should return the decorated service instance. The function is called using\n * the {@link auto.$injector#invoke injector.invoke} method and is therefore fully injectable.\n * Local injection arguments:\n *\n * * `$delegate` - The original service instance, which can be replaced, monkey patched, configured,\n * decorated or delegated to.\n *\n * @example\n * Here we decorate the {@link ng.$log $log} service to convert warnings to errors by intercepting\n * calls to {@link ng.$log#error $log.warn()}.\n * ```js\n * $provide.decorator('$log', ['$delegate', function($delegate) {\n * $delegate.warn = $delegate.error;\n * return $delegate;\n * }]);\n * ```\n */\n\n\nfunction createInjector(modulesToLoad, strictDi) {\n strictDi = (strictDi === true);\n var INSTANTIATING = {},\n providerSuffix = 'Provider',\n path = [],\n loadedModules = new HashMap([], true),\n providerCache = {\n $provide: {\n provider: supportObject(provider),\n factory: supportObject(factory),\n service: supportObject(service),\n value: supportObject(value),\n constant: supportObject(constant),\n decorator: decorator\n }\n },\n providerInjector = (providerCache.$injector =\n createInternalInjector(providerCache, function(serviceName, caller) {\n if (angular.isString(caller)) {\n path.push(caller);\n }\n throw $injectorMinErr('unpr', 'Unknown provider: {0}', path.join(' <- '));\n })),\n instanceCache = {},\n protoInstanceInjector =\n createInternalInjector(instanceCache, function(serviceName, caller) {\n var provider = providerInjector.get(serviceName + providerSuffix, caller);\n return instanceInjector.invoke(\n provider.$get, provider, undefined, serviceName);\n }),\n instanceInjector = protoInstanceInjector;\n\n providerCache['$injector' + providerSuffix] = { $get: valueFn(protoInstanceInjector) };\n var runBlocks = loadModules(modulesToLoad);\n instanceInjector = protoInstanceInjector.get('$injector');\n instanceInjector.strictDi = strictDi;\n forEach(runBlocks, function(fn) { if (fn) instanceInjector.invoke(fn); });\n\n return instanceInjector;\n\n ////////////////////////////////////\n // $provider\n ////////////////////////////////////\n\n function supportObject(delegate) {\n return function(key, value) {\n if (isObject(key)) {\n forEach(key, reverseParams(delegate));\n } else {\n return delegate(key, value);\n }\n };\n }\n\n function provider(name, provider_) {\n assertNotHasOwnProperty(name, 'service');\n if (isFunction(provider_) || isArray(provider_)) {\n provider_ = providerInjector.instantiate(provider_);\n }\n if (!provider_.$get) {\n throw $injectorMinErr('pget', 'Provider \\'{0}\\' must define $get factory method.', name);\n }\n return (providerCache[name + providerSuffix] = provider_);\n }\n\n function enforceReturnValue(name, factory) {\n return /** @this */ function enforcedReturnValue() {\n var result = instanceInjector.invoke(factory, this);\n if (isUndefined(result)) {\n throw $injectorMinErr('undef', 'Provider \\'{0}\\' must return a value from $get factory method.', name);\n }\n return result;\n };\n }\n\n function factory(name, factoryFn, enforce) {\n return provider(name, {\n $get: enforce !== false ? enforceReturnValue(name, factoryFn) : factoryFn\n });\n }\n\n function service(name, constructor) {\n return factory(name, ['$injector', function($injector) {\n return $injector.instantiate(constructor);\n }]);\n }\n\n function value(name, val) { return factory(name, valueFn(val), false); }\n\n function constant(name, value) {\n assertNotHasOwnProperty(name, 'constant');\n providerCache[name] = value;\n instanceCache[name] = value;\n }\n\n function decorator(serviceName, decorFn) {\n var origProvider = providerInjector.get(serviceName + providerSuffix),\n orig$get = origProvider.$get;\n\n origProvider.$get = function() {\n var origInstance = instanceInjector.invoke(orig$get, origProvider);\n return instanceInjector.invoke(decorFn, null, {$delegate: origInstance});\n };\n }\n\n ////////////////////////////////////\n // Module Loading\n ////////////////////////////////////\n function loadModules(modulesToLoad) {\n assertArg(isUndefined(modulesToLoad) || isArray(modulesToLoad), 'modulesToLoad', 'not an array');\n var runBlocks = [], moduleFn;\n forEach(modulesToLoad, function(module) {\n if (loadedModules.get(module)) return;\n loadedModules.put(module, true);\n\n function runInvokeQueue(queue) {\n var i, ii;\n for (i = 0, ii = queue.length; i < ii; i++) {\n var invokeArgs = queue[i],\n provider = providerInjector.get(invokeArgs[0]);\n\n provider[invokeArgs[1]].apply(provider, invokeArgs[2]);\n }\n }\n\n try {\n if (isString(module)) {\n moduleFn = angularModule(module);\n runBlocks = runBlocks.concat(loadModules(moduleFn.requires)).concat(moduleFn._runBlocks);\n runInvokeQueue(moduleFn._invokeQueue);\n runInvokeQueue(moduleFn._configBlocks);\n } else if (isFunction(module)) {\n runBlocks.push(providerInjector.invoke(module));\n } else if (isArray(module)) {\n runBlocks.push(providerInjector.invoke(module));\n } else {\n assertArgFn(module, 'module');\n }\n } catch (e) {\n if (isArray(module)) {\n module = module[module.length - 1];\n }\n if (e.message && e.stack && e.stack.indexOf(e.message) === -1) {\n // Safari & FF's stack traces don't contain error.message content\n // unlike those of Chrome and IE\n // So if stack doesn't contain message, we create a new string that contains both.\n // Since error.stack is read-only in Safari, I'm overriding e and not e.stack here.\n // eslint-disable-next-line no-ex-assign\n e = e.message + '\\n' + e.stack;\n }\n throw $injectorMinErr('modulerr', 'Failed to instantiate module {0} due to:\\n{1}',\n module, e.stack || e.message || e);\n }\n });\n return runBlocks;\n }\n\n ////////////////////////////////////\n // internal Injector\n ////////////////////////////////////\n\n function createInternalInjector(cache, factory) {\n\n function getService(serviceName, caller) {\n if (cache.hasOwnProperty(serviceName)) {\n if (cache[serviceName] === INSTANTIATING) {\n throw $injectorMinErr('cdep', 'Circular dependency found: {0}',\n serviceName + ' <- ' + path.join(' <- '));\n }\n return cache[serviceName];\n } else {\n try {\n path.unshift(serviceName);\n cache[serviceName] = INSTANTIATING;\n cache[serviceName] = factory(serviceName, caller);\n return cache[serviceName];\n } catch (err) {\n if (cache[serviceName] === INSTANTIATING) {\n delete cache[serviceName];\n }\n throw err;\n } finally {\n path.shift();\n }\n }\n }\n\n\n function injectionArgs(fn, locals, serviceName) {\n var args = [],\n $inject = createInjector.$$annotate(fn, strictDi, serviceName);\n\n for (var i = 0, length = $inject.length; i < length; i++) {\n var key = $inject[i];\n if (typeof key !== 'string') {\n throw $injectorMinErr('itkn',\n 'Incorrect injection token! Expected service name as string, got {0}', key);\n }\n args.push(locals && locals.hasOwnProperty(key) ? locals[key] :\n getService(key, serviceName));\n }\n return args;\n }\n\n function isClass(func) {\n // Support: IE 9-11 only\n // IE 9-11 do not support classes and IE9 leaks with the code below.\n if (msie || typeof func !== 'function') {\n return false;\n }\n var result = func.$$ngIsClass;\n if (!isBoolean(result)) {\n // Support: Edge 12-13 only\n // See: https://developer.microsoft.com/en-us/microsoft-edge/platform/issues/6156135/\n result = func.$$ngIsClass = /^(?:class\\b|constructor\\()/.test(stringifyFn(func));\n }\n return result;\n }\n\n function invoke(fn, self, locals, serviceName) {\n if (typeof locals === 'string') {\n serviceName = locals;\n locals = null;\n }\n\n var args = injectionArgs(fn, locals, serviceName);\n if (isArray(fn)) {\n fn = fn[fn.length - 1];\n }\n\n if (!isClass(fn)) {\n // http://jsperf.com/angularjs-invoke-apply-vs-switch\n // #5388\n return fn.apply(self, args);\n } else {\n args.unshift(null);\n return new (Function.prototype.bind.apply(fn, args))();\n }\n }\n\n\n function instantiate(Type, locals, serviceName) {\n // Check if Type is annotated and use just the given function at n-1 as parameter\n // e.g. someModule.factory('greeter', ['$window', function(renamed$window) {}]);\n var ctor = (isArray(Type) ? Type[Type.length - 1] : Type);\n var args = injectionArgs(Type, locals, serviceName);\n // Empty object at position 0 is ignored for invocation with `new`, but required.\n args.unshift(null);\n return new (Function.prototype.bind.apply(ctor, args))();\n }\n\n\n return {\n invoke: invoke,\n instantiate: instantiate,\n get: getService,\n annotate: createInjector.$$annotate,\n has: function(name) {\n return providerCache.hasOwnProperty(name + providerSuffix) || cache.hasOwnProperty(name);\n }\n };\n }\n}\n\ncreateInjector.$$annotate = annotate;\n\n/**\n * @ngdoc provider\n * @name $anchorScrollProvider\n * @this\n *\n * @description\n * Use `$anchorScrollProvider` to disable automatic scrolling whenever\n * {@link ng.$location#hash $location.hash()} changes.\n */\nfunction $AnchorScrollProvider() {\n\n var autoScrollingEnabled = true;\n\n /**\n * @ngdoc method\n * @name $anchorScrollProvider#disableAutoScrolling\n *\n * @description\n * By default, {@link ng.$anchorScroll $anchorScroll()} will automatically detect changes to\n * {@link ng.$location#hash $location.hash()} and scroll to the element matching the new hash.
\n * Use this method to disable automatic scrolling.\n *\n * If automatic scrolling is disabled, one must explicitly call\n * {@link ng.$anchorScroll $anchorScroll()} in order to scroll to the element related to the\n * current hash.\n */\n this.disableAutoScrolling = function() {\n autoScrollingEnabled = false;\n };\n\n /**\n * @ngdoc service\n * @name $anchorScroll\n * @kind function\n * @requires $window\n * @requires $location\n * @requires $rootScope\n *\n * @description\n * When called, it scrolls to the element related to the specified `hash` or (if omitted) to the\n * current value of {@link ng.$location#hash $location.hash()}, according to the rules specified\n * in the\n * [HTML5 spec](http://www.w3.org/html/wg/drafts/html/master/browsers.html#an-indicated-part-of-the-document).\n *\n * It also watches the {@link ng.$location#hash $location.hash()} and automatically scrolls to\n * match any anchor whenever it changes. This can be disabled by calling\n * {@link ng.$anchorScrollProvider#disableAutoScrolling $anchorScrollProvider.disableAutoScrolling()}.\n *\n * Additionally, you can use its {@link ng.$anchorScroll#yOffset yOffset} property to specify a\n * vertical scroll-offset (either fixed or dynamic).\n *\n * @param {string=} hash The hash specifying the element to scroll to. If omitted, the value of\n * {@link ng.$location#hash $location.hash()} will be used.\n *\n * @property {(number|function|jqLite)} yOffset\n * If set, specifies a vertical scroll-offset. This is often useful when there are fixed\n * positioned elements at the top of the page, such as navbars, headers etc.\n *\n * `yOffset` can be specified in various ways:\n * - **number**: A fixed number of pixels to be used as offset.

\n * - **function**: A getter function called everytime `$anchorScroll()` is executed. Must return\n * a number representing the offset (in pixels).

\n * - **jqLite**: A jqLite/jQuery element to be used for specifying the offset. The distance from\n * the top of the page to the element's bottom will be used as offset.
\n * **Note**: The element will be taken into account only as long as its `position` is set to\n * `fixed`. This option is useful, when dealing with responsive navbars/headers that adjust\n * their height and/or positioning according to the viewport's size.\n *\n *
\n *
\n * In order for `yOffset` to work properly, scrolling should take place on the document's root and\n * not some child element.\n *
\n *\n * @example\n \n \n
\n Go to bottom\n You're at the bottom!\n
\n
\n \n angular.module('anchorScrollExample', [])\n .controller('ScrollController', ['$scope', '$location', '$anchorScroll',\n function($scope, $location, $anchorScroll) {\n $scope.gotoBottom = function() {\n // set the location.hash to the id of\n // the element you wish to scroll to.\n $location.hash('bottom');\n\n // call $anchorScroll()\n $anchorScroll();\n };\n }]);\n \n \n #scrollArea {\n height: 280px;\n overflow: auto;\n }\n\n #bottom {\n display: block;\n margin-top: 2000px;\n }\n \n
\n *\n *
\n * The example below illustrates the use of a vertical scroll-offset (specified as a fixed value).\n * See {@link ng.$anchorScroll#yOffset $anchorScroll.yOffset} for more details.\n *\n * @example\n \n \n \n
\n Anchor {{x}} of 5\n
\n
\n \n angular.module('anchorScrollOffsetExample', [])\n .run(['$anchorScroll', function($anchorScroll) {\n $anchorScroll.yOffset = 50; // always scroll by 50 extra pixels\n }])\n .controller('headerCtrl', ['$anchorScroll', '$location', '$scope',\n function($anchorScroll, $location, $scope) {\n $scope.gotoAnchor = function(x) {\n var newHash = 'anchor' + x;\n if ($location.hash() !== newHash) {\n // set the $location.hash to `newHash` and\n // $anchorScroll will automatically scroll to it\n $location.hash('anchor' + x);\n } else {\n // call $anchorScroll() explicitly,\n // since $location.hash hasn't changed\n $anchorScroll();\n }\n };\n }\n ]);\n \n \n body {\n padding-top: 50px;\n }\n\n .anchor {\n border: 2px dashed DarkOrchid;\n padding: 10px 10px 200px 10px;\n }\n\n .fixed-header {\n background-color: rgba(0, 0, 0, 0.2);\n height: 50px;\n position: fixed;\n top: 0; left: 0; right: 0;\n }\n\n .fixed-header > a {\n display: inline-block;\n margin: 5px 15px;\n }\n \n
\n */\n this.$get = ['$window', '$location', '$rootScope', function($window, $location, $rootScope) {\n var document = $window.document;\n\n // Helper function to get first anchor from a NodeList\n // (using `Array#some()` instead of `angular#forEach()` since it's more performant\n // and working in all supported browsers.)\n function getFirstAnchor(list) {\n var result = null;\n Array.prototype.some.call(list, function(element) {\n if (nodeName_(element) === 'a') {\n result = element;\n return true;\n }\n });\n return result;\n }\n\n function getYOffset() {\n\n var offset = scroll.yOffset;\n\n if (isFunction(offset)) {\n offset = offset();\n } else if (isElement(offset)) {\n var elem = offset[0];\n var style = $window.getComputedStyle(elem);\n if (style.position !== 'fixed') {\n offset = 0;\n } else {\n offset = elem.getBoundingClientRect().bottom;\n }\n } else if (!isNumber(offset)) {\n offset = 0;\n }\n\n return offset;\n }\n\n function scrollTo(elem) {\n if (elem) {\n elem.scrollIntoView();\n\n var offset = getYOffset();\n\n if (offset) {\n // `offset` is the number of pixels we should scroll UP in order to align `elem` properly.\n // This is true ONLY if the call to `elem.scrollIntoView()` initially aligns `elem` at the\n // top of the viewport.\n //\n // IF the number of pixels from the top of `elem` to the end of the page's content is less\n // than the height of the viewport, then `elem.scrollIntoView()` will align the `elem` some\n // way down the page.\n //\n // This is often the case for elements near the bottom of the page.\n //\n // In such cases we do not need to scroll the whole `offset` up, just the difference between\n // the top of the element and the offset, which is enough to align the top of `elem` at the\n // desired position.\n var elemTop = elem.getBoundingClientRect().top;\n $window.scrollBy(0, elemTop - offset);\n }\n } else {\n $window.scrollTo(0, 0);\n }\n }\n\n function scroll(hash) {\n // Allow numeric hashes\n hash = isString(hash) ? hash : isNumber(hash) ? hash.toString() : $location.hash();\n var elm;\n\n // empty hash, scroll to the top of the page\n if (!hash) scrollTo(null);\n\n // element with given id\n else if ((elm = document.getElementById(hash))) scrollTo(elm);\n\n // first anchor with given name :-D\n else if ((elm = getFirstAnchor(document.getElementsByName(hash)))) scrollTo(elm);\n\n // no element and hash === 'top', scroll to the top of the page\n else if (hash === 'top') scrollTo(null);\n }\n\n // does not scroll when user clicks on anchor link that is currently on\n // (no url change, no $location.hash() change), browser native does scroll\n if (autoScrollingEnabled) {\n $rootScope.$watch(function autoScrollWatch() {return $location.hash();},\n function autoScrollWatchAction(newVal, oldVal) {\n // skip the initial scroll if $location.hash is empty\n if (newVal === oldVal && newVal === '') return;\n\n jqLiteDocumentLoaded(function() {\n $rootScope.$evalAsync(scroll);\n });\n });\n }\n\n return scroll;\n }];\n}\n\nvar $animateMinErr = minErr('$animate');\nvar ELEMENT_NODE = 1;\nvar NG_ANIMATE_CLASSNAME = 'ng-animate';\n\nfunction mergeClasses(a,b) {\n if (!a && !b) return '';\n if (!a) return b;\n if (!b) return a;\n if (isArray(a)) a = a.join(' ');\n if (isArray(b)) b = b.join(' ');\n return a + ' ' + b;\n}\n\nfunction extractElementNode(element) {\n for (var i = 0; i < element.length; i++) {\n var elm = element[i];\n if (elm.nodeType === ELEMENT_NODE) {\n return elm;\n }\n }\n}\n\nfunction splitClasses(classes) {\n if (isString(classes)) {\n classes = classes.split(' ');\n }\n\n // Use createMap() to prevent class assumptions involving property names in\n // Object.prototype\n var obj = createMap();\n forEach(classes, function(klass) {\n // sometimes the split leaves empty string values\n // incase extra spaces were applied to the options\n if (klass.length) {\n obj[klass] = true;\n }\n });\n return obj;\n}\n\n// if any other type of options value besides an Object value is\n// passed into the $animate.method() animation then this helper code\n// will be run which will ignore it. While this patch is not the\n// greatest solution to this, a lot of existing plugins depend on\n// $animate to either call the callback (< 1.2) or return a promise\n// that can be changed. This helper function ensures that the options\n// are wiped clean incase a callback function is provided.\nfunction prepareAnimateOptions(options) {\n return isObject(options)\n ? options\n : {};\n}\n\nvar $$CoreAnimateJsProvider = /** @this */ function() {\n this.$get = noop;\n};\n\n// this is prefixed with Core since it conflicts with\n// the animateQueueProvider defined in ngAnimate/animateQueue.js\nvar $$CoreAnimateQueueProvider = /** @this */ function() {\n var postDigestQueue = new HashMap();\n var postDigestElements = [];\n\n this.$get = ['$$AnimateRunner', '$rootScope',\n function($$AnimateRunner, $rootScope) {\n return {\n enabled: noop,\n on: noop,\n off: noop,\n pin: noop,\n\n push: function(element, event, options, domOperation) {\n if (domOperation) {\n domOperation();\n }\n\n options = options || {};\n if (options.from) {\n element.css(options.from);\n }\n if (options.to) {\n element.css(options.to);\n }\n\n if (options.addClass || options.removeClass) {\n addRemoveClassesPostDigest(element, options.addClass, options.removeClass);\n }\n\n var runner = new $$AnimateRunner();\n\n // since there are no animations to run the runner needs to be\n // notified that the animation call is complete.\n runner.complete();\n return runner;\n }\n };\n\n\n function updateData(data, classes, value) {\n var changed = false;\n if (classes) {\n classes = isString(classes) ? classes.split(' ') :\n isArray(classes) ? classes : [];\n forEach(classes, function(className) {\n if (className) {\n changed = true;\n data[className] = value;\n }\n });\n }\n return changed;\n }\n\n function handleCSSClassChanges() {\n forEach(postDigestElements, function(element) {\n var data = postDigestQueue.get(element);\n if (data) {\n var existing = splitClasses(element.attr('class'));\n var toAdd = '';\n var toRemove = '';\n forEach(data, function(status, className) {\n var hasClass = !!existing[className];\n if (status !== hasClass) {\n if (status) {\n toAdd += (toAdd.length ? ' ' : '') + className;\n } else {\n toRemove += (toRemove.length ? ' ' : '') + className;\n }\n }\n });\n\n forEach(element, function(elm) {\n if (toAdd) {\n jqLiteAddClass(elm, toAdd);\n }\n if (toRemove) {\n jqLiteRemoveClass(elm, toRemove);\n }\n });\n postDigestQueue.remove(element);\n }\n });\n postDigestElements.length = 0;\n }\n\n\n function addRemoveClassesPostDigest(element, add, remove) {\n var data = postDigestQueue.get(element) || {};\n\n var classesAdded = updateData(data, add, true);\n var classesRemoved = updateData(data, remove, false);\n\n if (classesAdded || classesRemoved) {\n\n postDigestQueue.put(element, data);\n postDigestElements.push(element);\n\n if (postDigestElements.length === 1) {\n $rootScope.$$postDigest(handleCSSClassChanges);\n }\n }\n }\n }];\n};\n\n/**\n * @ngdoc provider\n * @name $animateProvider\n *\n * @description\n * Default implementation of $animate that doesn't perform any animations, instead just\n * synchronously performs DOM updates and resolves the returned runner promise.\n *\n * In order to enable animations the `ngAnimate` module has to be loaded.\n *\n * To see the functional implementation check out `src/ngAnimate/animate.js`.\n */\nvar $AnimateProvider = ['$provide', /** @this */ function($provide) {\n var provider = this;\n\n this.$$registeredAnimations = Object.create(null);\n\n /**\n * @ngdoc method\n * @name $animateProvider#register\n *\n * @description\n * Registers a new injectable animation factory function. The factory function produces the\n * animation object which contains callback functions for each event that is expected to be\n * animated.\n *\n * * `eventFn`: `function(element, ... , doneFunction, options)`\n * The element to animate, the `doneFunction` and the options fed into the animation. Depending\n * on the type of animation additional arguments will be injected into the animation function. The\n * list below explains the function signatures for the different animation methods:\n *\n * - setClass: function(element, addedClasses, removedClasses, doneFunction, options)\n * - addClass: function(element, addedClasses, doneFunction, options)\n * - removeClass: function(element, removedClasses, doneFunction, options)\n * - enter, leave, move: function(element, doneFunction, options)\n * - animate: function(element, fromStyles, toStyles, doneFunction, options)\n *\n * Make sure to trigger the `doneFunction` once the animation is fully complete.\n *\n * ```js\n * return {\n * //enter, leave, move signature\n * eventFn : function(element, done, options) {\n * //code to run the animation\n * //once complete, then run done()\n * return function endFunction(wasCancelled) {\n * //code to cancel the animation\n * }\n * }\n * }\n * ```\n *\n * @param {string} name The name of the animation (this is what the class-based CSS value will be compared to).\n * @param {Function} factory The factory function that will be executed to return the animation\n * object.\n */\n this.register = function(name, factory) {\n if (name && name.charAt(0) !== '.') {\n throw $animateMinErr('notcsel', 'Expecting class selector starting with \\'.\\' got \\'{0}\\'.', name);\n }\n\n var key = name + '-animation';\n provider.$$registeredAnimations[name.substr(1)] = key;\n $provide.factory(key, factory);\n };\n\n /**\n * @ngdoc method\n * @name $animateProvider#classNameFilter\n *\n * @description\n * Sets and/or returns the CSS class regular expression that is checked when performing\n * an animation. Upon bootstrap the classNameFilter value is not set at all and will\n * therefore enable $animate to attempt to perform an animation on any element that is triggered.\n * When setting the `classNameFilter` value, animations will only be performed on elements\n * that successfully match the filter expression. This in turn can boost performance\n * for low-powered devices as well as applications containing a lot of structural operations.\n * @param {RegExp=} expression The className expression which will be checked against all animations\n * @return {RegExp} The current CSS className expression value. If null then there is no expression value\n */\n this.classNameFilter = function(expression) {\n if (arguments.length === 1) {\n this.$$classNameFilter = (expression instanceof RegExp) ? expression : null;\n if (this.$$classNameFilter) {\n var reservedRegex = new RegExp('(\\\\s+|\\\\/)' + NG_ANIMATE_CLASSNAME + '(\\\\s+|\\\\/)');\n if (reservedRegex.test(this.$$classNameFilter.toString())) {\n throw $animateMinErr('nongcls','$animateProvider.classNameFilter(regex) prohibits accepting a regex value which matches/contains the \"{0}\" CSS class.', NG_ANIMATE_CLASSNAME);\n }\n }\n }\n return this.$$classNameFilter;\n };\n\n this.$get = ['$$animateQueue', function($$animateQueue) {\n function domInsert(element, parentElement, afterElement) {\n // if for some reason the previous element was removed\n // from the dom sometime before this code runs then let's\n // just stick to using the parent element as the anchor\n if (afterElement) {\n var afterNode = extractElementNode(afterElement);\n if (afterNode && !afterNode.parentNode && !afterNode.previousElementSibling) {\n afterElement = null;\n }\n }\n if (afterElement) {\n afterElement.after(element);\n } else {\n parentElement.prepend(element);\n }\n }\n\n /**\n * @ngdoc service\n * @name $animate\n * @description The $animate service exposes a series of DOM utility methods that provide support\n * for animation hooks. The default behavior is the application of DOM operations, however,\n * when an animation is detected (and animations are enabled), $animate will do the heavy lifting\n * to ensure that animation runs with the triggered DOM operation.\n *\n * By default $animate doesn't trigger any animations. This is because the `ngAnimate` module isn't\n * included and only when it is active then the animation hooks that `$animate` triggers will be\n * functional. Once active then all structural `ng-` directives will trigger animations as they perform\n * their DOM-related operations (enter, leave and move). Other directives such as `ngClass`,\n * `ngShow`, `ngHide` and `ngMessages` also provide support for animations.\n *\n * It is recommended that the`$animate` service is always used when executing DOM-related procedures within directives.\n *\n * To learn more about enabling animation support, click here to visit the\n * {@link ngAnimate ngAnimate module page}.\n */\n return {\n // we don't call it directly since non-existant arguments may\n // be interpreted as null within the sub enabled function\n\n /**\n *\n * @ngdoc method\n * @name $animate#on\n * @kind function\n * @description Sets up an event listener to fire whenever the animation event (enter, leave, move, etc...)\n * has fired on the given element or among any of its children. Once the listener is fired, the provided callback\n * is fired with the following params:\n *\n * ```js\n * $animate.on('enter', container,\n * function callback(element, phase) {\n * // cool we detected an enter animation within the container\n * }\n * );\n * ```\n *\n * @param {string} event the animation event that will be captured (e.g. enter, leave, move, addClass, removeClass, etc...)\n * @param {DOMElement} container the container element that will capture each of the animation events that are fired on itself\n * as well as among its children\n * @param {Function} callback the callback function that will be fired when the listener is triggered\n *\n * The arguments present in the callback function are:\n * * `element` - The captured DOM element that the animation was fired on.\n * * `phase` - The phase of the animation. The two possible phases are **start** (when the animation starts) and **close** (when it ends).\n */\n on: $$animateQueue.on,\n\n /**\n *\n * @ngdoc method\n * @name $animate#off\n * @kind function\n * @description Deregisters an event listener based on the event which has been associated with the provided element. This method\n * can be used in three different ways depending on the arguments:\n *\n * ```js\n * // remove all the animation event listeners listening for `enter`\n * $animate.off('enter');\n *\n * // remove listeners for all animation events from the container element\n * $animate.off(container);\n *\n * // remove all the animation event listeners listening for `enter` on the given element and its children\n * $animate.off('enter', container);\n *\n * // remove the event listener function provided by `callback` that is set\n * // to listen for `enter` on the given `container` as well as its children\n * $animate.off('enter', container, callback);\n * ```\n *\n * @param {string|DOMElement} event|container the animation event (e.g. enter, leave, move,\n * addClass, removeClass, etc...), or the container element. If it is the element, all other\n * arguments are ignored.\n * @param {DOMElement=} container the container element the event listener was placed on\n * @param {Function=} callback the callback function that was registered as the listener\n */\n off: $$animateQueue.off,\n\n /**\n * @ngdoc method\n * @name $animate#pin\n * @kind function\n * @description Associates the provided element with a host parent element to allow the element to be animated even if it exists\n * outside of the DOM structure of the Angular application. By doing so, any animation triggered via `$animate` can be issued on the\n * element despite being outside the realm of the application or within another application. Say for example if the application\n * was bootstrapped on an element that is somewhere inside of the `` tag, but we wanted to allow for an element to be situated\n * as a direct child of `document.body`, then this can be achieved by pinning the element via `$animate.pin(element)`. Keep in mind\n * that calling `$animate.pin(element, parentElement)` will not actually insert into the DOM anywhere; it will just create the association.\n *\n * Note that this feature is only active when the `ngAnimate` module is used.\n *\n * @param {DOMElement} element the external element that will be pinned\n * @param {DOMElement} parentElement the host parent element that will be associated with the external element\n */\n pin: $$animateQueue.pin,\n\n /**\n *\n * @ngdoc method\n * @name $animate#enabled\n * @kind function\n * @description Used to get and set whether animations are enabled or not on the entire application or on an element and its children. This\n * function can be called in four ways:\n *\n * ```js\n * // returns true or false\n * $animate.enabled();\n *\n * // changes the enabled state for all animations\n * $animate.enabled(false);\n * $animate.enabled(true);\n *\n * // returns true or false if animations are enabled for an element\n * $animate.enabled(element);\n *\n * // changes the enabled state for an element and its children\n * $animate.enabled(element, true);\n * $animate.enabled(element, false);\n * ```\n *\n * @param {DOMElement=} element the element that will be considered for checking/setting the enabled state\n * @param {boolean=} enabled whether or not the animations will be enabled for the element\n *\n * @return {boolean} whether or not animations are enabled\n */\n enabled: $$animateQueue.enabled,\n\n /**\n * @ngdoc method\n * @name $animate#cancel\n * @kind function\n * @description Cancels the provided animation.\n *\n * @param {Promise} animationPromise The animation promise that is returned when an animation is started.\n */\n cancel: function(runner) {\n if (runner.end) {\n runner.end();\n }\n },\n\n /**\n *\n * @ngdoc method\n * @name $animate#enter\n * @kind function\n * @description Inserts the element into the DOM either after the `after` element (if provided) or\n * as the first child within the `parent` element and then triggers an animation.\n * A promise is returned that will be resolved during the next digest once the animation\n * has completed.\n *\n * @param {DOMElement} element the element which will be inserted into the DOM\n * @param {DOMElement} parent the parent element which will append the element as\n * a child (so long as the after element is not present)\n * @param {DOMElement=} after the sibling element after which the element will be appended\n * @param {object=} options an optional collection of options/styles that will be applied to the element.\n * The object can have the following properties:\n *\n * - **addClass** - `{string}` - space-separated CSS classes to add to element\n * - **from** - `{Object}` - CSS properties & values at the beginning of animation. Must have matching `to`\n * - **removeClass** - `{string}` - space-separated CSS classes to remove from element\n * - **to** - `{Object}` - CSS properties & values at end of animation. Must have matching `from`\n *\n * @return {Promise} the animation callback promise\n */\n enter: function(element, parent, after, options) {\n parent = parent && jqLite(parent);\n after = after && jqLite(after);\n parent = parent || after.parent();\n domInsert(element, parent, after);\n return $$animateQueue.push(element, 'enter', prepareAnimateOptions(options));\n },\n\n /**\n *\n * @ngdoc method\n * @name $animate#move\n * @kind function\n * @description Inserts (moves) the element into its new position in the DOM either after\n * the `after` element (if provided) or as the first child within the `parent` element\n * and then triggers an animation. A promise is returned that will be resolved\n * during the next digest once the animation has completed.\n *\n * @param {DOMElement} element the element which will be moved into the new DOM position\n * @param {DOMElement} parent the parent element which will append the element as\n * a child (so long as the after element is not present)\n * @param {DOMElement=} after the sibling element after which the element will be appended\n * @param {object=} options an optional collection of options/styles that will be applied to the element.\n * The object can have the following properties:\n *\n * - **addClass** - `{string}` - space-separated CSS classes to add to element\n * - **from** - `{Object}` - CSS properties & values at the beginning of animation. Must have matching `to`\n * - **removeClass** - `{string}` - space-separated CSS classes to remove from element\n * - **to** - `{Object}` - CSS properties & values at end of animation. Must have matching `from`\n *\n * @return {Promise} the animation callback promise\n */\n move: function(element, parent, after, options) {\n parent = parent && jqLite(parent);\n after = after && jqLite(after);\n parent = parent || after.parent();\n domInsert(element, parent, after);\n return $$animateQueue.push(element, 'move', prepareAnimateOptions(options));\n },\n\n /**\n * @ngdoc method\n * @name $animate#leave\n * @kind function\n * @description Triggers an animation and then removes the element from the DOM.\n * When the function is called a promise is returned that will be resolved during the next\n * digest once the animation has completed.\n *\n * @param {DOMElement} element the element which will be removed from the DOM\n * @param {object=} options an optional collection of options/styles that will be applied to the element.\n * The object can have the following properties:\n *\n * - **addClass** - `{string}` - space-separated CSS classes to add to element\n * - **from** - `{Object}` - CSS properties & values at the beginning of animation. Must have matching `to`\n * - **removeClass** - `{string}` - space-separated CSS classes to remove from element\n * - **to** - `{Object}` - CSS properties & values at end of animation. Must have matching `from`\n *\n * @return {Promise} the animation callback promise\n */\n leave: function(element, options) {\n return $$animateQueue.push(element, 'leave', prepareAnimateOptions(options), function() {\n element.remove();\n });\n },\n\n /**\n * @ngdoc method\n * @name $animate#addClass\n * @kind function\n *\n * @description Triggers an addClass animation surrounding the addition of the provided CSS class(es). Upon\n * execution, the addClass operation will only be handled after the next digest and it will not trigger an\n * animation if element already contains the CSS class or if the class is removed at a later step.\n * Note that class-based animations are treated differently compared to structural animations\n * (like enter, move and leave) since the CSS classes may be added/removed at different points\n * depending if CSS or JavaScript animations are used.\n *\n * @param {DOMElement} element the element which the CSS classes will be applied to\n * @param {string} className the CSS class(es) that will be added (multiple classes are separated via spaces)\n * @param {object=} options an optional collection of options/styles that will be applied to the element.\n * The object can have the following properties:\n *\n * - **addClass** - `{string}` - space-separated CSS classes to add to element\n * - **from** - `{Object}` - CSS properties & values at the beginning of animation. Must have matching `to`\n * - **removeClass** - `{string}` - space-separated CSS classes to remove from element\n * - **to** - `{Object}` - CSS properties & values at end of animation. Must have matching `from`\n *\n * @return {Promise} the animation callback promise\n */\n addClass: function(element, className, options) {\n options = prepareAnimateOptions(options);\n options.addClass = mergeClasses(options.addclass, className);\n return $$animateQueue.push(element, 'addClass', options);\n },\n\n /**\n * @ngdoc method\n * @name $animate#removeClass\n * @kind function\n *\n * @description Triggers a removeClass animation surrounding the removal of the provided CSS class(es). Upon\n * execution, the removeClass operation will only be handled after the next digest and it will not trigger an\n * animation if element does not contain the CSS class or if the class is added at a later step.\n * Note that class-based animations are treated differently compared to structural animations\n * (like enter, move and leave) since the CSS classes may be added/removed at different points\n * depending if CSS or JavaScript animations are used.\n *\n * @param {DOMElement} element the element which the CSS classes will be applied to\n * @param {string} className the CSS class(es) that will be removed (multiple classes are separated via spaces)\n * @param {object=} options an optional collection of options/styles that will be applied to the element.\n * The object can have the following properties:\n *\n * - **addClass** - `{string}` - space-separated CSS classes to add to element\n * - **from** - `{Object}` - CSS properties & values at the beginning of animation. Must have matching `to`\n * - **removeClass** - `{string}` - space-separated CSS classes to remove from element\n * - **to** - `{Object}` - CSS properties & values at end of animation. Must have matching `from`\n *\n * @return {Promise} the animation callback promise\n */\n removeClass: function(element, className, options) {\n options = prepareAnimateOptions(options);\n options.removeClass = mergeClasses(options.removeClass, className);\n return $$animateQueue.push(element, 'removeClass', options);\n },\n\n /**\n * @ngdoc method\n * @name $animate#setClass\n * @kind function\n *\n * @description Performs both the addition and removal of a CSS classes on an element and (during the process)\n * triggers an animation surrounding the class addition/removal. Much like `$animate.addClass` and\n * `$animate.removeClass`, `setClass` will only evaluate the classes being added/removed once a digest has\n * passed. Note that class-based animations are treated differently compared to structural animations\n * (like enter, move and leave) since the CSS classes may be added/removed at different points\n * depending if CSS or JavaScript animations are used.\n *\n * @param {DOMElement} element the element which the CSS classes will be applied to\n * @param {string} add the CSS class(es) that will be added (multiple classes are separated via spaces)\n * @param {string} remove the CSS class(es) that will be removed (multiple classes are separated via spaces)\n * @param {object=} options an optional collection of options/styles that will be applied to the element.\n * The object can have the following properties:\n *\n * - **addClass** - `{string}` - space-separated CSS classes to add to element\n * - **from** - `{Object}` - CSS properties & values at the beginning of animation. Must have matching `to`\n * - **removeClass** - `{string}` - space-separated CSS classes to remove from element\n * - **to** - `{Object}` - CSS properties & values at end of animation. Must have matching `from`\n *\n * @return {Promise} the animation callback promise\n */\n setClass: function(element, add, remove, options) {\n options = prepareAnimateOptions(options);\n options.addClass = mergeClasses(options.addClass, add);\n options.removeClass = mergeClasses(options.removeClass, remove);\n return $$animateQueue.push(element, 'setClass', options);\n },\n\n /**\n * @ngdoc method\n * @name $animate#animate\n * @kind function\n *\n * @description Performs an inline animation on the element which applies the provided to and from CSS styles to the element.\n * If any detected CSS transition, keyframe or JavaScript matches the provided className value, then the animation will take\n * on the provided styles. For example, if a transition animation is set for the given className, then the provided `from` and\n * `to` styles will be applied alongside the given transition. If the CSS style provided in `from` does not have a corresponding\n * style in `to`, the style in `from` is applied immediately, and no animation is run.\n * If a JavaScript animation is detected then the provided styles will be given in as function parameters into the `animate`\n * method (or as part of the `options` parameter):\n *\n * ```js\n * ngModule.animation('.my-inline-animation', function() {\n * return {\n * animate : function(element, from, to, done, options) {\n * //animation\n * done();\n * }\n * }\n * });\n * ```\n *\n * @param {DOMElement} element the element which the CSS styles will be applied to\n * @param {object} from the from (starting) CSS styles that will be applied to the element and across the animation.\n * @param {object} to the to (destination) CSS styles that will be applied to the element and across the animation.\n * @param {string=} className an optional CSS class that will be applied to the element for the duration of the animation. If\n * this value is left as empty then a CSS class of `ng-inline-animate` will be applied to the element.\n * (Note that if no animation is detected then this value will not be applied to the element.)\n * @param {object=} options an optional collection of options/styles that will be applied to the element.\n * The object can have the following properties:\n *\n * - **addClass** - `{string}` - space-separated CSS classes to add to element\n * - **from** - `{Object}` - CSS properties & values at the beginning of animation. Must have matching `to`\n * - **removeClass** - `{string}` - space-separated CSS classes to remove from element\n * - **to** - `{Object}` - CSS properties & values at end of animation. Must have matching `from`\n *\n * @return {Promise} the animation callback promise\n */\n animate: function(element, from, to, className, options) {\n options = prepareAnimateOptions(options);\n options.from = options.from ? extend(options.from, from) : from;\n options.to = options.to ? extend(options.to, to) : to;\n\n className = className || 'ng-inline-animate';\n options.tempClasses = mergeClasses(options.tempClasses, className);\n return $$animateQueue.push(element, 'animate', options);\n }\n };\n }];\n}];\n\nvar $$AnimateAsyncRunFactoryProvider = /** @this */ function() {\n this.$get = ['$$rAF', function($$rAF) {\n var waitQueue = [];\n\n function waitForTick(fn) {\n waitQueue.push(fn);\n if (waitQueue.length > 1) return;\n $$rAF(function() {\n for (var i = 0; i < waitQueue.length; i++) {\n waitQueue[i]();\n }\n waitQueue = [];\n });\n }\n\n return function() {\n var passed = false;\n waitForTick(function() {\n passed = true;\n });\n return function(callback) {\n if (passed) {\n callback();\n } else {\n waitForTick(callback);\n }\n };\n };\n }];\n};\n\nvar $$AnimateRunnerFactoryProvider = /** @this */ function() {\n this.$get = ['$q', '$sniffer', '$$animateAsyncRun', '$$isDocumentHidden', '$timeout',\n function($q, $sniffer, $$animateAsyncRun, $$isDocumentHidden, $timeout) {\n\n var INITIAL_STATE = 0;\n var DONE_PENDING_STATE = 1;\n var DONE_COMPLETE_STATE = 2;\n\n AnimateRunner.chain = function(chain, callback) {\n var index = 0;\n\n next();\n function next() {\n if (index === chain.length) {\n callback(true);\n return;\n }\n\n chain[index](function(response) {\n if (response === false) {\n callback(false);\n return;\n }\n index++;\n next();\n });\n }\n };\n\n AnimateRunner.all = function(runners, callback) {\n var count = 0;\n var status = true;\n forEach(runners, function(runner) {\n runner.done(onProgress);\n });\n\n function onProgress(response) {\n status = status && response;\n if (++count === runners.length) {\n callback(status);\n }\n }\n };\n\n function AnimateRunner(host) {\n this.setHost(host);\n\n var rafTick = $$animateAsyncRun();\n var timeoutTick = function(fn) {\n $timeout(fn, 0, false);\n };\n\n this._doneCallbacks = [];\n this._tick = function(fn) {\n if ($$isDocumentHidden()) {\n timeoutTick(fn);\n } else {\n rafTick(fn);\n }\n };\n this._state = 0;\n }\n\n AnimateRunner.prototype = {\n setHost: function(host) {\n this.host = host || {};\n },\n\n done: function(fn) {\n if (this._state === DONE_COMPLETE_STATE) {\n fn();\n } else {\n this._doneCallbacks.push(fn);\n }\n },\n\n progress: noop,\n\n getPromise: function() {\n if (!this.promise) {\n var self = this;\n this.promise = $q(function(resolve, reject) {\n self.done(function(status) {\n if (status === false) {\n reject();\n } else {\n resolve();\n }\n });\n });\n }\n return this.promise;\n },\n\n then: function(resolveHandler, rejectHandler) {\n return this.getPromise().then(resolveHandler, rejectHandler);\n },\n\n 'catch': function(handler) {\n return this.getPromise()['catch'](handler);\n },\n\n 'finally': function(handler) {\n return this.getPromise()['finally'](handler);\n },\n\n pause: function() {\n if (this.host.pause) {\n this.host.pause();\n }\n },\n\n resume: function() {\n if (this.host.resume) {\n this.host.resume();\n }\n },\n\n end: function() {\n if (this.host.end) {\n this.host.end();\n }\n this._resolve(true);\n },\n\n cancel: function() {\n if (this.host.cancel) {\n this.host.cancel();\n }\n this._resolve(false);\n },\n\n complete: function(response) {\n var self = this;\n if (self._state === INITIAL_STATE) {\n self._state = DONE_PENDING_STATE;\n self._tick(function() {\n self._resolve(response);\n });\n }\n },\n\n _resolve: function(response) {\n if (this._state !== DONE_COMPLETE_STATE) {\n forEach(this._doneCallbacks, function(fn) {\n fn(response);\n });\n this._doneCallbacks.length = 0;\n this._state = DONE_COMPLETE_STATE;\n }\n }\n };\n\n return AnimateRunner;\n }];\n};\n\n/* exported $CoreAnimateCssProvider */\n\n/**\n * @ngdoc service\n * @name $animateCss\n * @kind object\n * @this\n *\n * @description\n * This is the core version of `$animateCss`. By default, only when the `ngAnimate` is included,\n * then the `$animateCss` service will actually perform animations.\n *\n * Click here {@link ngAnimate.$animateCss to read the documentation for $animateCss}.\n */\nvar $CoreAnimateCssProvider = function() {\n this.$get = ['$$rAF', '$q', '$$AnimateRunner', function($$rAF, $q, $$AnimateRunner) {\n\n return function(element, initialOptions) {\n // all of the animation functions should create\n // a copy of the options data, however, if a\n // parent service has already created a copy then\n // we should stick to using that\n var options = initialOptions || {};\n if (!options.$$prepared) {\n options = copy(options);\n }\n\n // there is no point in applying the styles since\n // there is no animation that goes on at all in\n // this version of $animateCss.\n if (options.cleanupStyles) {\n options.from = options.to = null;\n }\n\n if (options.from) {\n element.css(options.from);\n options.from = null;\n }\n\n var closed, runner = new $$AnimateRunner();\n return {\n start: run,\n end: run\n };\n\n function run() {\n $$rAF(function() {\n applyAnimationContents();\n if (!closed) {\n runner.complete();\n }\n closed = true;\n });\n return runner;\n }\n\n function applyAnimationContents() {\n if (options.addClass) {\n element.addClass(options.addClass);\n options.addClass = null;\n }\n if (options.removeClass) {\n element.removeClass(options.removeClass);\n options.removeClass = null;\n }\n if (options.to) {\n element.css(options.to);\n options.to = null;\n }\n }\n };\n }];\n};\n\n/* global stripHash: true */\n\n/**\n * ! This is a private undocumented service !\n *\n * @name $browser\n * @requires $log\n * @description\n * This object has two goals:\n *\n * - hide all the global state in the browser caused by the window object\n * - abstract away all the browser specific features and inconsistencies\n *\n * For tests we provide {@link ngMock.$browser mock implementation} of the `$browser`\n * service, which can be used for convenient testing of the application without the interaction with\n * the real browser apis.\n */\n/**\n * @param {object} window The global window object.\n * @param {object} document jQuery wrapped document.\n * @param {object} $log window.console or an object with the same interface.\n * @param {object} $sniffer $sniffer service\n */\nfunction Browser(window, document, $log, $sniffer) {\n var self = this,\n location = window.location,\n history = window.history,\n setTimeout = window.setTimeout,\n clearTimeout = window.clearTimeout,\n pendingDeferIds = {};\n\n self.isMock = false;\n\n var outstandingRequestCount = 0;\n var outstandingRequestCallbacks = [];\n\n // TODO(vojta): remove this temporary api\n self.$$completeOutstandingRequest = completeOutstandingRequest;\n self.$$incOutstandingRequestCount = function() { outstandingRequestCount++; };\n\n /**\n * Executes the `fn` function(supports currying) and decrements the `outstandingRequestCallbacks`\n * counter. If the counter reaches 0, all the `outstandingRequestCallbacks` are executed.\n */\n function completeOutstandingRequest(fn) {\n try {\n fn.apply(null, sliceArgs(arguments, 1));\n } finally {\n outstandingRequestCount--;\n if (outstandingRequestCount === 0) {\n while (outstandingRequestCallbacks.length) {\n try {\n outstandingRequestCallbacks.pop()();\n } catch (e) {\n $log.error(e);\n }\n }\n }\n }\n }\n\n function getHash(url) {\n var index = url.indexOf('#');\n return index === -1 ? '' : url.substr(index);\n }\n\n /**\n * @private\n * Note: this method is used only by scenario runner\n * TODO(vojta): prefix this method with $$ ?\n * @param {function()} callback Function that will be called when no outstanding request\n */\n self.notifyWhenNoOutstandingRequests = function(callback) {\n if (outstandingRequestCount === 0) {\n callback();\n } else {\n outstandingRequestCallbacks.push(callback);\n }\n };\n\n //////////////////////////////////////////////////////////////\n // URL API\n //////////////////////////////////////////////////////////////\n\n var cachedState, lastHistoryState,\n lastBrowserUrl = location.href,\n baseElement = document.find('base'),\n pendingLocation = null,\n getCurrentState = !$sniffer.history ? noop : function getCurrentState() {\n try {\n return history.state;\n } catch (e) {\n // MSIE can reportedly throw when there is no state (UNCONFIRMED).\n }\n };\n\n cacheState();\n lastHistoryState = cachedState;\n\n /**\n * @name $browser#url\n *\n * @description\n * GETTER:\n * Without any argument, this method just returns current value of location.href.\n *\n * SETTER:\n * With at least one argument, this method sets url to new value.\n * If html5 history api supported, pushState/replaceState is used, otherwise\n * location.href/location.replace is used.\n * Returns its own instance to allow chaining\n *\n * NOTE: this api is intended for use only by the $location service. Please use the\n * {@link ng.$location $location service} to change url.\n *\n * @param {string} url New url (when used as setter)\n * @param {boolean=} replace Should new url replace current history record?\n * @param {object=} state object to use with pushState/replaceState\n */\n self.url = function(url, replace, state) {\n // In modern browsers `history.state` is `null` by default; treating it separately\n // from `undefined` would cause `$browser.url('/foo')` to change `history.state`\n // to undefined via `pushState`. Instead, let's change `undefined` to `null` here.\n if (isUndefined(state)) {\n state = null;\n }\n\n // Android Browser BFCache causes location, history reference to become stale.\n if (location !== window.location) location = window.location;\n if (history !== window.history) history = window.history;\n\n // setter\n if (url) {\n var sameState = lastHistoryState === state;\n\n // Don't change anything if previous and current URLs and states match. This also prevents\n // IE<10 from getting into redirect loop when in LocationHashbangInHtml5Url mode.\n // See https://github.com/angular/angular.js/commit/ffb2701\n if (lastBrowserUrl === url && (!$sniffer.history || sameState)) {\n return self;\n }\n var sameBase = lastBrowserUrl && stripHash(lastBrowserUrl) === stripHash(url);\n lastBrowserUrl = url;\n lastHistoryState = state;\n // Don't use history API if only the hash changed\n // due to a bug in IE10/IE11 which leads\n // to not firing a `hashchange` nor `popstate` event\n // in some cases (see #9143).\n if ($sniffer.history && (!sameBase || !sameState)) {\n history[replace ? 'replaceState' : 'pushState'](state, '', url);\n cacheState();\n // Do the assignment again so that those two variables are referentially identical.\n lastHistoryState = cachedState;\n } else {\n if (!sameBase) {\n pendingLocation = url;\n }\n if (replace) {\n location.replace(url);\n } else if (!sameBase) {\n location.href = url;\n } else {\n location.hash = getHash(url);\n }\n if (location.href !== url) {\n pendingLocation = url;\n }\n }\n if (pendingLocation) {\n pendingLocation = url;\n }\n return self;\n // getter\n } else {\n // - pendingLocation is needed as browsers don't allow to read out\n // the new location.href if a reload happened or if there is a bug like in iOS 9 (see\n // https://openradar.appspot.com/22186109).\n // - the replacement is a workaround for https://bugzilla.mozilla.org/show_bug.cgi?id=407172\n return pendingLocation || location.href.replace(/%27/g,'\\'');\n }\n };\n\n /**\n * @name $browser#state\n *\n * @description\n * This method is a getter.\n *\n * Return history.state or null if history.state is undefined.\n *\n * @returns {object} state\n */\n self.state = function() {\n return cachedState;\n };\n\n var urlChangeListeners = [],\n urlChangeInit = false;\n\n function cacheStateAndFireUrlChange() {\n pendingLocation = null;\n cacheState();\n fireUrlChange();\n }\n\n // This variable should be used *only* inside the cacheState function.\n var lastCachedState = null;\n function cacheState() {\n // This should be the only place in $browser where `history.state` is read.\n cachedState = getCurrentState();\n cachedState = isUndefined(cachedState) ? null : cachedState;\n\n // Prevent callbacks fo fire twice if both hashchange & popstate were fired.\n if (equals(cachedState, lastCachedState)) {\n cachedState = lastCachedState;\n }\n lastCachedState = cachedState;\n }\n\n function fireUrlChange() {\n if (lastBrowserUrl === self.url() && lastHistoryState === cachedState) {\n return;\n }\n\n lastBrowserUrl = self.url();\n lastHistoryState = cachedState;\n forEach(urlChangeListeners, function(listener) {\n listener(self.url(), cachedState);\n });\n }\n\n /**\n * @name $browser#onUrlChange\n *\n * @description\n * Register callback function that will be called, when url changes.\n *\n * It's only called when the url is changed from outside of angular:\n * - user types different url into address bar\n * - user clicks on history (forward/back) button\n * - user clicks on a link\n *\n * It's not called when url is changed by $browser.url() method\n *\n * The listener gets called with new url as parameter.\n *\n * NOTE: this api is intended for use only by the $location service. Please use the\n * {@link ng.$location $location service} to monitor url changes in angular apps.\n *\n * @param {function(string)} listener Listener function to be called when url changes.\n * @return {function(string)} Returns the registered listener fn - handy if the fn is anonymous.\n */\n self.onUrlChange = function(callback) {\n // TODO(vojta): refactor to use node's syntax for events\n if (!urlChangeInit) {\n // We listen on both (hashchange/popstate) when available, as some browsers (e.g. Opera)\n // don't fire popstate when user change the address bar and don't fire hashchange when url\n // changed by push/replaceState\n\n // html5 history api - popstate event\n if ($sniffer.history) jqLite(window).on('popstate', cacheStateAndFireUrlChange);\n // hashchange event\n jqLite(window).on('hashchange', cacheStateAndFireUrlChange);\n\n urlChangeInit = true;\n }\n\n urlChangeListeners.push(callback);\n return callback;\n };\n\n /**\n * @private\n * Remove popstate and hashchange handler from window.\n *\n * NOTE: this api is intended for use only by $rootScope.\n */\n self.$$applicationDestroyed = function() {\n jqLite(window).off('hashchange popstate', cacheStateAndFireUrlChange);\n };\n\n /**\n * Checks whether the url has changed outside of Angular.\n * Needs to be exported to be able to check for changes that have been done in sync,\n * as hashchange/popstate events fire in async.\n */\n self.$$checkUrlChange = fireUrlChange;\n\n //////////////////////////////////////////////////////////////\n // Misc API\n //////////////////////////////////////////////////////////////\n\n /**\n * @name $browser#baseHref\n *\n * @description\n * Returns current \n * (always relative - without domain)\n *\n * @returns {string} The current base href\n */\n self.baseHref = function() {\n var href = baseElement.attr('href');\n return href ? href.replace(/^(https?:)?\\/\\/[^/]*/, '') : '';\n };\n\n /**\n * @name $browser#defer\n * @param {function()} fn A function, who's execution should be deferred.\n * @param {number=} [delay=0] of milliseconds to defer the function execution.\n * @returns {*} DeferId that can be used to cancel the task via `$browser.defer.cancel()`.\n *\n * @description\n * Executes a fn asynchronously via `setTimeout(fn, delay)`.\n *\n * Unlike when calling `setTimeout` directly, in test this function is mocked and instead of using\n * `setTimeout` in tests, the fns are queued in an array, which can be programmatically flushed\n * via `$browser.defer.flush()`.\n *\n */\n self.defer = function(fn, delay) {\n var timeoutId;\n outstandingRequestCount++;\n timeoutId = setTimeout(function() {\n delete pendingDeferIds[timeoutId];\n completeOutstandingRequest(fn);\n }, delay || 0);\n pendingDeferIds[timeoutId] = true;\n return timeoutId;\n };\n\n\n /**\n * @name $browser#defer.cancel\n *\n * @description\n * Cancels a deferred task identified with `deferId`.\n *\n * @param {*} deferId Token returned by the `$browser.defer` function.\n * @returns {boolean} Returns `true` if the task hasn't executed yet and was successfully\n * canceled.\n */\n self.defer.cancel = function(deferId) {\n if (pendingDeferIds[deferId]) {\n delete pendingDeferIds[deferId];\n clearTimeout(deferId);\n completeOutstandingRequest(noop);\n return true;\n }\n return false;\n };\n\n}\n\n/** @this */\nfunction $BrowserProvider() {\n this.$get = ['$window', '$log', '$sniffer', '$document',\n function($window, $log, $sniffer, $document) {\n return new Browser($window, $document, $log, $sniffer);\n }];\n}\n\n/**\n * @ngdoc service\n * @name $cacheFactory\n * @this\n *\n * @description\n * Factory that constructs {@link $cacheFactory.Cache Cache} objects and gives access to\n * them.\n *\n * ```js\n *\n * var cache = $cacheFactory('cacheId');\n * expect($cacheFactory.get('cacheId')).toBe(cache);\n * expect($cacheFactory.get('noSuchCacheId')).not.toBeDefined();\n *\n * cache.put(\"key\", \"value\");\n * cache.put(\"another key\", \"another value\");\n *\n * // We've specified no options on creation\n * expect(cache.info()).toEqual({id: 'cacheId', size: 2});\n *\n * ```\n *\n *\n * @param {string} cacheId Name or id of the newly created cache.\n * @param {object=} options Options object that specifies the cache behavior. Properties:\n *\n * - `{number=}` `capacity` — turns the cache into LRU cache.\n *\n * @returns {object} Newly created cache object with the following set of methods:\n *\n * - `{object}` `info()` — Returns id, size, and options of cache.\n * - `{{*}}` `put({string} key, {*} value)` — Puts a new key-value pair into the cache and returns\n * it.\n * - `{{*}}` `get({string} key)` — Returns cached value for `key` or undefined for cache miss.\n * - `{void}` `remove({string} key)` — Removes a key-value pair from the cache.\n * - `{void}` `removeAll()` — Removes all cached values.\n * - `{void}` `destroy()` — Removes references to this cache from $cacheFactory.\n *\n * @example\n \n \n
\n \n \n \n\n

Cached Values

\n
\n \n : \n \n
\n\n

Cache Info

\n
\n \n : \n \n
\n
\n
\n \n angular.module('cacheExampleApp', []).\n controller('CacheController', ['$scope', '$cacheFactory', function($scope, $cacheFactory) {\n $scope.keys = [];\n $scope.cache = $cacheFactory('cacheId');\n $scope.put = function(key, value) {\n if (angular.isUndefined($scope.cache.get(key))) {\n $scope.keys.push(key);\n }\n $scope.cache.put(key, angular.isUndefined(value) ? null : value);\n };\n }]);\n \n \n p {\n margin: 10px 0 3px;\n }\n \n
\n */\nfunction $CacheFactoryProvider() {\n\n this.$get = function() {\n var caches = {};\n\n function cacheFactory(cacheId, options) {\n if (cacheId in caches) {\n throw minErr('$cacheFactory')('iid', 'CacheId \\'{0}\\' is already taken!', cacheId);\n }\n\n var size = 0,\n stats = extend({}, options, {id: cacheId}),\n data = createMap(),\n capacity = (options && options.capacity) || Number.MAX_VALUE,\n lruHash = createMap(),\n freshEnd = null,\n staleEnd = null;\n\n /**\n * @ngdoc type\n * @name $cacheFactory.Cache\n *\n * @description\n * A cache object used to store and retrieve data, primarily used by\n * {@link $http $http} and the {@link ng.directive:script script} directive to cache\n * templates and other data.\n *\n * ```js\n * angular.module('superCache')\n * .factory('superCache', ['$cacheFactory', function($cacheFactory) {\n * return $cacheFactory('super-cache');\n * }]);\n * ```\n *\n * Example test:\n *\n * ```js\n * it('should behave like a cache', inject(function(superCache) {\n * superCache.put('key', 'value');\n * superCache.put('another key', 'another value');\n *\n * expect(superCache.info()).toEqual({\n * id: 'super-cache',\n * size: 2\n * });\n *\n * superCache.remove('another key');\n * expect(superCache.get('another key')).toBeUndefined();\n *\n * superCache.removeAll();\n * expect(superCache.info()).toEqual({\n * id: 'super-cache',\n * size: 0\n * });\n * }));\n * ```\n */\n return (caches[cacheId] = {\n\n /**\n * @ngdoc method\n * @name $cacheFactory.Cache#put\n * @kind function\n *\n * @description\n * Inserts a named entry into the {@link $cacheFactory.Cache Cache} object to be\n * retrieved later, and incrementing the size of the cache if the key was not already\n * present in the cache. If behaving like an LRU cache, it will also remove stale\n * entries from the set.\n *\n * It will not insert undefined values into the cache.\n *\n * @param {string} key the key under which the cached data is stored.\n * @param {*} value the value to store alongside the key. If it is undefined, the key\n * will not be stored.\n * @returns {*} the value stored.\n */\n put: function(key, value) {\n if (isUndefined(value)) return;\n if (capacity < Number.MAX_VALUE) {\n var lruEntry = lruHash[key] || (lruHash[key] = {key: key});\n\n refresh(lruEntry);\n }\n\n if (!(key in data)) size++;\n data[key] = value;\n\n if (size > capacity) {\n this.remove(staleEnd.key);\n }\n\n return value;\n },\n\n /**\n * @ngdoc method\n * @name $cacheFactory.Cache#get\n * @kind function\n *\n * @description\n * Retrieves named data stored in the {@link $cacheFactory.Cache Cache} object.\n *\n * @param {string} key the key of the data to be retrieved\n * @returns {*} the value stored.\n */\n get: function(key) {\n if (capacity < Number.MAX_VALUE) {\n var lruEntry = lruHash[key];\n\n if (!lruEntry) return;\n\n refresh(lruEntry);\n }\n\n return data[key];\n },\n\n\n /**\n * @ngdoc method\n * @name $cacheFactory.Cache#remove\n * @kind function\n *\n * @description\n * Removes an entry from the {@link $cacheFactory.Cache Cache} object.\n *\n * @param {string} key the key of the entry to be removed\n */\n remove: function(key) {\n if (capacity < Number.MAX_VALUE) {\n var lruEntry = lruHash[key];\n\n if (!lruEntry) return;\n\n if (lruEntry === freshEnd) freshEnd = lruEntry.p;\n if (lruEntry === staleEnd) staleEnd = lruEntry.n;\n link(lruEntry.n,lruEntry.p);\n\n delete lruHash[key];\n }\n\n if (!(key in data)) return;\n\n delete data[key];\n size--;\n },\n\n\n /**\n * @ngdoc method\n * @name $cacheFactory.Cache#removeAll\n * @kind function\n *\n * @description\n * Clears the cache object of any entries.\n */\n removeAll: function() {\n data = createMap();\n size = 0;\n lruHash = createMap();\n freshEnd = staleEnd = null;\n },\n\n\n /**\n * @ngdoc method\n * @name $cacheFactory.Cache#destroy\n * @kind function\n *\n * @description\n * Destroys the {@link $cacheFactory.Cache Cache} object entirely,\n * removing it from the {@link $cacheFactory $cacheFactory} set.\n */\n destroy: function() {\n data = null;\n stats = null;\n lruHash = null;\n delete caches[cacheId];\n },\n\n\n /**\n * @ngdoc method\n * @name $cacheFactory.Cache#info\n * @kind function\n *\n * @description\n * Retrieve information regarding a particular {@link $cacheFactory.Cache Cache}.\n *\n * @returns {object} an object with the following properties:\n *
    \n *
  • **id**: the id of the cache instance
  • \n *
  • **size**: the number of entries kept in the cache instance
  • \n *
  • **...**: any additional properties from the options object when creating the\n * cache.
  • \n *
\n */\n info: function() {\n return extend({}, stats, {size: size});\n }\n });\n\n\n /**\n * makes the `entry` the freshEnd of the LRU linked list\n */\n function refresh(entry) {\n if (entry !== freshEnd) {\n if (!staleEnd) {\n staleEnd = entry;\n } else if (staleEnd === entry) {\n staleEnd = entry.n;\n }\n\n link(entry.n, entry.p);\n link(entry, freshEnd);\n freshEnd = entry;\n freshEnd.n = null;\n }\n }\n\n\n /**\n * bidirectionally links two entries of the LRU linked list\n */\n function link(nextEntry, prevEntry) {\n if (nextEntry !== prevEntry) {\n if (nextEntry) nextEntry.p = prevEntry; //p stands for previous, 'prev' didn't minify\n if (prevEntry) prevEntry.n = nextEntry; //n stands for next, 'next' didn't minify\n }\n }\n }\n\n\n /**\n * @ngdoc method\n * @name $cacheFactory#info\n *\n * @description\n * Get information about all the caches that have been created\n *\n * @returns {Object} - key-value map of `cacheId` to the result of calling `cache#info`\n */\n cacheFactory.info = function() {\n var info = {};\n forEach(caches, function(cache, cacheId) {\n info[cacheId] = cache.info();\n });\n return info;\n };\n\n\n /**\n * @ngdoc method\n * @name $cacheFactory#get\n *\n * @description\n * Get access to a cache object by the `cacheId` used when it was created.\n *\n * @param {string} cacheId Name or id of a cache to access.\n * @returns {object} Cache object identified by the cacheId or undefined if no such cache.\n */\n cacheFactory.get = function(cacheId) {\n return caches[cacheId];\n };\n\n\n return cacheFactory;\n };\n}\n\n/**\n * @ngdoc service\n * @name $templateCache\n * @this\n *\n * @description\n * The first time a template is used, it is loaded in the template cache for quick retrieval. You\n * can load templates directly into the cache in a `script` tag, or by consuming the\n * `$templateCache` service directly.\n *\n * Adding via the `script` tag:\n *\n * ```html\n * \n * ```\n *\n * **Note:** the `script` tag containing the template does not need to be included in the `head` of\n * the document, but it must be a descendent of the {@link ng.$rootElement $rootElement} (IE,\n * element with ng-app attribute), otherwise the template will be ignored.\n *\n * Adding via the `$templateCache` service:\n *\n * ```js\n * var myApp = angular.module('myApp', []);\n * myApp.run(function($templateCache) {\n * $templateCache.put('templateId.html', 'This is the content of the template');\n * });\n * ```\n *\n * To retrieve the template later, simply use it in your component:\n * ```js\n * myApp.component('myComponent', {\n * templateUrl: 'templateId.html'\n * });\n * ```\n *\n * or get it via the `$templateCache` service:\n * ```js\n * $templateCache.get('templateId.html')\n * ```\n *\n * See {@link ng.$cacheFactory $cacheFactory}.\n *\n */\nfunction $TemplateCacheProvider() {\n this.$get = ['$cacheFactory', function($cacheFactory) {\n return $cacheFactory('templates');\n }];\n}\n\n/* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *\n * Any commits to this file should be reviewed with security in mind. *\n * Changes to this file can potentially create security vulnerabilities. *\n * An approval from 2 Core members with history of modifying *\n * this file is required. *\n * *\n * Does the change somehow allow for arbitrary javascript to be executed? *\n * Or allows for someone to change the prototype of built-in objects? *\n * Or gives undesired access to variables like document or window? *\n * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */\n\n/* ! VARIABLE/FUNCTION NAMING CONVENTIONS THAT APPLY TO THIS FILE!\n *\n * DOM-related variables:\n *\n * - \"node\" - DOM Node\n * - \"element\" - DOM Element or Node\n * - \"$node\" or \"$element\" - jqLite-wrapped node or element\n *\n *\n * Compiler related stuff:\n *\n * - \"linkFn\" - linking fn of a single directive\n * - \"nodeLinkFn\" - function that aggregates all linking fns for a particular node\n * - \"childLinkFn\" - function that aggregates all linking fns for child nodes of a particular node\n * - \"compositeLinkFn\" - function that aggregates all linking fns for a compilation root (nodeList)\n */\n\n\n/**\n * @ngdoc service\n * @name $compile\n * @kind function\n *\n * @description\n * Compiles an HTML string or DOM into a template and produces a template function, which\n * can then be used to link {@link ng.$rootScope.Scope `scope`} and the template together.\n *\n * The compilation is a process of walking the DOM tree and matching DOM elements to\n * {@link ng.$compileProvider#directive directives}.\n *\n *
\n * **Note:** This document is an in-depth reference of all directive options.\n * For a gentle introduction to directives with examples of common use cases,\n * see the {@link guide/directive directive guide}.\n *
\n *\n * ## Comprehensive Directive API\n *\n * There are many different options for a directive.\n *\n * The difference resides in the return value of the factory function.\n * You can either return a {@link $compile#directive-definition-object Directive Definition Object (see below)}\n * that defines the directive properties, or just the `postLink` function (all other properties will have\n * the default values).\n *\n *
\n * **Best Practice:** It's recommended to use the \"directive definition object\" form.\n *
\n *\n * Here's an example directive declared with a Directive Definition Object:\n *\n * ```js\n * var myModule = angular.module(...);\n *\n * myModule.directive('directiveName', function factory(injectables) {\n * var directiveDefinitionObject = {\n * {@link $compile#-priority- priority}: 0,\n * {@link $compile#-template- template}: '
', // or // function(tElement, tAttrs) { ... },\n * // or\n * // {@link $compile#-templateurl- templateUrl}: 'directive.html', // or // function(tElement, tAttrs) { ... },\n * {@link $compile#-transclude- transclude}: false,\n * {@link $compile#-restrict- restrict}: 'A',\n * {@link $compile#-templatenamespace- templateNamespace}: 'html',\n * {@link $compile#-scope- scope}: false,\n * {@link $compile#-controller- controller}: function($scope, $element, $attrs, $transclude, otherInjectables) { ... },\n * {@link $compile#-controlleras- controllerAs}: 'stringIdentifier',\n * {@link $compile#-bindtocontroller- bindToController}: false,\n * {@link $compile#-require- require}: 'siblingDirectiveName', // or // ['^parentDirectiveName', '?optionalDirectiveName', '?^optionalParent'],\n * {@link $compile#-multielement- multiElement}: false,\n * {@link $compile#-compile- compile}: function compile(tElement, tAttrs, transclude) {\n * return {\n * {@link $compile#pre-linking-function pre}: function preLink(scope, iElement, iAttrs, controller) { ... },\n * {@link $compile#post-linking-function post}: function postLink(scope, iElement, iAttrs, controller) { ... }\n * }\n * // or\n * // return function postLink( ... ) { ... }\n * },\n * // or\n * // {@link $compile#-link- link}: {\n * // {@link $compile#pre-linking-function pre}: function preLink(scope, iElement, iAttrs, controller) { ... },\n * // {@link $compile#post-linking-function post}: function postLink(scope, iElement, iAttrs, controller) { ... }\n * // }\n * // or\n * // {@link $compile#-link- link}: function postLink( ... ) { ... }\n * };\n * return directiveDefinitionObject;\n * });\n * ```\n *\n *
\n * **Note:** Any unspecified options will use the default value. You can see the default values below.\n *
\n *\n * Therefore the above can be simplified as:\n *\n * ```js\n * var myModule = angular.module(...);\n *\n * myModule.directive('directiveName', function factory(injectables) {\n * var directiveDefinitionObject = {\n * link: function postLink(scope, iElement, iAttrs) { ... }\n * };\n * return directiveDefinitionObject;\n * // or\n * // return function postLink(scope, iElement, iAttrs) { ... }\n * });\n * ```\n *\n * ### Life-cycle hooks\n * Directive controllers can provide the following methods that are called by Angular at points in the life-cycle of the\n * directive:\n * * `$onInit()` - Called on each controller after all the controllers on an element have been constructed and\n * had their bindings initialized (and before the pre & post linking functions for the directives on\n * this element). This is a good place to put initialization code for your controller.\n * * `$onChanges(changesObj)` - Called whenever one-way (`<`) or interpolation (`@`) bindings are updated. The\n * `changesObj` is a hash whose keys are the names of the bound properties that have changed, and the values are an\n * object of the form `{ currentValue, previousValue, isFirstChange() }`. Use this hook to trigger updates within a\n * component such as cloning the bound value to prevent accidental mutation of the outer value.\n * * `$doCheck()` - Called on each turn of the digest cycle. Provides an opportunity to detect and act on\n * changes. Any actions that you wish to take in response to the changes that you detect must be\n * invoked from this hook; implementing this has no effect on when `$onChanges` is called. For example, this hook\n * could be useful if you wish to perform a deep equality check, or to check a Date object, changes to which would not\n * be detected by Angular's change detector and thus not trigger `$onChanges`. This hook is invoked with no arguments;\n * if detecting changes, you must store the previous value(s) for comparison to the current values.\n * * `$onDestroy()` - Called on a controller when its containing scope is destroyed. Use this hook for releasing\n * external resources, watches and event handlers. Note that components have their `$onDestroy()` hooks called in\n * the same order as the `$scope.$broadcast` events are triggered, which is top down. This means that parent\n * components will have their `$onDestroy()` hook called before child components.\n * * `$postLink()` - Called after this controller's element and its children have been linked. Similar to the post-link\n * function this hook can be used to set up DOM event handlers and do direct DOM manipulation.\n * Note that child elements that contain `templateUrl` directives will not have been compiled and linked since\n * they are waiting for their template to load asynchronously and their own compilation and linking has been\n * suspended until that occurs.\n *\n * #### Comparison with Angular 2 life-cycle hooks\n * Angular 2 also uses life-cycle hooks for its components. While the Angular 1 life-cycle hooks are similar there are\n * some differences that you should be aware of, especially when it comes to moving your code from Angular 1 to Angular 2:\n *\n * * Angular 1 hooks are prefixed with `$`, such as `$onInit`. Angular 2 hooks are prefixed with `ng`, such as `ngOnInit`.\n * * Angular 1 hooks can be defined on the controller prototype or added to the controller inside its constructor.\n * In Angular 2 you can only define hooks on the prototype of the Component class.\n * * Due to the differences in change-detection, you may get many more calls to `$doCheck` in Angular 1 than you would to\n * `ngDoCheck` in Angular 2\n * * Changes to the model inside `$doCheck` will trigger new turns of the digest loop, which will cause the changes to be\n * propagated throughout the application.\n * Angular 2 does not allow the `ngDoCheck` hook to trigger a change outside of the component. It will either throw an\n * error or do nothing depending upon the state of `enableProdMode()`.\n *\n * #### Life-cycle hook examples\n *\n * This example shows how you can check for mutations to a Date object even though the identity of the object\n * has not changed.\n *\n * \n * \n * angular.module('do-check-module', [])\n * .component('app', {\n * template:\n * 'Month: ' +\n * 'Date: {{ $ctrl.date }}' +\n * '',\n * controller: function() {\n * this.date = new Date();\n * this.month = this.date.getMonth();\n * this.updateDate = function() {\n * this.date.setMonth(this.month);\n * };\n * }\n * })\n * .component('test', {\n * bindings: { date: '<' },\n * template:\n * '
{{ $ctrl.log | json }}
',\n * controller: function() {\n * var previousValue;\n * this.log = [];\n * this.$doCheck = function() {\n * var currentValue = this.date && this.date.valueOf();\n * if (previousValue !== currentValue) {\n * this.log.push('doCheck: date mutated: ' + this.date);\n * previousValue = currentValue;\n * }\n * };\n * }\n * });\n *
\n * \n * \n * \n *
\n *\n * This example show how you might use `$doCheck` to trigger changes in your component's inputs even if the\n * actual identity of the component doesn't change. (Be aware that cloning and deep equality checks on large\n * arrays or objects can have a negative impact on your application performance)\n *\n * \n * \n *
\n * \n * \n *
{{ items }}
\n * \n *
\n *
\n * \n * angular.module('do-check-module', [])\n * .component('test', {\n * bindings: { items: '<' },\n * template:\n * '
{{ $ctrl.log | json }}
',\n * controller: function() {\n * this.log = [];\n *\n * this.$doCheck = function() {\n * if (this.items_ref !== this.items) {\n * this.log.push('doCheck: items changed');\n * this.items_ref = this.items;\n * }\n * if (!angular.equals(this.items_clone, this.items)) {\n * this.log.push('doCheck: items mutated');\n * this.items_clone = angular.copy(this.items);\n * }\n * };\n * }\n * });\n *
\n *
\n *\n *\n * ### Directive Definition Object\n *\n * The directive definition object provides instructions to the {@link ng.$compile\n * compiler}. The attributes are:\n *\n * #### `multiElement`\n * When this property is set to true (default is `false`), the HTML compiler will collect DOM nodes between\n * nodes with the attributes `directive-name-start` and `directive-name-end`, and group them\n * together as the directive elements. It is recommended that this feature be used on directives\n * which are not strictly behavioral (such as {@link ngClick}), and which\n * do not manipulate or replace child nodes (such as {@link ngInclude}).\n *\n * #### `priority`\n * When there are multiple directives defined on a single DOM element, sometimes it\n * is necessary to specify the order in which the directives are applied. The `priority` is used\n * to sort the directives before their `compile` functions get called. Priority is defined as a\n * number. Directives with greater numerical `priority` are compiled first. Pre-link functions\n * are also run in priority order, but post-link functions are run in reverse order. The order\n * of directives with the same priority is undefined. The default priority is `0`.\n *\n * #### `terminal`\n * If set to true then the current `priority` will be the last set of directives\n * which will execute (any directives at the current priority will still execute\n * as the order of execution on same `priority` is undefined). Note that expressions\n * and other directives used in the directive's template will also be excluded from execution.\n *\n * #### `scope`\n * The scope property can be `false`, `true`, or an object:\n *\n * * **`false` (default):** No scope will be created for the directive. The directive will use its\n * parent's scope.\n *\n * * **`true`:** A new child scope that prototypically inherits from its parent will be created for\n * the directive's element. If multiple directives on the same element request a new scope,\n * only one new scope is created.\n *\n * * **`{...}` (an object hash):** A new \"isolate\" scope is created for the directive's element. The\n * 'isolate' scope differs from normal scope in that it does not prototypically inherit from its parent\n * scope. This is useful when creating reusable components, which should not accidentally read or modify\n * data in the parent scope.\n *\n * The 'isolate' scope object hash defines a set of local scope properties derived from attributes on the\n * directive's element. These local properties are useful for aliasing values for templates. The keys in\n * the object hash map to the name of the property on the isolate scope; the values define how the property\n * is bound to the parent scope, via matching attributes on the directive's element:\n *\n * * `@` or `@attr` - bind a local scope property to the value of DOM attribute. The result is\n * always a string since DOM attributes are strings. If no `attr` name is specified then the\n * attribute name is assumed to be the same as the local name. Given `` and the isolate scope definition `scope: { localName:'@myAttr' }`,\n * the directive's scope property `localName` will reflect the interpolated value of `hello\n * {{name}}`. As the `name` attribute changes so will the `localName` property on the directive's\n * scope. The `name` is read from the parent scope (not the directive's scope).\n *\n * * `=` or `=attr` - set up a bidirectional binding between a local scope property and an expression\n * passed via the attribute `attr`. The expression is evaluated in the context of the parent scope.\n * If no `attr` name is specified then the attribute name is assumed to be the same as the local\n * name. Given `` and the isolate scope definition `scope: {\n * localModel: '=myAttr' }`, the property `localModel` on the directive's scope will reflect the\n * value of `parentModel` on the parent scope. Changes to `parentModel` will be reflected in\n * `localModel` and vice versa. Optional attributes should be marked as such with a question mark:\n * `=?` or `=?attr`. If the binding expression is non-assignable, or if the attribute isn't\n * optional and doesn't exist, an exception ({@link error/$compile/nonassign `$compile:nonassign`})\n * will be thrown upon discovering changes to the local value, since it will be impossible to sync\n * them back to the parent scope. By default, the {@link ng.$rootScope.Scope#$watch `$watch`}\n * method is used for tracking changes, and the equality check is based on object identity.\n * However, if an object literal or an array literal is passed as the binding expression, the\n * equality check is done by value (using the {@link angular.equals} function). It's also possible\n * to watch the evaluated value shallowly with {@link ng.$rootScope.Scope#$watchCollection\n * `$watchCollection`}: use `=*` or `=*attr` (`=*?` or `=*?attr` if the attribute is optional).\n *\n * * `<` or `` and directive definition of\n * `scope: { localModel:'` and the isolate scope definition `scope: {\n * localFn:'&myAttr' }`, the isolate scope property `localFn` will point to a function wrapper for\n * the `count = count + value` expression. Often it's desirable to pass data from the isolated scope\n * via an expression to the parent scope. This can be done by passing a map of local variable names\n * and values into the expression wrapper fn. For example, if the expression is `increment(amount)`\n * then we can specify the amount value by calling the `localFn` as `localFn({amount: 22})`.\n *\n * In general it's possible to apply more than one directive to one element, but there might be limitations\n * depending on the type of scope required by the directives. The following points will help explain these limitations.\n * For simplicity only two directives are taken into account, but it is also applicable for several directives:\n *\n * * **no scope** + **no scope** => Two directives which don't require their own scope will use their parent's scope\n * * **child scope** + **no scope** => Both directives will share one single child scope\n * * **child scope** + **child scope** => Both directives will share one single child scope\n * * **isolated scope** + **no scope** => The isolated directive will use it's own created isolated scope. The other directive will use\n * its parent's scope\n * * **isolated scope** + **child scope** => **Won't work!** Only one scope can be related to one element. Therefore these directives cannot\n * be applied to the same element.\n * * **isolated scope** + **isolated scope** => **Won't work!** Only one scope can be related to one element. Therefore these directives\n * cannot be applied to the same element.\n *\n *\n * #### `bindToController`\n * This property is used to bind scope properties directly to the controller. It can be either\n * `true` or an object hash with the same format as the `scope` property.\n *\n * When an isolate scope is used for a directive (see above), `bindToController: true` will\n * allow a component to have its properties bound to the controller, rather than to scope.\n *\n * After the controller is instantiated, the initial values of the isolate scope bindings will be bound to the controller\n * properties. You can access these bindings once they have been initialized by providing a controller method called\n * `$onInit`, which is called after all the controllers on an element have been constructed and had their bindings\n * initialized.\n *\n *
\n * **Deprecation warning:** although bindings for non-ES6 class controllers are currently\n * bound to `this` before the controller constructor is called, this use is now deprecated. Please place initialization\n * code that relies upon bindings inside a `$onInit` method on the controller, instead.\n *
\n *\n * It is also possible to set `bindToController` to an object hash with the same format as the `scope` property.\n * This will set up the scope bindings to the controller directly. Note that `scope` can still be used\n * to define which kind of scope is created. By default, no scope is created. Use `scope: {}` to create an isolate\n * scope (useful for component directives).\n *\n * If both `bindToController` and `scope` are defined and have object hashes, `bindToController` overrides `scope`.\n *\n *\n * #### `controller`\n * Controller constructor function. The controller is instantiated before the\n * pre-linking phase and can be accessed by other directives (see\n * `require` attribute). This allows the directives to communicate with each other and augment\n * each other's behavior. The controller is injectable (and supports bracket notation) with the following locals:\n *\n * * `$scope` - Current scope associated with the element\n * * `$element` - Current element\n * * `$attrs` - Current attributes object for the element\n * * `$transclude` - A transclude linking function pre-bound to the correct transclusion scope:\n * `function([scope], cloneLinkingFn, futureParentElement, slotName)`:\n * * `scope`: (optional) override the scope.\n * * `cloneLinkingFn`: (optional) argument to create clones of the original transcluded content.\n * * `futureParentElement` (optional):\n * * defines the parent to which the `cloneLinkingFn` will add the cloned elements.\n * * default: `$element.parent()` resp. `$element` for `transclude:'element'` resp. `transclude:true`.\n * * only needed for transcludes that are allowed to contain non html elements (e.g. SVG elements)\n * and when the `cloneLinkingFn` is passed,\n * as those elements need to created and cloned in a special way when they are defined outside their\n * usual containers (e.g. like ``).\n * * See also the `directive.templateNamespace` property.\n * * `slotName`: (optional) the name of the slot to transclude. If falsy (e.g. `null`, `undefined` or `''`)\n * then the default transclusion is provided.\n * The `$transclude` function also has a method on it, `$transclude.isSlotFilled(slotName)`, which returns\n * `true` if the specified slot contains content (i.e. one or more DOM nodes).\n *\n * #### `require`\n * Require another directive and inject its controller as the fourth argument to the linking function. The\n * `require` property can be a string, an array or an object:\n * * a **string** containing the name of the directive to pass to the linking function\n * * an **array** containing the names of directives to pass to the linking function. The argument passed to the\n * linking function will be an array of controllers in the same order as the names in the `require` property\n * * an **object** whose property values are the names of the directives to pass to the linking function. The argument\n * passed to the linking function will also be an object with matching keys, whose values will hold the corresponding\n * controllers.\n *\n * If the `require` property is an object and `bindToController` is truthy, then the required controllers are\n * bound to the controller using the keys of the `require` property. This binding occurs after all the controllers\n * have been constructed but before `$onInit` is called.\n * If the name of the required controller is the same as the local name (the key), the name can be\n * omitted. For example, `{parentDir: '^^'}` is equivalent to `{parentDir: '^^parentDir'}`.\n * See the {@link $compileProvider#component} helper for an example of how this can be used.\n * If no such required directive(s) can be found, or if the directive does not have a controller, then an error is\n * raised (unless no link function is specified and the required controllers are not being bound to the directive\n * controller, in which case error checking is skipped). The name can be prefixed with:\n *\n * * (no prefix) - Locate the required controller on the current element. Throw an error if not found.\n * * `?` - Attempt to locate the required controller or pass `null` to the `link` fn if not found.\n * * `^` - Locate the required controller by searching the element and its parents. Throw an error if not found.\n * * `^^` - Locate the required controller by searching the element's parents. Throw an error if not found.\n * * `?^` - Attempt to locate the required controller by searching the element and its parents or pass\n * `null` to the `link` fn if not found.\n * * `?^^` - Attempt to locate the required controller by searching the element's parents, or pass\n * `null` to the `link` fn if not found.\n *\n *\n * #### `controllerAs`\n * Identifier name for a reference to the controller in the directive's scope.\n * This allows the controller to be referenced from the directive template. This is especially\n * useful when a directive is used as component, i.e. with an `isolate` scope. It's also possible\n * to use it in a directive without an `isolate` / `new` scope, but you need to be aware that the\n * `controllerAs` reference might overwrite a property that already exists on the parent scope.\n *\n *\n * #### `restrict`\n * String of subset of `EACM` which restricts the directive to a specific directive\n * declaration style. If omitted, the defaults (elements and attributes) are used.\n *\n * * `E` - Element name (default): ``\n * * `A` - Attribute (default): `
`\n * * `C` - Class: `
`\n * * `M` - Comment: ``\n *\n *\n * #### `templateNamespace`\n * String representing the document type used by the markup in the template.\n * AngularJS needs this information as those elements need to be created and cloned\n * in a special way when they are defined outside their usual containers like `` and ``.\n *\n * * `html` - All root nodes in the template are HTML. Root nodes may also be\n * top-level elements such as `` or ``.\n * * `svg` - The root nodes in the template are SVG elements (excluding ``).\n * * `math` - The root nodes in the template are MathML elements (excluding ``).\n *\n * If no `templateNamespace` is specified, then the namespace is considered to be `html`.\n *\n * #### `template`\n * HTML markup that may:\n * * Replace the contents of the directive's element (default).\n * * Replace the directive's element itself (if `replace` is true - DEPRECATED).\n * * Wrap the contents of the directive's element (if `transclude` is true).\n *\n * Value may be:\n *\n * * A string. For example `
{{delete_str}}
`.\n * * A function which takes two arguments `tElement` and `tAttrs` (described in the `compile`\n * function api below) and returns a string value.\n *\n *\n * #### `templateUrl`\n * This is similar to `template` but the template is loaded from the specified URL, asynchronously.\n *\n * Because template loading is asynchronous the compiler will suspend compilation of directives on that element\n * for later when the template has been resolved. In the meantime it will continue to compile and link\n * sibling and parent elements as though this element had not contained any directives.\n *\n * The compiler does not suspend the entire compilation to wait for templates to be loaded because this\n * would result in the whole app \"stalling\" until all templates are loaded asynchronously - even in the\n * case when only one deeply nested directive has `templateUrl`.\n *\n * Template loading is asynchronous even if the template has been preloaded into the {@link $templateCache}\n *\n * You can specify `templateUrl` as a string representing the URL or as a function which takes two\n * arguments `tElement` and `tAttrs` (described in the `compile` function api below) and returns\n * a string value representing the url. In either case, the template URL is passed through {@link\n * $sce#getTrustedResourceUrl $sce.getTrustedResourceUrl}.\n *\n *\n * #### `replace` ([*DEPRECATED*!], will be removed in next major release - i.e. v2.0)\n * specify what the template should replace. Defaults to `false`.\n *\n * * `true` - the template will replace the directive's element.\n * * `false` - the template will replace the contents of the directive's element.\n *\n * The replacement process migrates all of the attributes / classes from the old element to the new\n * one. See the {@link guide/directive#template-expanding-directive\n * Directives Guide} for an example.\n *\n * There are very few scenarios where element replacement is required for the application function,\n * the main one being reusable custom components that are used within SVG contexts\n * (because SVG doesn't work with custom elements in the DOM tree).\n *\n * #### `transclude`\n * Extract the contents of the element where the directive appears and make it available to the directive.\n * The contents are compiled and provided to the directive as a **transclusion function**. See the\n * {@link $compile#transclusion Transclusion} section below.\n *\n *\n * #### `compile`\n *\n * ```js\n * function compile(tElement, tAttrs, transclude) { ... }\n * ```\n *\n * The compile function deals with transforming the template DOM. Since most directives do not do\n * template transformation, it is not used often. The compile function takes the following arguments:\n *\n * * `tElement` - template element - The element where the directive has been declared. It is\n * safe to do template transformation on the element and child elements only.\n *\n * * `tAttrs` - template attributes - Normalized list of attributes declared on this element shared\n * between all directive compile functions.\n *\n * * `transclude` - [*DEPRECATED*!] A transclude linking function: `function(scope, cloneLinkingFn)`\n *\n *
\n * **Note:** The template instance and the link instance may be different objects if the template has\n * been cloned. For this reason it is **not** safe to do anything other than DOM transformations that\n * apply to all cloned DOM nodes within the compile function. Specifically, DOM listener registration\n * should be done in a linking function rather than in a compile function.\n *
\n\n *
\n * **Note:** The compile function cannot handle directives that recursively use themselves in their\n * own templates or compile functions. Compiling these directives results in an infinite loop and\n * stack overflow errors.\n *\n * This can be avoided by manually using $compile in the postLink function to imperatively compile\n * a directive's template instead of relying on automatic template compilation via `template` or\n * `templateUrl` declaration or manual compilation inside the compile function.\n *
\n *\n *
\n * **Note:** The `transclude` function that is passed to the compile function is deprecated, as it\n * e.g. does not know about the right outer scope. Please use the transclude function that is passed\n * to the link function instead.\n *
\n\n * A compile function can have a return value which can be either a function or an object.\n *\n * * returning a (post-link) function - is equivalent to registering the linking function via the\n * `link` property of the config object when the compile function is empty.\n *\n * * returning an object with function(s) registered via `pre` and `post` properties - allows you to\n * control when a linking function should be called during the linking phase. See info about\n * pre-linking and post-linking functions below.\n *\n *\n * #### `link`\n * This property is used only if the `compile` property is not defined.\n *\n * ```js\n * function link(scope, iElement, iAttrs, controller, transcludeFn) { ... }\n * ```\n *\n * The link function is responsible for registering DOM listeners as well as updating the DOM. It is\n * executed after the template has been cloned. This is where most of the directive logic will be\n * put.\n *\n * * `scope` - {@link ng.$rootScope.Scope Scope} - The scope to be used by the\n * directive for registering {@link ng.$rootScope.Scope#$watch watches}.\n *\n * * `iElement` - instance element - The element where the directive is to be used. It is safe to\n * manipulate the children of the element only in `postLink` function since the children have\n * already been linked.\n *\n * * `iAttrs` - instance attributes - Normalized list of attributes declared on this element shared\n * between all directive linking functions.\n *\n * * `controller` - the directive's required controller instance(s) - Instances are shared\n * among all directives, which allows the directives to use the controllers as a communication\n * channel. The exact value depends on the directive's `require` property:\n * * no controller(s) required: the directive's own controller, or `undefined` if it doesn't have one\n * * `string`: the controller instance\n * * `array`: array of controller instances\n *\n * If a required controller cannot be found, and it is optional, the instance is `null`,\n * otherwise the {@link error:$compile:ctreq Missing Required Controller} error is thrown.\n *\n * Note that you can also require the directive's own controller - it will be made available like\n * any other controller.\n *\n * * `transcludeFn` - A transclude linking function pre-bound to the correct transclusion scope.\n * This is the same as the `$transclude` parameter of directive controllers,\n * see {@link ng.$compile#-controller- the controller section for details}.\n * `function([scope], cloneLinkingFn, futureParentElement)`.\n *\n * #### Pre-linking function\n *\n * Executed before the child elements are linked. Not safe to do DOM transformation since the\n * compiler linking function will fail to locate the correct elements for linking.\n *\n * #### Post-linking function\n *\n * Executed after the child elements are linked.\n *\n * Note that child elements that contain `templateUrl` directives will not have been compiled\n * and linked since they are waiting for their template to load asynchronously and their own\n * compilation and linking has been suspended until that occurs.\n *\n * It is safe to do DOM transformation in the post-linking function on elements that are not waiting\n * for their async templates to be resolved.\n *\n *\n * ### Transclusion\n *\n * Transclusion is the process of extracting a collection of DOM elements from one part of the DOM and\n * copying them to another part of the DOM, while maintaining their connection to the original AngularJS\n * scope from where they were taken.\n *\n * Transclusion is used (often with {@link ngTransclude}) to insert the\n * original contents of a directive's element into a specified place in the template of the directive.\n * The benefit of transclusion, over simply moving the DOM elements manually, is that the transcluded\n * content has access to the properties on the scope from which it was taken, even if the directive\n * has isolated scope.\n * See the {@link guide/directive#creating-a-directive-that-wraps-other-elements Directives Guide}.\n *\n * This makes it possible for the widget to have private state for its template, while the transcluded\n * content has access to its originating scope.\n *\n *
\n * **Note:** When testing an element transclude directive you must not place the directive at the root of the\n * DOM fragment that is being compiled. See {@link guide/unit-testing#testing-transclusion-directives\n * Testing Transclusion Directives}.\n *
\n *\n * There are three kinds of transclusion depending upon whether you want to transclude just the contents of the\n * directive's element, the entire element or multiple parts of the element contents:\n *\n * * `true` - transclude the content (i.e. the child nodes) of the directive's element.\n * * `'element'` - transclude the whole of the directive's element including any directives on this\n * element that defined at a lower priority than this directive. When used, the `template`\n * property is ignored.\n * * **`{...}` (an object hash):** - map elements of the content onto transclusion \"slots\" in the template.\n *\n * **Mult-slot transclusion** is declared by providing an object for the `transclude` property.\n *\n * This object is a map where the keys are the name of the slot to fill and the value is an element selector\n * used to match the HTML to the slot. The element selector should be in normalized form (e.g. `myElement`)\n * and will match the standard element variants (e.g. `my-element`, `my:element`, `data-my-element`, etc).\n *\n * For further information check out the guide on {@link guide/directive#matching-directives Matching Directives}\n *\n * If the element selector is prefixed with a `?` then that slot is optional.\n *\n * For example, the transclude object `{ slotA: '?myCustomElement' }` maps `` elements to\n * the `slotA` slot, which can be accessed via the `$transclude` function or via the {@link ngTransclude} directive.\n *\n * Slots that are not marked as optional (`?`) will trigger a compile time error if there are no matching elements\n * in the transclude content. If you wish to know if an optional slot was filled with content, then you can call\n * `$transclude.isSlotFilled(slotName)` on the transclude function passed to the directive's link function and\n * injectable into the directive's controller.\n *\n *\n * #### Transclusion Functions\n *\n * When a directive requests transclusion, the compiler extracts its contents and provides a **transclusion\n * function** to the directive's `link` function and `controller`. This transclusion function is a special\n * **linking function** that will return the compiled contents linked to a new transclusion scope.\n *\n *
\n * If you are just using {@link ngTransclude} then you don't need to worry about this function, since\n * ngTransclude will deal with it for us.\n *
\n *\n * If you want to manually control the insertion and removal of the transcluded content in your directive\n * then you must use this transclude function. When you call a transclude function it returns a a jqLite/JQuery\n * object that contains the compiled DOM, which is linked to the correct transclusion scope.\n *\n * When you call a transclusion function you can pass in a **clone attach function**. This function accepts\n * two parameters, `function(clone, scope) { ... }`, where the `clone` is a fresh compiled copy of your transcluded\n * content and the `scope` is the newly created transclusion scope, which the clone will be linked to.\n *\n *
\n * **Best Practice**: Always provide a `cloneFn` (clone attach function) when you call a transclude function\n * since you then get a fresh clone of the original DOM and also have access to the new transclusion scope.\n *
\n *\n * It is normal practice to attach your transcluded content (`clone`) to the DOM inside your **clone\n * attach function**:\n *\n * ```js\n * var transcludedContent, transclusionScope;\n *\n * $transclude(function(clone, scope) {\n * element.append(clone);\n * transcludedContent = clone;\n * transclusionScope = scope;\n * });\n * ```\n *\n * Later, if you want to remove the transcluded content from your DOM then you should also destroy the\n * associated transclusion scope:\n *\n * ```js\n * transcludedContent.remove();\n * transclusionScope.$destroy();\n * ```\n *\n *
\n * **Best Practice**: if you intend to add and remove transcluded content manually in your directive\n * (by calling the transclude function to get the DOM and calling `element.remove()` to remove it),\n * then you are also responsible for calling `$destroy` on the transclusion scope.\n *
\n *\n * The built-in DOM manipulation directives, such as {@link ngIf}, {@link ngSwitch} and {@link ngRepeat}\n * automatically destroy their transcluded clones as necessary so you do not need to worry about this if\n * you are simply using {@link ngTransclude} to inject the transclusion into your directive.\n *\n *\n * #### Transclusion Scopes\n *\n * When you call a transclude function it returns a DOM fragment that is pre-bound to a **transclusion\n * scope**. This scope is special, in that it is a child of the directive's scope (and so gets destroyed\n * when the directive's scope gets destroyed) but it inherits the properties of the scope from which it\n * was taken.\n *\n * For example consider a directive that uses transclusion and isolated scope. The DOM hierarchy might look\n * like this:\n *\n * ```html\n *
\n *
\n *
\n *
\n *
\n *
\n * ```\n *\n * The `$parent` scope hierarchy will look like this:\n *\n ```\n - $rootScope\n - isolate\n - transclusion\n ```\n *\n * but the scopes will inherit prototypically from different scopes to their `$parent`.\n *\n ```\n - $rootScope\n - transclusion\n - isolate\n ```\n *\n *\n * ### Attributes\n *\n * The {@link ng.$compile.directive.Attributes Attributes} object - passed as a parameter in the\n * `link()` or `compile()` functions. It has a variety of uses.\n *\n * * *Accessing normalized attribute names:* Directives like 'ngBind' can be expressed in many ways:\n * 'ng:bind', `data-ng-bind`, or 'x-ng-bind'. The attributes object allows for normalized access\n * to the attributes.\n *\n * * *Directive inter-communication:* All directives share the same instance of the attributes\n * object which allows the directives to use the attributes object as inter directive\n * communication.\n *\n * * *Supports interpolation:* Interpolation attributes are assigned to the attribute object\n * allowing other directives to read the interpolated value.\n *\n * * *Observing interpolated attributes:* Use `$observe` to observe the value changes of attributes\n * that contain interpolation (e.g. `src=\"{{bar}}\"`). Not only is this very efficient but it's also\n * the only way to easily get the actual value because during the linking phase the interpolation\n * hasn't been evaluated yet and so the value is at this time set to `undefined`.\n *\n * ```js\n * function linkingFn(scope, elm, attrs, ctrl) {\n * // get the attribute value\n * console.log(attrs.ngModel);\n *\n * // change the attribute\n * attrs.$set('ngModel', 'new value');\n *\n * // observe changes to interpolated attribute\n * attrs.$observe('ngModel', function(value) {\n * console.log('ngModel has changed value to ' + value);\n * });\n * }\n * ```\n *\n * ## Example\n *\n *
\n * **Note**: Typically directives are registered with `module.directive`. The example below is\n * to illustrate how `$compile` works.\n *
\n *\n \n \n \n
\n
\n
\n
\n
\n
\n \n it('should auto compile', function() {\n var textarea = $('textarea');\n var output = $('div[compile]');\n // The initial state reads 'Hello Angular'.\n expect(output.getText()).toBe('Hello Angular');\n textarea.clear();\n textarea.sendKeys('{{name}}!');\n expect(output.getText()).toBe('Angular!');\n });\n \n
\n\n *\n *\n * @param {string|DOMElement} element Element or HTML string to compile into a template function.\n * @param {function(angular.Scope, cloneAttachFn=)} transclude function available to directives - DEPRECATED.\n *\n *
\n * **Note:** Passing a `transclude` function to the $compile function is deprecated, as it\n * e.g. will not use the right outer scope. Please pass the transclude function as a\n * `parentBoundTranscludeFn` to the link function instead.\n *
\n *\n * @param {number} maxPriority only apply directives lower than given priority (Only effects the\n * root element(s), not their children)\n * @returns {function(scope, cloneAttachFn=, options=)} a link function which is used to bind template\n * (a DOM element/tree) to a scope. Where:\n *\n * * `scope` - A {@link ng.$rootScope.Scope Scope} to bind to.\n * * `cloneAttachFn` - If `cloneAttachFn` is provided, then the link function will clone the\n * `template` and call the `cloneAttachFn` function allowing the caller to attach the\n * cloned elements to the DOM document at the appropriate place. The `cloneAttachFn` is\n * called as:
`cloneAttachFn(clonedElement, scope)` where:\n *\n * * `clonedElement` - is a clone of the original `element` passed into the compiler.\n * * `scope` - is the current scope with which the linking function is working with.\n *\n * * `options` - An optional object hash with linking options. If `options` is provided, then the following\n * keys may be used to control linking behavior:\n *\n * * `parentBoundTranscludeFn` - the transclude function made available to\n * directives; if given, it will be passed through to the link functions of\n * directives found in `element` during compilation.\n * * `transcludeControllers` - an object hash with keys that map controller names\n * to a hash with the key `instance`, which maps to the controller instance;\n * if given, it will make the controllers available to directives on the compileNode:\n * ```\n * {\n * parent: {\n * instance: parentControllerInstance\n * }\n * }\n * ```\n * * `futureParentElement` - defines the parent to which the `cloneAttachFn` will add\n * the cloned elements; only needed for transcludes that are allowed to contain non html\n * elements (e.g. SVG elements). See also the directive.controller property.\n *\n * Calling the linking function returns the element of the template. It is either the original\n * element passed in, or the clone of the element if the `cloneAttachFn` is provided.\n *\n * After linking the view is not updated until after a call to $digest which typically is done by\n * Angular automatically.\n *\n * If you need access to the bound view, there are two ways to do it:\n *\n * - If you are not asking the linking function to clone the template, create the DOM element(s)\n * before you send them to the compiler and keep this reference around.\n * ```js\n * var element = $compile('

{{total}}

')(scope);\n * ```\n *\n * - if on the other hand, you need the element to be cloned, the view reference from the original\n * example would not point to the clone, but rather to the original template that was cloned. In\n * this case, you can access the clone via the cloneAttachFn:\n * ```js\n * var templateElement = angular.element('

{{total}}

'),\n * scope = ....;\n *\n * var clonedElement = $compile(templateElement)(scope, function(clonedElement, scope) {\n * //attach the clone to DOM document at the right place\n * });\n *\n * //now we have reference to the cloned DOM via `clonedElement`\n * ```\n *\n *\n * For information on how the compiler works, see the\n * {@link guide/compiler Angular HTML Compiler} section of the Developer Guide.\n *\n * @knownIssue\n *\n * ### Double Compilation\n *\n Double compilation occurs when an already compiled part of the DOM gets\n compiled again. This is an undesired effect and can lead to misbehaving directives, performance issues,\n and memory leaks. Refer to the Compiler Guide {@link guide/compiler#double-compilation-and-how-to-avoid-it\n section on double compilation} for an in-depth explanation and ways to avoid it.\n *\n */\n\nvar $compileMinErr = minErr('$compile');\n\nfunction UNINITIALIZED_VALUE() {}\nvar _UNINITIALIZED_VALUE = new UNINITIALIZED_VALUE();\n\n/**\n * @ngdoc provider\n * @name $compileProvider\n *\n * @description\n */\n$CompileProvider.$inject = ['$provide', '$$sanitizeUriProvider'];\n/** @this */\nfunction $CompileProvider($provide, $$sanitizeUriProvider) {\n var hasDirectives = {},\n Suffix = 'Directive',\n COMMENT_DIRECTIVE_REGEXP = /^\\s*directive:\\s*([\\w-]+)\\s+(.*)$/,\n CLASS_DIRECTIVE_REGEXP = /(([\\w-]+)(?::([^;]+))?;?)/,\n ALL_OR_NOTHING_ATTRS = makeMap('ngSrc,ngSrcset,src,srcset'),\n REQUIRE_PREFIX_REGEXP = /^(?:(\\^\\^?)?(\\?)?(\\^\\^?)?)?/;\n\n // Ref: http://developers.whatwg.org/webappapis.html#event-handler-idl-attributes\n // The assumption is that future DOM event attribute names will begin with\n // 'on' and be composed of only English letters.\n var EVENT_HANDLER_ATTR_REGEXP = /^(on[a-z]+|formaction)$/;\n var bindingCache = createMap();\n\n function parseIsolateBindings(scope, directiveName, isController) {\n var LOCAL_REGEXP = /^\\s*([@&<]|=(\\*?))(\\??)\\s*(\\w*)\\s*$/;\n\n var bindings = createMap();\n\n forEach(scope, function(definition, scopeName) {\n if (definition in bindingCache) {\n bindings[scopeName] = bindingCache[definition];\n return;\n }\n var match = definition.match(LOCAL_REGEXP);\n\n if (!match) {\n throw $compileMinErr('iscp',\n 'Invalid {3} for directive \\'{0}\\'.' +\n ' Definition: {... {1}: \\'{2}\\' ...}',\n directiveName, scopeName, definition,\n (isController ? 'controller bindings definition' :\n 'isolate scope definition'));\n }\n\n bindings[scopeName] = {\n mode: match[1][0],\n collection: match[2] === '*',\n optional: match[3] === '?',\n attrName: match[4] || scopeName\n };\n if (match[4]) {\n bindingCache[definition] = bindings[scopeName];\n }\n });\n\n return bindings;\n }\n\n function parseDirectiveBindings(directive, directiveName) {\n var bindings = {\n isolateScope: null,\n bindToController: null\n };\n if (isObject(directive.scope)) {\n if (directive.bindToController === true) {\n bindings.bindToController = parseIsolateBindings(directive.scope,\n directiveName, true);\n bindings.isolateScope = {};\n } else {\n bindings.isolateScope = parseIsolateBindings(directive.scope,\n directiveName, false);\n }\n }\n if (isObject(directive.bindToController)) {\n bindings.bindToController =\n parseIsolateBindings(directive.bindToController, directiveName, true);\n }\n if (bindings.bindToController && !directive.controller) {\n // There is no controller\n throw $compileMinErr('noctrl',\n 'Cannot bind to controller without directive \\'{0}\\'s controller.',\n directiveName);\n }\n return bindings;\n }\n\n function assertValidDirectiveName(name) {\n var letter = name.charAt(0);\n if (!letter || letter !== lowercase(letter)) {\n throw $compileMinErr('baddir', 'Directive/Component name \\'{0}\\' is invalid. The first character must be a lowercase letter', name);\n }\n if (name !== name.trim()) {\n throw $compileMinErr('baddir',\n 'Directive/Component name \\'{0}\\' is invalid. The name should not contain leading or trailing whitespaces',\n name);\n }\n }\n\n function getDirectiveRequire(directive) {\n var require = directive.require || (directive.controller && directive.name);\n\n if (!isArray(require) && isObject(require)) {\n forEach(require, function(value, key) {\n var match = value.match(REQUIRE_PREFIX_REGEXP);\n var name = value.substring(match[0].length);\n if (!name) require[key] = match[0] + key;\n });\n }\n\n return require;\n }\n\n function getDirectiveRestrict(restrict, name) {\n if (restrict && !(isString(restrict) && /[EACM]/.test(restrict))) {\n throw $compileMinErr('badrestrict',\n 'Restrict property \\'{0}\\' of directive \\'{1}\\' is invalid',\n restrict,\n name);\n }\n\n return restrict || 'EA';\n }\n\n /**\n * @ngdoc method\n * @name $compileProvider#directive\n * @kind function\n *\n * @description\n * Register a new directive with the compiler.\n *\n * @param {string|Object} name Name of the directive in camel-case (i.e. ngBind which\n * will match as ng-bind), or an object map of directives where the keys are the\n * names and the values are the factories.\n * @param {Function|Array} directiveFactory An injectable directive factory function. See the\n * {@link guide/directive directive guide} and the {@link $compile compile API} for more info.\n * @returns {ng.$compileProvider} Self for chaining.\n */\n this.directive = function registerDirective(name, directiveFactory) {\n assertArg(name, 'name');\n assertNotHasOwnProperty(name, 'directive');\n if (isString(name)) {\n assertValidDirectiveName(name);\n assertArg(directiveFactory, 'directiveFactory');\n if (!hasDirectives.hasOwnProperty(name)) {\n hasDirectives[name] = [];\n $provide.factory(name + Suffix, ['$injector', '$exceptionHandler',\n function($injector, $exceptionHandler) {\n var directives = [];\n forEach(hasDirectives[name], function(directiveFactory, index) {\n try {\n var directive = $injector.invoke(directiveFactory);\n if (isFunction(directive)) {\n directive = { compile: valueFn(directive) };\n } else if (!directive.compile && directive.link) {\n directive.compile = valueFn(directive.link);\n }\n directive.priority = directive.priority || 0;\n directive.index = index;\n directive.name = directive.name || name;\n directive.require = getDirectiveRequire(directive);\n directive.restrict = getDirectiveRestrict(directive.restrict, name);\n directive.$$moduleName = directiveFactory.$$moduleName;\n directives.push(directive);\n } catch (e) {\n $exceptionHandler(e);\n }\n });\n return directives;\n }]);\n }\n hasDirectives[name].push(directiveFactory);\n } else {\n forEach(name, reverseParams(registerDirective));\n }\n return this;\n };\n\n /**\n * @ngdoc method\n * @name $compileProvider#component\n * @module ng\n * @param {string} name Name of the component in camelCase (i.e. `myComp` which will match ``)\n * @param {Object} options Component definition object (a simplified\n * {@link ng.$compile#directive-definition-object directive definition object}),\n * with the following properties (all optional):\n *\n * - `controller` – `{(string|function()=}` – controller constructor function that should be\n * associated with newly created scope or the name of a {@link ng.$compile#-controller-\n * registered controller} if passed as a string. An empty `noop` function by default.\n * - `controllerAs` – `{string=}` – identifier name for to reference the controller in the component's scope.\n * If present, the controller will be published to scope under the `controllerAs` name.\n * If not present, this will default to be `$ctrl`.\n * - `template` – `{string=|function()=}` – html template as a string or a function that\n * returns an html template as a string which should be used as the contents of this component.\n * Empty string by default.\n *\n * If `template` is a function, then it is {@link auto.$injector#invoke injected} with\n * the following locals:\n *\n * - `$element` - Current element\n * - `$attrs` - Current attributes object for the element\n *\n * - `templateUrl` – `{string=|function()=}` – path or function that returns a path to an html\n * template that should be used as the contents of this component.\n *\n * If `templateUrl` is a function, then it is {@link auto.$injector#invoke injected} with\n * the following locals:\n *\n * - `$element` - Current element\n * - `$attrs` - Current attributes object for the element\n *\n * - `bindings` – `{object=}` – defines bindings between DOM attributes and component properties.\n * Component properties are always bound to the component controller and not to the scope.\n * See {@link ng.$compile#-bindtocontroller- `bindToController`}.\n * - `transclude` – `{boolean=}` – whether {@link $compile#transclusion content transclusion} is enabled.\n * Disabled by default.\n * - `require` - `{Object=}` - requires the controllers of other directives and binds them to\n * this component's controller. The object keys specify the property names under which the required\n * controllers (object values) will be bound. See {@link ng.$compile#-require- `require`}.\n * - `$...` – additional properties to attach to the directive factory function and the controller\n * constructor function. (This is used by the component router to annotate)\n *\n * @returns {ng.$compileProvider} the compile provider itself, for chaining of function calls.\n * @description\n * Register a **component definition** with the compiler. This is a shorthand for registering a special\n * type of directive, which represents a self-contained UI component in your application. Such components\n * are always isolated (i.e. `scope: {}`) and are always restricted to elements (i.e. `restrict: 'E'`).\n *\n * Component definitions are very simple and do not require as much configuration as defining general\n * directives. Component definitions usually consist only of a template and a controller backing it.\n *\n * In order to make the definition easier, components enforce best practices like use of `controllerAs`,\n * `bindToController`. They always have **isolate scope** and are restricted to elements.\n *\n * Here are a few examples of how you would usually define components:\n *\n * ```js\n * var myMod = angular.module(...);\n * myMod.component('myComp', {\n * template: '
My name is {{$ctrl.name}}
',\n * controller: function() {\n * this.name = 'shahar';\n * }\n * });\n *\n * myMod.component('myComp', {\n * template: '
My name is {{$ctrl.name}}
',\n * bindings: {name: '@'}\n * });\n *\n * myMod.component('myComp', {\n * templateUrl: 'views/my-comp.html',\n * controller: 'MyCtrl',\n * controllerAs: 'ctrl',\n * bindings: {name: '@'}\n * });\n *\n * ```\n * For more examples, and an in-depth guide, see the {@link guide/component component guide}.\n *\n *
\n * See also {@link ng.$compileProvider#directive $compileProvider.directive()}.\n */\n this.component = function registerComponent(name, options) {\n var controller = options.controller || function() {};\n\n function factory($injector) {\n function makeInjectable(fn) {\n if (isFunction(fn) || isArray(fn)) {\n return /** @this */ function(tElement, tAttrs) {\n return $injector.invoke(fn, this, {$element: tElement, $attrs: tAttrs});\n };\n } else {\n return fn;\n }\n }\n\n var template = (!options.template && !options.templateUrl ? '' : options.template);\n var ddo = {\n controller: controller,\n controllerAs: identifierForController(options.controller) || options.controllerAs || '$ctrl',\n template: makeInjectable(template),\n templateUrl: makeInjectable(options.templateUrl),\n transclude: options.transclude,\n scope: {},\n bindToController: options.bindings || {},\n restrict: 'E',\n require: options.require\n };\n\n // Copy annotations (starting with $) over to the DDO\n forEach(options, function(val, key) {\n if (key.charAt(0) === '$') ddo[key] = val;\n });\n\n return ddo;\n }\n\n // TODO(pete) remove the following `forEach` before we release 1.6.0\n // The component-router@0.2.0 looks for the annotations on the controller constructor\n // Nothing in Angular looks for annotations on the factory function but we can't remove\n // it from 1.5.x yet.\n\n // Copy any annotation properties (starting with $) over to the factory and controller constructor functions\n // These could be used by libraries such as the new component router\n forEach(options, function(val, key) {\n if (key.charAt(0) === '$') {\n factory[key] = val;\n // Don't try to copy over annotations to named controller\n if (isFunction(controller)) controller[key] = val;\n }\n });\n\n factory.$inject = ['$injector'];\n\n return this.directive(name, factory);\n };\n\n\n /**\n * @ngdoc method\n * @name $compileProvider#aHrefSanitizationWhitelist\n * @kind function\n *\n * @description\n * Retrieves or overrides the default regular expression that is used for whitelisting of safe\n * urls during a[href] sanitization.\n *\n * The sanitization is a security measure aimed at preventing XSS attacks via html links.\n *\n * Any url about to be assigned to a[href] via data-binding is first normalized and turned into\n * an absolute url. Afterwards, the url is matched against the `aHrefSanitizationWhitelist`\n * regular expression. If a match is found, the original url is written into the dom. Otherwise,\n * the absolute url is prefixed with `'unsafe:'` string and only then is it written into the DOM.\n *\n * @param {RegExp=} regexp New regexp to whitelist urls with.\n * @returns {RegExp|ng.$compileProvider} Current RegExp if called without value or self for\n * chaining otherwise.\n */\n this.aHrefSanitizationWhitelist = function(regexp) {\n if (isDefined(regexp)) {\n $$sanitizeUriProvider.aHrefSanitizationWhitelist(regexp);\n return this;\n } else {\n return $$sanitizeUriProvider.aHrefSanitizationWhitelist();\n }\n };\n\n\n /**\n * @ngdoc method\n * @name $compileProvider#imgSrcSanitizationWhitelist\n * @kind function\n *\n * @description\n * Retrieves or overrides the default regular expression that is used for whitelisting of safe\n * urls during img[src] sanitization.\n *\n * The sanitization is a security measure aimed at prevent XSS attacks via html links.\n *\n * Any url about to be assigned to img[src] via data-binding is first normalized and turned into\n * an absolute url. Afterwards, the url is matched against the `imgSrcSanitizationWhitelist`\n * regular expression. If a match is found, the original url is written into the dom. Otherwise,\n * the absolute url is prefixed with `'unsafe:'` string and only then is it written into the DOM.\n *\n * @param {RegExp=} regexp New regexp to whitelist urls with.\n * @returns {RegExp|ng.$compileProvider} Current RegExp if called without value or self for\n * chaining otherwise.\n */\n this.imgSrcSanitizationWhitelist = function(regexp) {\n if (isDefined(regexp)) {\n $$sanitizeUriProvider.imgSrcSanitizationWhitelist(regexp);\n return this;\n } else {\n return $$sanitizeUriProvider.imgSrcSanitizationWhitelist();\n }\n };\n\n /**\n * @ngdoc method\n * @name $compileProvider#debugInfoEnabled\n *\n * @param {boolean=} enabled update the debugInfoEnabled state if provided, otherwise just return the\n * current debugInfoEnabled state\n * @returns {*} current value if used as getter or itself (chaining) if used as setter\n *\n * @kind function\n *\n * @description\n * Call this method to enable/disable various debug runtime information in the compiler such as adding\n * binding information and a reference to the current scope on to DOM elements.\n * If enabled, the compiler will add the following to DOM elements that have been bound to the scope\n * * `ng-binding` CSS class\n * * `$binding` data property containing an array of the binding expressions\n *\n * You may want to disable this in production for a significant performance boost. See\n * {@link guide/production#disabling-debug-data Disabling Debug Data} for more.\n *\n * The default value is true.\n */\n var debugInfoEnabled = true;\n this.debugInfoEnabled = function(enabled) {\n if (isDefined(enabled)) {\n debugInfoEnabled = enabled;\n return this;\n }\n return debugInfoEnabled;\n };\n\n /**\n * @ngdoc method\n * @name $compileProvider#preAssignBindingsEnabled\n *\n * @param {boolean=} enabled update the preAssignBindingsEnabled state if provided, otherwise just return the\n * current preAssignBindingsEnabled state\n * @returns {*} current value if used as getter or itself (chaining) if used as setter\n *\n * @kind function\n *\n * @description\n * Call this method to enable/disable whether directive controllers are assigned bindings before\n * calling the controller's constructor.\n * If enabled (true), the compiler assigns the value of each of the bindings to the\n * properties of the controller object before the constructor of this object is called.\n *\n * If disabled (false), the compiler calls the constructor first before assigning bindings.\n *\n * The default value is true in Angular 1.5.x but will switch to false in Angular 1.6.x.\n */\n var preAssignBindingsEnabled = false;\n this.preAssignBindingsEnabled = function(enabled) {\n if (isDefined(enabled)) {\n preAssignBindingsEnabled = enabled;\n return this;\n }\n return preAssignBindingsEnabled;\n };\n\n\n var TTL = 10;\n /**\n * @ngdoc method\n * @name $compileProvider#onChangesTtl\n * @description\n *\n * Sets the number of times `$onChanges` hooks can trigger new changes before giving up and\n * assuming that the model is unstable.\n *\n * The current default is 10 iterations.\n *\n * In complex applications it's possible that dependencies between `$onChanges` hooks and bindings will result\n * in several iterations of calls to these hooks. However if an application needs more than the default 10\n * iterations to stabilize then you should investigate what is causing the model to continuously change during\n * the `$onChanges` hook execution.\n *\n * Increasing the TTL could have performance implications, so you should not change it without proper justification.\n *\n * @param {number} limit The number of `$onChanges` hook iterations.\n * @returns {number|object} the current limit (or `this` if called as a setter for chaining)\n */\n this.onChangesTtl = function(value) {\n if (arguments.length) {\n TTL = value;\n return this;\n }\n return TTL;\n };\n\n var commentDirectivesEnabledConfig = true;\n /**\n * @ngdoc method\n * @name $compileProvider#commentDirectivesEnabled\n * @description\n *\n * It indicates to the compiler\n * whether or not directives on comments should be compiled.\n * Defaults to `true`.\n *\n * Calling this function with false disables the compilation of directives\n * on comments for the whole application.\n * This results in a compilation performance gain,\n * as the compiler doesn't have to check comments when looking for directives.\n * This should however only be used if you are sure that no comment directives are used in\n * the application (including any 3rd party directives).\n *\n * @param {boolean} enabled `false` if the compiler may ignore directives on comments\n * @returns {boolean|object} the current value (or `this` if called as a setter for chaining)\n */\n this.commentDirectivesEnabled = function(value) {\n if (arguments.length) {\n commentDirectivesEnabledConfig = value;\n return this;\n }\n return commentDirectivesEnabledConfig;\n };\n\n\n var cssClassDirectivesEnabledConfig = true;\n /**\n * @ngdoc method\n * @name $compileProvider#cssClassDirectivesEnabled\n * @description\n *\n * It indicates to the compiler\n * whether or not directives on element classes should be compiled.\n * Defaults to `true`.\n *\n * Calling this function with false disables the compilation of directives\n * on element classes for the whole application.\n * This results in a compilation performance gain,\n * as the compiler doesn't have to check element classes when looking for directives.\n * This should however only be used if you are sure that no class directives are used in\n * the application (including any 3rd party directives).\n *\n * @param {boolean} enabled `false` if the compiler may ignore directives on element classes\n * @returns {boolean|object} the current value (or `this` if called as a setter for chaining)\n */\n this.cssClassDirectivesEnabled = function(value) {\n if (arguments.length) {\n cssClassDirectivesEnabledConfig = value;\n return this;\n }\n return cssClassDirectivesEnabledConfig;\n };\n\n this.$get = [\n '$injector', '$interpolate', '$exceptionHandler', '$templateRequest', '$parse',\n '$controller', '$rootScope', '$sce', '$animate', '$$sanitizeUri',\n function($injector, $interpolate, $exceptionHandler, $templateRequest, $parse,\n $controller, $rootScope, $sce, $animate, $$sanitizeUri) {\n\n var SIMPLE_ATTR_NAME = /^\\w/;\n var specialAttrHolder = window.document.createElement('div');\n\n\n var commentDirectivesEnabled = commentDirectivesEnabledConfig;\n var cssClassDirectivesEnabled = cssClassDirectivesEnabledConfig;\n\n\n var onChangesTtl = TTL;\n // The onChanges hooks should all be run together in a single digest\n // When changes occur, the call to trigger their hooks will be added to this queue\n var onChangesQueue;\n\n // This function is called in a $$postDigest to trigger all the onChanges hooks in a single digest\n function flushOnChangesQueue() {\n try {\n if (!(--onChangesTtl)) {\n // We have hit the TTL limit so reset everything\n onChangesQueue = undefined;\n throw $compileMinErr('infchng', '{0} $onChanges() iterations reached. Aborting!\\n', TTL);\n }\n // We must run this hook in an apply since the $$postDigest runs outside apply\n $rootScope.$apply(function() {\n var errors = [];\n for (var i = 0, ii = onChangesQueue.length; i < ii; ++i) {\n try {\n onChangesQueue[i]();\n } catch (e) {\n errors.push(e);\n }\n }\n // Reset the queue to trigger a new schedule next time there is a change\n onChangesQueue = undefined;\n if (errors.length) {\n throw errors;\n }\n });\n } finally {\n onChangesTtl++;\n }\n }\n\n\n function Attributes(element, attributesToCopy) {\n if (attributesToCopy) {\n var keys = Object.keys(attributesToCopy);\n var i, l, key;\n\n for (i = 0, l = keys.length; i < l; i++) {\n key = keys[i];\n this[key] = attributesToCopy[key];\n }\n } else {\n this.$attr = {};\n }\n\n this.$$element = element;\n }\n\n Attributes.prototype = {\n /**\n * @ngdoc method\n * @name $compile.directive.Attributes#$normalize\n * @kind function\n *\n * @description\n * Converts an attribute name (e.g. dash/colon/underscore-delimited string, optionally prefixed with `x-` or\n * `data-`) to its normalized, camelCase form.\n *\n * Also there is special case for Moz prefix starting with upper case letter.\n *\n * For further information check out the guide on {@link guide/directive#matching-directives Matching Directives}\n *\n * @param {string} name Name to normalize\n */\n $normalize: directiveNormalize,\n\n\n /**\n * @ngdoc method\n * @name $compile.directive.Attributes#$addClass\n * @kind function\n *\n * @description\n * Adds the CSS class value specified by the classVal parameter to the element. If animations\n * are enabled then an animation will be triggered for the class addition.\n *\n * @param {string} classVal The className value that will be added to the element\n */\n $addClass: function(classVal) {\n if (classVal && classVal.length > 0) {\n $animate.addClass(this.$$element, classVal);\n }\n },\n\n /**\n * @ngdoc method\n * @name $compile.directive.Attributes#$removeClass\n * @kind function\n *\n * @description\n * Removes the CSS class value specified by the classVal parameter from the element. If\n * animations are enabled then an animation will be triggered for the class removal.\n *\n * @param {string} classVal The className value that will be removed from the element\n */\n $removeClass: function(classVal) {\n if (classVal && classVal.length > 0) {\n $animate.removeClass(this.$$element, classVal);\n }\n },\n\n /**\n * @ngdoc method\n * @name $compile.directive.Attributes#$updateClass\n * @kind function\n *\n * @description\n * Adds and removes the appropriate CSS class values to the element based on the difference\n * between the new and old CSS class values (specified as newClasses and oldClasses).\n *\n * @param {string} newClasses The current CSS className value\n * @param {string} oldClasses The former CSS className value\n */\n $updateClass: function(newClasses, oldClasses) {\n var toAdd = tokenDifference(newClasses, oldClasses);\n if (toAdd && toAdd.length) {\n $animate.addClass(this.$$element, toAdd);\n }\n\n var toRemove = tokenDifference(oldClasses, newClasses);\n if (toRemove && toRemove.length) {\n $animate.removeClass(this.$$element, toRemove);\n }\n },\n\n /**\n * Set a normalized attribute on the element in a way such that all directives\n * can share the attribute. This function properly handles boolean attributes.\n * @param {string} key Normalized key. (ie ngAttribute)\n * @param {string|boolean} value The value to set. If `null` attribute will be deleted.\n * @param {boolean=} writeAttr If false, does not write the value to DOM element attribute.\n * Defaults to true.\n * @param {string=} attrName Optional none normalized name. Defaults to key.\n */\n $set: function(key, value, writeAttr, attrName) {\n // TODO: decide whether or not to throw an error if \"class\"\n //is set through this function since it may cause $updateClass to\n //become unstable.\n\n var node = this.$$element[0],\n booleanKey = getBooleanAttrName(node, key),\n aliasedKey = getAliasedAttrName(key),\n observer = key,\n nodeName;\n\n if (booleanKey) {\n this.$$element.prop(key, value);\n attrName = booleanKey;\n } else if (aliasedKey) {\n this[aliasedKey] = value;\n observer = aliasedKey;\n }\n\n this[key] = value;\n\n // translate normalized key to actual key\n if (attrName) {\n this.$attr[key] = attrName;\n } else {\n attrName = this.$attr[key];\n if (!attrName) {\n this.$attr[key] = attrName = snake_case(key, '-');\n }\n }\n\n nodeName = nodeName_(this.$$element);\n\n if ((nodeName === 'a' && (key === 'href' || key === 'xlinkHref')) ||\n (nodeName === 'img' && key === 'src')) {\n // sanitize a[href] and img[src] values\n this[key] = value = $$sanitizeUri(value, key === 'src');\n } else if (nodeName === 'img' && key === 'srcset' && isDefined(value)) {\n // sanitize img[srcset] values\n var result = '';\n\n // first check if there are spaces because it's not the same pattern\n var trimmedSrcset = trim(value);\n // ( 999x ,| 999w ,| ,|, )\n var srcPattern = /(\\s+\\d+x\\s*,|\\s+\\d+w\\s*,|\\s+,|,\\s+)/;\n var pattern = /\\s/.test(trimmedSrcset) ? srcPattern : /(,)/;\n\n // split srcset into tuple of uri and descriptor except for the last item\n var rawUris = trimmedSrcset.split(pattern);\n\n // for each tuples\n var nbrUrisWith2parts = Math.floor(rawUris.length / 2);\n for (var i = 0; i < nbrUrisWith2parts; i++) {\n var innerIdx = i * 2;\n // sanitize the uri\n result += $$sanitizeUri(trim(rawUris[innerIdx]), true);\n // add the descriptor\n result += (' ' + trim(rawUris[innerIdx + 1]));\n }\n\n // split the last item into uri and descriptor\n var lastTuple = trim(rawUris[i * 2]).split(/\\s/);\n\n // sanitize the last uri\n result += $$sanitizeUri(trim(lastTuple[0]), true);\n\n // and add the last descriptor if any\n if (lastTuple.length === 2) {\n result += (' ' + trim(lastTuple[1]));\n }\n this[key] = value = result;\n }\n\n if (writeAttr !== false) {\n if (value === null || isUndefined(value)) {\n this.$$element.removeAttr(attrName);\n } else {\n if (SIMPLE_ATTR_NAME.test(attrName)) {\n this.$$element.attr(attrName, value);\n } else {\n setSpecialAttr(this.$$element[0], attrName, value);\n }\n }\n }\n\n // fire observers\n var $$observers = this.$$observers;\n if ($$observers) {\n forEach($$observers[observer], function(fn) {\n try {\n fn(value);\n } catch (e) {\n $exceptionHandler(e);\n }\n });\n }\n },\n\n\n /**\n * @ngdoc method\n * @name $compile.directive.Attributes#$observe\n * @kind function\n *\n * @description\n * Observes an interpolated attribute.\n *\n * The observer function will be invoked once during the next `$digest` following\n * compilation. The observer is then invoked whenever the interpolated value\n * changes.\n *\n * @param {string} key Normalized key. (ie ngAttribute) .\n * @param {function(interpolatedValue)} fn Function that will be called whenever\n the interpolated value of the attribute changes.\n * See the {@link guide/interpolation#how-text-and-attribute-bindings-work Interpolation\n * guide} for more info.\n * @returns {function()} Returns a deregistration function for this observer.\n */\n $observe: function(key, fn) {\n var attrs = this,\n $$observers = (attrs.$$observers || (attrs.$$observers = createMap())),\n listeners = ($$observers[key] || ($$observers[key] = []));\n\n listeners.push(fn);\n $rootScope.$evalAsync(function() {\n if (!listeners.$$inter && attrs.hasOwnProperty(key) && !isUndefined(attrs[key])) {\n // no one registered attribute interpolation function, so lets call it manually\n fn(attrs[key]);\n }\n });\n\n return function() {\n arrayRemove(listeners, fn);\n };\n }\n };\n\n function setSpecialAttr(element, attrName, value) {\n // Attributes names that do not start with letters (such as `(click)`) cannot be set using `setAttribute`\n // so we have to jump through some hoops to get such an attribute\n // https://github.com/angular/angular.js/pull/13318\n specialAttrHolder.innerHTML = '';\n var attributes = specialAttrHolder.firstChild.attributes;\n var attribute = attributes[0];\n // We have to remove the attribute from its container element before we can add it to the destination element\n attributes.removeNamedItem(attribute.name);\n attribute.value = value;\n element.attributes.setNamedItem(attribute);\n }\n\n function safeAddClass($element, className) {\n try {\n $element.addClass(className);\n } catch (e) {\n // ignore, since it means that we are trying to set class on\n // SVG element, where class name is read-only.\n }\n }\n\n\n var startSymbol = $interpolate.startSymbol(),\n endSymbol = $interpolate.endSymbol(),\n denormalizeTemplate = (startSymbol === '{{' && endSymbol === '}}')\n ? identity\n : function denormalizeTemplate(template) {\n return template.replace(/\\{\\{/g, startSymbol).replace(/}}/g, endSymbol);\n },\n NG_ATTR_BINDING = /^ngAttr[A-Z]/;\n var MULTI_ELEMENT_DIR_RE = /^(.+)Start$/;\n\n compile.$$addBindingInfo = debugInfoEnabled ? function $$addBindingInfo($element, binding) {\n var bindings = $element.data('$binding') || [];\n\n if (isArray(binding)) {\n bindings = bindings.concat(binding);\n } else {\n bindings.push(binding);\n }\n\n $element.data('$binding', bindings);\n } : noop;\n\n compile.$$addBindingClass = debugInfoEnabled ? function $$addBindingClass($element) {\n safeAddClass($element, 'ng-binding');\n } : noop;\n\n compile.$$addScopeInfo = debugInfoEnabled ? function $$addScopeInfo($element, scope, isolated, noTemplate) {\n var dataName = isolated ? (noTemplate ? '$isolateScopeNoTemplate' : '$isolateScope') : '$scope';\n $element.data(dataName, scope);\n } : noop;\n\n compile.$$addScopeClass = debugInfoEnabled ? function $$addScopeClass($element, isolated) {\n safeAddClass($element, isolated ? 'ng-isolate-scope' : 'ng-scope');\n } : noop;\n\n compile.$$createComment = function(directiveName, comment) {\n var content = '';\n if (debugInfoEnabled) {\n content = ' ' + (directiveName || '') + ': ';\n if (comment) content += comment + ' ';\n }\n return window.document.createComment(content);\n };\n\n return compile;\n\n //================================\n\n function compile($compileNodes, transcludeFn, maxPriority, ignoreDirective,\n previousCompileContext) {\n if (!($compileNodes instanceof jqLite)) {\n // jquery always rewraps, whereas we need to preserve the original selector so that we can\n // modify it.\n $compileNodes = jqLite($compileNodes);\n }\n var compositeLinkFn =\n compileNodes($compileNodes, transcludeFn, $compileNodes,\n maxPriority, ignoreDirective, previousCompileContext);\n compile.$$addScopeClass($compileNodes);\n var namespace = null;\n return function publicLinkFn(scope, cloneConnectFn, options) {\n if (!$compileNodes) {\n throw $compileMinErr('multilink', 'This element has already been linked.');\n }\n assertArg(scope, 'scope');\n\n if (previousCompileContext && previousCompileContext.needsNewScope) {\n // A parent directive did a replace and a directive on this element asked\n // for transclusion, which caused us to lose a layer of element on which\n // we could hold the new transclusion scope, so we will create it manually\n // here.\n scope = scope.$parent.$new();\n }\n\n options = options || {};\n var parentBoundTranscludeFn = options.parentBoundTranscludeFn,\n transcludeControllers = options.transcludeControllers,\n futureParentElement = options.futureParentElement;\n\n // When `parentBoundTranscludeFn` is passed, it is a\n // `controllersBoundTransclude` function (it was previously passed\n // as `transclude` to directive.link) so we must unwrap it to get\n // its `boundTranscludeFn`\n if (parentBoundTranscludeFn && parentBoundTranscludeFn.$$boundTransclude) {\n parentBoundTranscludeFn = parentBoundTranscludeFn.$$boundTransclude;\n }\n\n if (!namespace) {\n namespace = detectNamespaceForChildElements(futureParentElement);\n }\n var $linkNode;\n if (namespace !== 'html') {\n // When using a directive with replace:true and templateUrl the $compileNodes\n // (or a child element inside of them)\n // might change, so we need to recreate the namespace adapted compileNodes\n // for call to the link function.\n // Note: This will already clone the nodes...\n $linkNode = jqLite(\n wrapTemplate(namespace, jqLite('
').append($compileNodes).html())\n );\n } else if (cloneConnectFn) {\n // important!!: we must call our jqLite.clone() since the jQuery one is trying to be smart\n // and sometimes changes the structure of the DOM.\n $linkNode = JQLitePrototype.clone.call($compileNodes);\n } else {\n $linkNode = $compileNodes;\n }\n\n if (transcludeControllers) {\n for (var controllerName in transcludeControllers) {\n $linkNode.data('$' + controllerName + 'Controller', transcludeControllers[controllerName].instance);\n }\n }\n\n compile.$$addScopeInfo($linkNode, scope);\n\n if (cloneConnectFn) cloneConnectFn($linkNode, scope);\n if (compositeLinkFn) compositeLinkFn(scope, $linkNode, $linkNode, parentBoundTranscludeFn);\n\n if (!cloneConnectFn) {\n $compileNodes = compositeLinkFn = null;\n }\n return $linkNode;\n };\n }\n\n function detectNamespaceForChildElements(parentElement) {\n // TODO: Make this detect MathML as well...\n var node = parentElement && parentElement[0];\n if (!node) {\n return 'html';\n } else {\n return nodeName_(node) !== 'foreignobject' && toString.call(node).match(/SVG/) ? 'svg' : 'html';\n }\n }\n\n /**\n * Compile function matches each node in nodeList against the directives. Once all directives\n * for a particular node are collected their compile functions are executed. The compile\n * functions return values - the linking functions - are combined into a composite linking\n * function, which is the a linking function for the node.\n *\n * @param {NodeList} nodeList an array of nodes or NodeList to compile\n * @param {function(angular.Scope, cloneAttachFn=)} transcludeFn A linking function, where the\n * scope argument is auto-generated to the new child of the transcluded parent scope.\n * @param {DOMElement=} $rootElement If the nodeList is the root of the compilation tree then\n * the rootElement must be set the jqLite collection of the compile root. This is\n * needed so that the jqLite collection items can be replaced with widgets.\n * @param {number=} maxPriority Max directive priority.\n * @returns {Function} A composite linking function of all of the matched directives or null.\n */\n function compileNodes(nodeList, transcludeFn, $rootElement, maxPriority, ignoreDirective,\n previousCompileContext) {\n var linkFns = [],\n // `nodeList` can be either an element's `.childNodes` (live NodeList)\n // or a jqLite/jQuery collection or an array\n notLiveList = isArray(nodeList) || (nodeList instanceof jqLite),\n attrs, directives, nodeLinkFn, childNodes, childLinkFn, linkFnFound, nodeLinkFnFound;\n\n\n for (var i = 0; i < nodeList.length; i++) {\n attrs = new Attributes();\n\n // Support: IE 11 only\n // Workaround for #11781 and #14924\n if (msie === 11) {\n mergeConsecutiveTextNodes(nodeList, i, notLiveList);\n }\n\n // We must always refer to `nodeList[i]` hereafter,\n // since the nodes can be replaced underneath us.\n directives = collectDirectives(nodeList[i], [], attrs, i === 0 ? maxPriority : undefined,\n ignoreDirective);\n\n nodeLinkFn = (directives.length)\n ? applyDirectivesToNode(directives, nodeList[i], attrs, transcludeFn, $rootElement,\n null, [], [], previousCompileContext)\n : null;\n\n if (nodeLinkFn && nodeLinkFn.scope) {\n compile.$$addScopeClass(attrs.$$element);\n }\n\n childLinkFn = (nodeLinkFn && nodeLinkFn.terminal ||\n !(childNodes = nodeList[i].childNodes) ||\n !childNodes.length)\n ? null\n : compileNodes(childNodes,\n nodeLinkFn ? (\n (nodeLinkFn.transcludeOnThisElement || !nodeLinkFn.templateOnThisElement)\n && nodeLinkFn.transclude) : transcludeFn);\n\n if (nodeLinkFn || childLinkFn) {\n linkFns.push(i, nodeLinkFn, childLinkFn);\n linkFnFound = true;\n nodeLinkFnFound = nodeLinkFnFound || nodeLinkFn;\n }\n\n //use the previous context only for the first element in the virtual group\n previousCompileContext = null;\n }\n\n // return a linking function if we have found anything, null otherwise\n return linkFnFound ? compositeLinkFn : null;\n\n function compositeLinkFn(scope, nodeList, $rootElement, parentBoundTranscludeFn) {\n var nodeLinkFn, childLinkFn, node, childScope, i, ii, idx, childBoundTranscludeFn;\n var stableNodeList;\n\n\n if (nodeLinkFnFound) {\n // copy nodeList so that if a nodeLinkFn removes or adds an element at this DOM level our\n // offsets don't get screwed up\n var nodeListLength = nodeList.length;\n stableNodeList = new Array(nodeListLength);\n\n // create a sparse array by only copying the elements which have a linkFn\n for (i = 0; i < linkFns.length; i += 3) {\n idx = linkFns[i];\n stableNodeList[idx] = nodeList[idx];\n }\n } else {\n stableNodeList = nodeList;\n }\n\n for (i = 0, ii = linkFns.length; i < ii;) {\n node = stableNodeList[linkFns[i++]];\n nodeLinkFn = linkFns[i++];\n childLinkFn = linkFns[i++];\n\n if (nodeLinkFn) {\n if (nodeLinkFn.scope) {\n childScope = scope.$new();\n compile.$$addScopeInfo(jqLite(node), childScope);\n } else {\n childScope = scope;\n }\n\n if (nodeLinkFn.transcludeOnThisElement) {\n childBoundTranscludeFn = createBoundTranscludeFn(\n scope, nodeLinkFn.transclude, parentBoundTranscludeFn);\n\n } else if (!nodeLinkFn.templateOnThisElement && parentBoundTranscludeFn) {\n childBoundTranscludeFn = parentBoundTranscludeFn;\n\n } else if (!parentBoundTranscludeFn && transcludeFn) {\n childBoundTranscludeFn = createBoundTranscludeFn(scope, transcludeFn);\n\n } else {\n childBoundTranscludeFn = null;\n }\n\n nodeLinkFn(childLinkFn, childScope, node, $rootElement, childBoundTranscludeFn);\n\n } else if (childLinkFn) {\n childLinkFn(scope, node.childNodes, undefined, parentBoundTranscludeFn);\n }\n }\n }\n }\n\n function mergeConsecutiveTextNodes(nodeList, idx, notLiveList) {\n var node = nodeList[idx];\n var parent = node.parentNode;\n var sibling;\n\n if (node.nodeType !== NODE_TYPE_TEXT) {\n return;\n }\n\n while (true) {\n sibling = parent ? node.nextSibling : nodeList[idx + 1];\n if (!sibling || sibling.nodeType !== NODE_TYPE_TEXT) {\n break;\n }\n\n node.nodeValue = node.nodeValue + sibling.nodeValue;\n\n if (sibling.parentNode) {\n sibling.parentNode.removeChild(sibling);\n }\n if (notLiveList && sibling === nodeList[idx + 1]) {\n nodeList.splice(idx + 1, 1);\n }\n }\n }\n\n function createBoundTranscludeFn(scope, transcludeFn, previousBoundTranscludeFn) {\n function boundTranscludeFn(transcludedScope, cloneFn, controllers, futureParentElement, containingScope) {\n\n if (!transcludedScope) {\n transcludedScope = scope.$new(false, containingScope);\n transcludedScope.$$transcluded = true;\n }\n\n return transcludeFn(transcludedScope, cloneFn, {\n parentBoundTranscludeFn: previousBoundTranscludeFn,\n transcludeControllers: controllers,\n futureParentElement: futureParentElement\n });\n }\n\n // We need to attach the transclusion slots onto the `boundTranscludeFn`\n // so that they are available inside the `controllersBoundTransclude` function\n var boundSlots = boundTranscludeFn.$$slots = createMap();\n for (var slotName in transcludeFn.$$slots) {\n if (transcludeFn.$$slots[slotName]) {\n boundSlots[slotName] = createBoundTranscludeFn(scope, transcludeFn.$$slots[slotName], previousBoundTranscludeFn);\n } else {\n boundSlots[slotName] = null;\n }\n }\n\n return boundTranscludeFn;\n }\n\n /**\n * Looks for directives on the given node and adds them to the directive collection which is\n * sorted.\n *\n * @param node Node to search.\n * @param directives An array to which the directives are added to. This array is sorted before\n * the function returns.\n * @param attrs The shared attrs object which is used to populate the normalized attributes.\n * @param {number=} maxPriority Max directive priority.\n */\n function collectDirectives(node, directives, attrs, maxPriority, ignoreDirective) {\n var nodeType = node.nodeType,\n attrsMap = attrs.$attr,\n match,\n nodeName,\n className;\n\n switch (nodeType) {\n case NODE_TYPE_ELEMENT: /* Element */\n\n nodeName = nodeName_(node);\n\n // use the node name: \n addDirective(directives,\n directiveNormalize(nodeName), 'E', maxPriority, ignoreDirective);\n\n // iterate over the attributes\n for (var attr, name, nName, ngAttrName, value, isNgAttr, nAttrs = node.attributes,\n j = 0, jj = nAttrs && nAttrs.length; j < jj; j++) {\n var attrStartName = false;\n var attrEndName = false;\n\n attr = nAttrs[j];\n name = attr.name;\n value = attr.value;\n\n // support ngAttr attribute binding\n ngAttrName = directiveNormalize(name);\n isNgAttr = NG_ATTR_BINDING.test(ngAttrName);\n if (isNgAttr) {\n name = name.replace(PREFIX_REGEXP, '')\n .substr(8).replace(/_(.)/g, function(match, letter) {\n return letter.toUpperCase();\n });\n }\n\n var multiElementMatch = ngAttrName.match(MULTI_ELEMENT_DIR_RE);\n if (multiElementMatch && directiveIsMultiElement(multiElementMatch[1])) {\n attrStartName = name;\n attrEndName = name.substr(0, name.length - 5) + 'end';\n name = name.substr(0, name.length - 6);\n }\n\n nName = directiveNormalize(name.toLowerCase());\n attrsMap[nName] = name;\n if (isNgAttr || !attrs.hasOwnProperty(nName)) {\n attrs[nName] = value;\n if (getBooleanAttrName(node, nName)) {\n attrs[nName] = true; // presence means true\n }\n }\n addAttrInterpolateDirective(node, directives, value, nName, isNgAttr);\n addDirective(directives, nName, 'A', maxPriority, ignoreDirective, attrStartName,\n attrEndName);\n }\n\n if (nodeName === 'input' && node.getAttribute('type') === 'hidden') {\n // Hidden input elements can have strange behaviour when navigating back to the page\n // This tells the browser not to try to cache and reinstate previous values\n node.setAttribute('autocomplete', 'off');\n }\n\n // use class as directive\n if (!cssClassDirectivesEnabled) break;\n className = node.className;\n if (isObject(className)) {\n // Maybe SVGAnimatedString\n className = className.animVal;\n }\n if (isString(className) && className !== '') {\n while ((match = CLASS_DIRECTIVE_REGEXP.exec(className))) {\n nName = directiveNormalize(match[2]);\n if (addDirective(directives, nName, 'C', maxPriority, ignoreDirective)) {\n attrs[nName] = trim(match[3]);\n }\n className = className.substr(match.index + match[0].length);\n }\n }\n break;\n case NODE_TYPE_TEXT: /* Text Node */\n addTextInterpolateDirective(directives, node.nodeValue);\n break;\n case NODE_TYPE_COMMENT: /* Comment */\n if (!commentDirectivesEnabled) break;\n collectCommentDirectives(node, directives, attrs, maxPriority, ignoreDirective);\n break;\n }\n\n directives.sort(byPriority);\n return directives;\n }\n\n function collectCommentDirectives(node, directives, attrs, maxPriority, ignoreDirective) {\n // function created because of performance, try/catch disables\n // the optimization of the whole function #14848\n try {\n var match = COMMENT_DIRECTIVE_REGEXP.exec(node.nodeValue);\n if (match) {\n var nName = directiveNormalize(match[1]);\n if (addDirective(directives, nName, 'M', maxPriority, ignoreDirective)) {\n attrs[nName] = trim(match[2]);\n }\n }\n } catch (e) {\n // turns out that under some circumstances IE9 throws errors when one attempts to read\n // comment's node value.\n // Just ignore it and continue. (Can't seem to reproduce in test case.)\n }\n }\n\n /**\n * Given a node with a directive-start it collects all of the siblings until it finds\n * directive-end.\n * @param node\n * @param attrStart\n * @param attrEnd\n * @returns {*}\n */\n function groupScan(node, attrStart, attrEnd) {\n var nodes = [];\n var depth = 0;\n if (attrStart && node.hasAttribute && node.hasAttribute(attrStart)) {\n do {\n if (!node) {\n throw $compileMinErr('uterdir',\n 'Unterminated attribute, found \\'{0}\\' but no matching \\'{1}\\' found.',\n attrStart, attrEnd);\n }\n if (node.nodeType === NODE_TYPE_ELEMENT) {\n if (node.hasAttribute(attrStart)) depth++;\n if (node.hasAttribute(attrEnd)) depth--;\n }\n nodes.push(node);\n node = node.nextSibling;\n } while (depth > 0);\n } else {\n nodes.push(node);\n }\n\n return jqLite(nodes);\n }\n\n /**\n * Wrapper for linking function which converts normal linking function into a grouped\n * linking function.\n * @param linkFn\n * @param attrStart\n * @param attrEnd\n * @returns {Function}\n */\n function groupElementsLinkFnWrapper(linkFn, attrStart, attrEnd) {\n return function groupedElementsLink(scope, element, attrs, controllers, transcludeFn) {\n element = groupScan(element[0], attrStart, attrEnd);\n return linkFn(scope, element, attrs, controllers, transcludeFn);\n };\n }\n\n /**\n * A function generator that is used to support both eager and lazy compilation\n * linking function.\n * @param eager\n * @param $compileNodes\n * @param transcludeFn\n * @param maxPriority\n * @param ignoreDirective\n * @param previousCompileContext\n * @returns {Function}\n */\n function compilationGenerator(eager, $compileNodes, transcludeFn, maxPriority, ignoreDirective, previousCompileContext) {\n var compiled;\n\n if (eager) {\n return compile($compileNodes, transcludeFn, maxPriority, ignoreDirective, previousCompileContext);\n }\n return /** @this */ function lazyCompilation() {\n if (!compiled) {\n compiled = compile($compileNodes, transcludeFn, maxPriority, ignoreDirective, previousCompileContext);\n\n // Null out all of these references in order to make them eligible for garbage collection\n // since this is a potentially long lived closure\n $compileNodes = transcludeFn = previousCompileContext = null;\n }\n return compiled.apply(this, arguments);\n };\n }\n\n /**\n * Once the directives have been collected, their compile functions are executed. This method\n * is responsible for inlining directive templates as well as terminating the application\n * of the directives if the terminal directive has been reached.\n *\n * @param {Array} directives Array of collected directives to execute their compile function.\n * this needs to be pre-sorted by priority order.\n * @param {Node} compileNode The raw DOM node to apply the compile functions to\n * @param {Object} templateAttrs The shared attribute function\n * @param {function(angular.Scope, cloneAttachFn=)} transcludeFn A linking function, where the\n * scope argument is auto-generated to the new\n * child of the transcluded parent scope.\n * @param {JQLite} jqCollection If we are working on the root of the compile tree then this\n * argument has the root jqLite array so that we can replace nodes\n * on it.\n * @param {Object=} originalReplaceDirective An optional directive that will be ignored when\n * compiling the transclusion.\n * @param {Array.} preLinkFns\n * @param {Array.} postLinkFns\n * @param {Object} previousCompileContext Context used for previous compilation of the current\n * node\n * @returns {Function} linkFn\n */\n function applyDirectivesToNode(directives, compileNode, templateAttrs, transcludeFn,\n jqCollection, originalReplaceDirective, preLinkFns, postLinkFns,\n previousCompileContext) {\n previousCompileContext = previousCompileContext || {};\n\n var terminalPriority = -Number.MAX_VALUE,\n newScopeDirective = previousCompileContext.newScopeDirective,\n controllerDirectives = previousCompileContext.controllerDirectives,\n newIsolateScopeDirective = previousCompileContext.newIsolateScopeDirective,\n templateDirective = previousCompileContext.templateDirective,\n nonTlbTranscludeDirective = previousCompileContext.nonTlbTranscludeDirective,\n hasTranscludeDirective = false,\n hasTemplate = false,\n hasElementTranscludeDirective = previousCompileContext.hasElementTranscludeDirective,\n $compileNode = templateAttrs.$$element = jqLite(compileNode),\n directive,\n directiveName,\n $template,\n replaceDirective = originalReplaceDirective,\n childTranscludeFn = transcludeFn,\n linkFn,\n didScanForMultipleTransclusion = false,\n mightHaveMultipleTransclusionError = false,\n directiveValue;\n\n // executes all directives on the current element\n for (var i = 0, ii = directives.length; i < ii; i++) {\n directive = directives[i];\n var attrStart = directive.$$start;\n var attrEnd = directive.$$end;\n\n // collect multiblock sections\n if (attrStart) {\n $compileNode = groupScan(compileNode, attrStart, attrEnd);\n }\n $template = undefined;\n\n if (terminalPriority > directive.priority) {\n break; // prevent further processing of directives\n }\n\n directiveValue = directive.scope;\n\n if (directiveValue) {\n\n // skip the check for directives with async templates, we'll check the derived sync\n // directive when the template arrives\n if (!directive.templateUrl) {\n if (isObject(directiveValue)) {\n // This directive is trying to add an isolated scope.\n // Check that there is no scope of any kind already\n assertNoDuplicate('new/isolated scope', newIsolateScopeDirective || newScopeDirective,\n directive, $compileNode);\n newIsolateScopeDirective = directive;\n } else {\n // This directive is trying to add a child scope.\n // Check that there is no isolated scope already\n assertNoDuplicate('new/isolated scope', newIsolateScopeDirective, directive,\n $compileNode);\n }\n }\n\n newScopeDirective = newScopeDirective || directive;\n }\n\n directiveName = directive.name;\n\n // If we encounter a condition that can result in transclusion on the directive,\n // then scan ahead in the remaining directives for others that may cause a multiple\n // transclusion error to be thrown during the compilation process. If a matching directive\n // is found, then we know that when we encounter a transcluded directive, we need to eagerly\n // compile the `transclude` function rather than doing it lazily in order to throw\n // exceptions at the correct time\n if (!didScanForMultipleTransclusion && ((directive.replace && (directive.templateUrl || directive.template))\n || (directive.transclude && !directive.$$tlb))) {\n var candidateDirective;\n\n for (var scanningIndex = i + 1; (candidateDirective = directives[scanningIndex++]);) {\n if ((candidateDirective.transclude && !candidateDirective.$$tlb)\n || (candidateDirective.replace && (candidateDirective.templateUrl || candidateDirective.template))) {\n mightHaveMultipleTransclusionError = true;\n break;\n }\n }\n\n didScanForMultipleTransclusion = true;\n }\n\n if (!directive.templateUrl && directive.controller) {\n controllerDirectives = controllerDirectives || createMap();\n assertNoDuplicate('\\'' + directiveName + '\\' controller',\n controllerDirectives[directiveName], directive, $compileNode);\n controllerDirectives[directiveName] = directive;\n }\n\n directiveValue = directive.transclude;\n\n if (directiveValue) {\n hasTranscludeDirective = true;\n\n // Special case ngIf and ngRepeat so that we don't complain about duplicate transclusion.\n // This option should only be used by directives that know how to safely handle element transclusion,\n // where the transcluded nodes are added or replaced after linking.\n if (!directive.$$tlb) {\n assertNoDuplicate('transclusion', nonTlbTranscludeDirective, directive, $compileNode);\n nonTlbTranscludeDirective = directive;\n }\n\n if (directiveValue === 'element') {\n hasElementTranscludeDirective = true;\n terminalPriority = directive.priority;\n $template = $compileNode;\n $compileNode = templateAttrs.$$element =\n jqLite(compile.$$createComment(directiveName, templateAttrs[directiveName]));\n compileNode = $compileNode[0];\n replaceWith(jqCollection, sliceArgs($template), compileNode);\n\n // Support: Chrome < 50\n // https://github.com/angular/angular.js/issues/14041\n\n // In the versions of V8 prior to Chrome 50, the document fragment that is created\n // in the `replaceWith` function is improperly garbage collected despite still\n // being referenced by the `parentNode` property of all of the child nodes. By adding\n // a reference to the fragment via a different property, we can avoid that incorrect\n // behavior.\n // TODO: remove this line after Chrome 50 has been released\n $template[0].$$parentNode = $template[0].parentNode;\n\n childTranscludeFn = compilationGenerator(mightHaveMultipleTransclusionError, $template, transcludeFn, terminalPriority,\n replaceDirective && replaceDirective.name, {\n // Don't pass in:\n // - controllerDirectives - otherwise we'll create duplicates controllers\n // - newIsolateScopeDirective or templateDirective - combining templates with\n // element transclusion doesn't make sense.\n //\n // We need only nonTlbTranscludeDirective so that we prevent putting transclusion\n // on the same element more than once.\n nonTlbTranscludeDirective: nonTlbTranscludeDirective\n });\n } else {\n\n var slots = createMap();\n\n if (!isObject(directiveValue)) {\n $template = jqLite(jqLiteClone(compileNode)).contents();\n } else {\n\n // We have transclusion slots,\n // collect them up, compile them and store their transclusion functions\n $template = [];\n\n var slotMap = createMap();\n var filledSlots = createMap();\n\n // Parse the element selectors\n forEach(directiveValue, function(elementSelector, slotName) {\n // If an element selector starts with a ? then it is optional\n var optional = (elementSelector.charAt(0) === '?');\n elementSelector = optional ? elementSelector.substring(1) : elementSelector;\n\n slotMap[elementSelector] = slotName;\n\n // We explicitly assign `null` since this implies that a slot was defined but not filled.\n // Later when calling boundTransclusion functions with a slot name we only error if the\n // slot is `undefined`\n slots[slotName] = null;\n\n // filledSlots contains `true` for all slots that are either optional or have been\n // filled. This is used to check that we have not missed any required slots\n filledSlots[slotName] = optional;\n });\n\n // Add the matching elements into their slot\n forEach($compileNode.contents(), function(node) {\n var slotName = slotMap[directiveNormalize(nodeName_(node))];\n if (slotName) {\n filledSlots[slotName] = true;\n slots[slotName] = slots[slotName] || [];\n slots[slotName].push(node);\n } else {\n $template.push(node);\n }\n });\n\n // Check for required slots that were not filled\n forEach(filledSlots, function(filled, slotName) {\n if (!filled) {\n throw $compileMinErr('reqslot', 'Required transclusion slot `{0}` was not filled.', slotName);\n }\n });\n\n for (var slotName in slots) {\n if (slots[slotName]) {\n // Only define a transclusion function if the slot was filled\n slots[slotName] = compilationGenerator(mightHaveMultipleTransclusionError, slots[slotName], transcludeFn);\n }\n }\n }\n\n $compileNode.empty(); // clear contents\n childTranscludeFn = compilationGenerator(mightHaveMultipleTransclusionError, $template, transcludeFn, undefined,\n undefined, { needsNewScope: directive.$$isolateScope || directive.$$newScope});\n childTranscludeFn.$$slots = slots;\n }\n }\n\n if (directive.template) {\n hasTemplate = true;\n assertNoDuplicate('template', templateDirective, directive, $compileNode);\n templateDirective = directive;\n\n directiveValue = (isFunction(directive.template))\n ? directive.template($compileNode, templateAttrs)\n : directive.template;\n\n directiveValue = denormalizeTemplate(directiveValue);\n\n if (directive.replace) {\n replaceDirective = directive;\n if (jqLiteIsTextNode(directiveValue)) {\n $template = [];\n } else {\n $template = removeComments(wrapTemplate(directive.templateNamespace, trim(directiveValue)));\n }\n compileNode = $template[0];\n\n if ($template.length !== 1 || compileNode.nodeType !== NODE_TYPE_ELEMENT) {\n throw $compileMinErr('tplrt',\n 'Template for directive \\'{0}\\' must have exactly one root element. {1}',\n directiveName, '');\n }\n\n replaceWith(jqCollection, $compileNode, compileNode);\n\n var newTemplateAttrs = {$attr: {}};\n\n // combine directives from the original node and from the template:\n // - take the array of directives for this element\n // - split it into two parts, those that already applied (processed) and those that weren't (unprocessed)\n // - collect directives from the template and sort them by priority\n // - combine directives as: processed + template + unprocessed\n var templateDirectives = collectDirectives(compileNode, [], newTemplateAttrs);\n var unprocessedDirectives = directives.splice(i + 1, directives.length - (i + 1));\n\n if (newIsolateScopeDirective || newScopeDirective) {\n // The original directive caused the current element to be replaced but this element\n // also needs to have a new scope, so we need to tell the template directives\n // that they would need to get their scope from further up, if they require transclusion\n markDirectiveScope(templateDirectives, newIsolateScopeDirective, newScopeDirective);\n }\n directives = directives.concat(templateDirectives).concat(unprocessedDirectives);\n mergeTemplateAttributes(templateAttrs, newTemplateAttrs);\n\n ii = directives.length;\n } else {\n $compileNode.html(directiveValue);\n }\n }\n\n if (directive.templateUrl) {\n hasTemplate = true;\n assertNoDuplicate('template', templateDirective, directive, $compileNode);\n templateDirective = directive;\n\n if (directive.replace) {\n replaceDirective = directive;\n }\n\n // eslint-disable-next-line no-func-assign\n nodeLinkFn = compileTemplateUrl(directives.splice(i, directives.length - i), $compileNode,\n templateAttrs, jqCollection, hasTranscludeDirective && childTranscludeFn, preLinkFns, postLinkFns, {\n controllerDirectives: controllerDirectives,\n newScopeDirective: (newScopeDirective !== directive) && newScopeDirective,\n newIsolateScopeDirective: newIsolateScopeDirective,\n templateDirective: templateDirective,\n nonTlbTranscludeDirective: nonTlbTranscludeDirective\n });\n ii = directives.length;\n } else if (directive.compile) {\n try {\n linkFn = directive.compile($compileNode, templateAttrs, childTranscludeFn);\n var context = directive.$$originalDirective || directive;\n if (isFunction(linkFn)) {\n addLinkFns(null, bind(context, linkFn), attrStart, attrEnd);\n } else if (linkFn) {\n addLinkFns(bind(context, linkFn.pre), bind(context, linkFn.post), attrStart, attrEnd);\n }\n } catch (e) {\n $exceptionHandler(e, startingTag($compileNode));\n }\n }\n\n if (directive.terminal) {\n nodeLinkFn.terminal = true;\n terminalPriority = Math.max(terminalPriority, directive.priority);\n }\n\n }\n\n nodeLinkFn.scope = newScopeDirective && newScopeDirective.scope === true;\n nodeLinkFn.transcludeOnThisElement = hasTranscludeDirective;\n nodeLinkFn.templateOnThisElement = hasTemplate;\n nodeLinkFn.transclude = childTranscludeFn;\n\n previousCompileContext.hasElementTranscludeDirective = hasElementTranscludeDirective;\n\n // might be normal or delayed nodeLinkFn depending on if templateUrl is present\n return nodeLinkFn;\n\n ////////////////////\n\n function addLinkFns(pre, post, attrStart, attrEnd) {\n if (pre) {\n if (attrStart) pre = groupElementsLinkFnWrapper(pre, attrStart, attrEnd);\n pre.require = directive.require;\n pre.directiveName = directiveName;\n if (newIsolateScopeDirective === directive || directive.$$isolateScope) {\n pre = cloneAndAnnotateFn(pre, {isolateScope: true});\n }\n preLinkFns.push(pre);\n }\n if (post) {\n if (attrStart) post = groupElementsLinkFnWrapper(post, attrStart, attrEnd);\n post.require = directive.require;\n post.directiveName = directiveName;\n if (newIsolateScopeDirective === directive || directive.$$isolateScope) {\n post = cloneAndAnnotateFn(post, {isolateScope: true});\n }\n postLinkFns.push(post);\n }\n }\n\n function nodeLinkFn(childLinkFn, scope, linkNode, $rootElement, boundTranscludeFn) {\n var i, ii, linkFn, isolateScope, controllerScope, elementControllers, transcludeFn, $element,\n attrs, scopeBindingInfo;\n\n if (compileNode === linkNode) {\n attrs = templateAttrs;\n $element = templateAttrs.$$element;\n } else {\n $element = jqLite(linkNode);\n attrs = new Attributes($element, templateAttrs);\n }\n\n controllerScope = scope;\n if (newIsolateScopeDirective) {\n isolateScope = scope.$new(true);\n } else if (newScopeDirective) {\n controllerScope = scope.$parent;\n }\n\n if (boundTranscludeFn) {\n // track `boundTranscludeFn` so it can be unwrapped if `transcludeFn`\n // is later passed as `parentBoundTranscludeFn` to `publicLinkFn`\n transcludeFn = controllersBoundTransclude;\n transcludeFn.$$boundTransclude = boundTranscludeFn;\n // expose the slots on the `$transclude` function\n transcludeFn.isSlotFilled = function(slotName) {\n return !!boundTranscludeFn.$$slots[slotName];\n };\n }\n\n if (controllerDirectives) {\n elementControllers = setupControllers($element, attrs, transcludeFn, controllerDirectives, isolateScope, scope, newIsolateScopeDirective);\n }\n\n if (newIsolateScopeDirective) {\n // Initialize isolate scope bindings for new isolate scope directive.\n compile.$$addScopeInfo($element, isolateScope, true, !(templateDirective && (templateDirective === newIsolateScopeDirective ||\n templateDirective === newIsolateScopeDirective.$$originalDirective)));\n compile.$$addScopeClass($element, true);\n isolateScope.$$isolateBindings =\n newIsolateScopeDirective.$$isolateBindings;\n scopeBindingInfo = initializeDirectiveBindings(scope, attrs, isolateScope,\n isolateScope.$$isolateBindings,\n newIsolateScopeDirective);\n if (scopeBindingInfo.removeWatches) {\n isolateScope.$on('$destroy', scopeBindingInfo.removeWatches);\n }\n }\n\n // Initialize bindToController bindings\n for (var name in elementControllers) {\n var controllerDirective = controllerDirectives[name];\n var controller = elementControllers[name];\n var bindings = controllerDirective.$$bindings.bindToController;\n\n if (preAssignBindingsEnabled) {\n if (bindings) {\n controller.bindingInfo =\n initializeDirectiveBindings(controllerScope, attrs, controller.instance, bindings, controllerDirective);\n } else {\n controller.bindingInfo = {};\n }\n\n var controllerResult = controller();\n if (controllerResult !== controller.instance) {\n // If the controller constructor has a return value, overwrite the instance\n // from setupControllers\n controller.instance = controllerResult;\n $element.data('$' + controllerDirective.name + 'Controller', controllerResult);\n if (controller.bindingInfo.removeWatches) {\n controller.bindingInfo.removeWatches();\n }\n controller.bindingInfo =\n initializeDirectiveBindings(controllerScope, attrs, controller.instance, bindings, controllerDirective);\n }\n } else {\n controller.instance = controller();\n $element.data('$' + controllerDirective.name + 'Controller', controller.instance);\n controller.bindingInfo =\n initializeDirectiveBindings(controllerScope, attrs, controller.instance, bindings, controllerDirective);\n }\n }\n\n // Bind the required controllers to the controller, if `require` is an object and `bindToController` is truthy\n forEach(controllerDirectives, function(controllerDirective, name) {\n var require = controllerDirective.require;\n if (controllerDirective.bindToController && !isArray(require) && isObject(require)) {\n extend(elementControllers[name].instance, getControllers(name, require, $element, elementControllers));\n }\n });\n\n // Handle the init and destroy lifecycle hooks on all controllers that have them\n forEach(elementControllers, function(controller) {\n var controllerInstance = controller.instance;\n if (isFunction(controllerInstance.$onChanges)) {\n try {\n controllerInstance.$onChanges(controller.bindingInfo.initialChanges);\n } catch (e) {\n $exceptionHandler(e);\n }\n }\n if (isFunction(controllerInstance.$onInit)) {\n try {\n controllerInstance.$onInit();\n } catch (e) {\n $exceptionHandler(e);\n }\n }\n if (isFunction(controllerInstance.$doCheck)) {\n controllerScope.$watch(function() { controllerInstance.$doCheck(); });\n controllerInstance.$doCheck();\n }\n if (isFunction(controllerInstance.$onDestroy)) {\n controllerScope.$on('$destroy', function callOnDestroyHook() {\n controllerInstance.$onDestroy();\n });\n }\n });\n\n // PRELINKING\n for (i = 0, ii = preLinkFns.length; i < ii; i++) {\n linkFn = preLinkFns[i];\n invokeLinkFn(linkFn,\n linkFn.isolateScope ? isolateScope : scope,\n $element,\n attrs,\n linkFn.require && getControllers(linkFn.directiveName, linkFn.require, $element, elementControllers),\n transcludeFn\n );\n }\n\n // RECURSION\n // We only pass the isolate scope, if the isolate directive has a template,\n // otherwise the child elements do not belong to the isolate directive.\n var scopeToChild = scope;\n if (newIsolateScopeDirective && (newIsolateScopeDirective.template || newIsolateScopeDirective.templateUrl === null)) {\n scopeToChild = isolateScope;\n }\n if (childLinkFn) {\n childLinkFn(scopeToChild, linkNode.childNodes, undefined, boundTranscludeFn);\n }\n\n // POSTLINKING\n for (i = postLinkFns.length - 1; i >= 0; i--) {\n linkFn = postLinkFns[i];\n invokeLinkFn(linkFn,\n linkFn.isolateScope ? isolateScope : scope,\n $element,\n attrs,\n linkFn.require && getControllers(linkFn.directiveName, linkFn.require, $element, elementControllers),\n transcludeFn\n );\n }\n\n // Trigger $postLink lifecycle hooks\n forEach(elementControllers, function(controller) {\n var controllerInstance = controller.instance;\n if (isFunction(controllerInstance.$postLink)) {\n controllerInstance.$postLink();\n }\n });\n\n // This is the function that is injected as `$transclude`.\n // Note: all arguments are optional!\n function controllersBoundTransclude(scope, cloneAttachFn, futureParentElement, slotName) {\n var transcludeControllers;\n // No scope passed in:\n if (!isScope(scope)) {\n slotName = futureParentElement;\n futureParentElement = cloneAttachFn;\n cloneAttachFn = scope;\n scope = undefined;\n }\n\n if (hasElementTranscludeDirective) {\n transcludeControllers = elementControllers;\n }\n if (!futureParentElement) {\n futureParentElement = hasElementTranscludeDirective ? $element.parent() : $element;\n }\n if (slotName) {\n // slotTranscludeFn can be one of three things:\n // * a transclude function - a filled slot\n // * `null` - an optional slot that was not filled\n // * `undefined` - a slot that was not declared (i.e. invalid)\n var slotTranscludeFn = boundTranscludeFn.$$slots[slotName];\n if (slotTranscludeFn) {\n return slotTranscludeFn(scope, cloneAttachFn, transcludeControllers, futureParentElement, scopeToChild);\n } else if (isUndefined(slotTranscludeFn)) {\n throw $compileMinErr('noslot',\n 'No parent directive that requires a transclusion with slot name \"{0}\". ' +\n 'Element: {1}',\n slotName, startingTag($element));\n }\n } else {\n return boundTranscludeFn(scope, cloneAttachFn, transcludeControllers, futureParentElement, scopeToChild);\n }\n }\n }\n }\n\n function getControllers(directiveName, require, $element, elementControllers) {\n var value;\n\n if (isString(require)) {\n var match = require.match(REQUIRE_PREFIX_REGEXP);\n var name = require.substring(match[0].length);\n var inheritType = match[1] || match[3];\n var optional = match[2] === '?';\n\n //If only parents then start at the parent element\n if (inheritType === '^^') {\n $element = $element.parent();\n //Otherwise attempt getting the controller from elementControllers in case\n //the element is transcluded (and has no data) and to avoid .data if possible\n } else {\n value = elementControllers && elementControllers[name];\n value = value && value.instance;\n }\n\n if (!value) {\n var dataName = '$' + name + 'Controller';\n value = inheritType ? $element.inheritedData(dataName) : $element.data(dataName);\n }\n\n if (!value && !optional) {\n throw $compileMinErr('ctreq',\n 'Controller \\'{0}\\', required by directive \\'{1}\\', can\\'t be found!',\n name, directiveName);\n }\n } else if (isArray(require)) {\n value = [];\n for (var i = 0, ii = require.length; i < ii; i++) {\n value[i] = getControllers(directiveName, require[i], $element, elementControllers);\n }\n } else if (isObject(require)) {\n value = {};\n forEach(require, function(controller, property) {\n value[property] = getControllers(directiveName, controller, $element, elementControllers);\n });\n }\n\n return value || null;\n }\n\n function setupControllers($element, attrs, transcludeFn, controllerDirectives, isolateScope, scope, newIsolateScopeDirective) {\n var elementControllers = createMap();\n for (var controllerKey in controllerDirectives) {\n var directive = controllerDirectives[controllerKey];\n var locals = {\n $scope: directive === newIsolateScopeDirective || directive.$$isolateScope ? isolateScope : scope,\n $element: $element,\n $attrs: attrs,\n $transclude: transcludeFn\n };\n\n var controller = directive.controller;\n if (controller === '@') {\n controller = attrs[directive.name];\n }\n\n var controllerInstance = $controller(controller, locals, true, directive.controllerAs);\n\n // For directives with element transclusion the element is a comment.\n // In this case .data will not attach any data.\n // Instead, we save the controllers for the element in a local hash and attach to .data\n // later, once we have the actual element.\n elementControllers[directive.name] = controllerInstance;\n $element.data('$' + directive.name + 'Controller', controllerInstance.instance);\n }\n return elementControllers;\n }\n\n // Depending upon the context in which a directive finds itself it might need to have a new isolated\n // or child scope created. For instance:\n // * if the directive has been pulled into a template because another directive with a higher priority\n // asked for element transclusion\n // * if the directive itself asks for transclusion but it is at the root of a template and the original\n // element was replaced. See https://github.com/angular/angular.js/issues/12936\n function markDirectiveScope(directives, isolateScope, newScope) {\n for (var j = 0, jj = directives.length; j < jj; j++) {\n directives[j] = inherit(directives[j], {$$isolateScope: isolateScope, $$newScope: newScope});\n }\n }\n\n /**\n * looks up the directive and decorates it with exception handling and proper parameters. We\n * call this the boundDirective.\n *\n * @param {string} name name of the directive to look up.\n * @param {string} location The directive must be found in specific format.\n * String containing any of theses characters:\n *\n * * `E`: element name\n * * `A': attribute\n * * `C`: class\n * * `M`: comment\n * @returns {boolean} true if directive was added.\n */\n function addDirective(tDirectives, name, location, maxPriority, ignoreDirective, startAttrName,\n endAttrName) {\n if (name === ignoreDirective) return null;\n var match = null;\n if (hasDirectives.hasOwnProperty(name)) {\n for (var directive, directives = $injector.get(name + Suffix),\n i = 0, ii = directives.length; i < ii; i++) {\n directive = directives[i];\n if ((isUndefined(maxPriority) || maxPriority > directive.priority) &&\n directive.restrict.indexOf(location) !== -1) {\n if (startAttrName) {\n directive = inherit(directive, {$$start: startAttrName, $$end: endAttrName});\n }\n if (!directive.$$bindings) {\n var bindings = directive.$$bindings =\n parseDirectiveBindings(directive, directive.name);\n if (isObject(bindings.isolateScope)) {\n directive.$$isolateBindings = bindings.isolateScope;\n }\n }\n tDirectives.push(directive);\n match = directive;\n }\n }\n }\n return match;\n }\n\n\n /**\n * looks up the directive and returns true if it is a multi-element directive,\n * and therefore requires DOM nodes between -start and -end markers to be grouped\n * together.\n *\n * @param {string} name name of the directive to look up.\n * @returns true if directive was registered as multi-element.\n */\n function directiveIsMultiElement(name) {\n if (hasDirectives.hasOwnProperty(name)) {\n for (var directive, directives = $injector.get(name + Suffix),\n i = 0, ii = directives.length; i < ii; i++) {\n directive = directives[i];\n if (directive.multiElement) {\n return true;\n }\n }\n }\n return false;\n }\n\n /**\n * When the element is replaced with HTML template then the new attributes\n * on the template need to be merged with the existing attributes in the DOM.\n * The desired effect is to have both of the attributes present.\n *\n * @param {object} dst destination attributes (original DOM)\n * @param {object} src source attributes (from the directive template)\n */\n function mergeTemplateAttributes(dst, src) {\n var srcAttr = src.$attr,\n dstAttr = dst.$attr;\n\n // reapply the old attributes to the new element\n forEach(dst, function(value, key) {\n if (key.charAt(0) !== '$') {\n if (src[key] && src[key] !== value) {\n if (value.length) {\n value += (key === 'style' ? ';' : ' ') + src[key];\n } else {\n value = src[key];\n }\n }\n dst.$set(key, value, true, srcAttr[key]);\n }\n });\n\n // copy the new attributes on the old attrs object\n forEach(src, function(value, key) {\n // Check if we already set this attribute in the loop above.\n // `dst` will never contain hasOwnProperty as DOM parser won't let it.\n // You will get an \"InvalidCharacterError: DOM Exception 5\" error if you\n // have an attribute like \"has-own-property\" or \"data-has-own-property\", etc.\n if (!dst.hasOwnProperty(key) && key.charAt(0) !== '$') {\n dst[key] = value;\n\n if (key !== 'class' && key !== 'style') {\n dstAttr[key] = srcAttr[key];\n }\n }\n });\n }\n\n\n function compileTemplateUrl(directives, $compileNode, tAttrs,\n $rootElement, childTranscludeFn, preLinkFns, postLinkFns, previousCompileContext) {\n var linkQueue = [],\n afterTemplateNodeLinkFn,\n afterTemplateChildLinkFn,\n beforeTemplateCompileNode = $compileNode[0],\n origAsyncDirective = directives.shift(),\n derivedSyncDirective = inherit(origAsyncDirective, {\n templateUrl: null, transclude: null, replace: null, $$originalDirective: origAsyncDirective\n }),\n templateUrl = (isFunction(origAsyncDirective.templateUrl))\n ? origAsyncDirective.templateUrl($compileNode, tAttrs)\n : origAsyncDirective.templateUrl,\n templateNamespace = origAsyncDirective.templateNamespace;\n\n $compileNode.empty();\n\n $templateRequest(templateUrl)\n .then(function(content) {\n var compileNode, tempTemplateAttrs, $template, childBoundTranscludeFn;\n\n content = denormalizeTemplate(content);\n\n if (origAsyncDirective.replace) {\n if (jqLiteIsTextNode(content)) {\n $template = [];\n } else {\n $template = removeComments(wrapTemplate(templateNamespace, trim(content)));\n }\n compileNode = $template[0];\n\n if ($template.length !== 1 || compileNode.nodeType !== NODE_TYPE_ELEMENT) {\n throw $compileMinErr('tplrt',\n 'Template for directive \\'{0}\\' must have exactly one root element. {1}',\n origAsyncDirective.name, templateUrl);\n }\n\n tempTemplateAttrs = {$attr: {}};\n replaceWith($rootElement, $compileNode, compileNode);\n var templateDirectives = collectDirectives(compileNode, [], tempTemplateAttrs);\n\n if (isObject(origAsyncDirective.scope)) {\n // the original directive that caused the template to be loaded async required\n // an isolate scope\n markDirectiveScope(templateDirectives, true);\n }\n directives = templateDirectives.concat(directives);\n mergeTemplateAttributes(tAttrs, tempTemplateAttrs);\n } else {\n compileNode = beforeTemplateCompileNode;\n $compileNode.html(content);\n }\n\n directives.unshift(derivedSyncDirective);\n\n afterTemplateNodeLinkFn = applyDirectivesToNode(directives, compileNode, tAttrs,\n childTranscludeFn, $compileNode, origAsyncDirective, preLinkFns, postLinkFns,\n previousCompileContext);\n forEach($rootElement, function(node, i) {\n if (node === compileNode) {\n $rootElement[i] = $compileNode[0];\n }\n });\n afterTemplateChildLinkFn = compileNodes($compileNode[0].childNodes, childTranscludeFn);\n\n while (linkQueue.length) {\n var scope = linkQueue.shift(),\n beforeTemplateLinkNode = linkQueue.shift(),\n linkRootElement = linkQueue.shift(),\n boundTranscludeFn = linkQueue.shift(),\n linkNode = $compileNode[0];\n\n if (scope.$$destroyed) continue;\n\n if (beforeTemplateLinkNode !== beforeTemplateCompileNode) {\n var oldClasses = beforeTemplateLinkNode.className;\n\n if (!(previousCompileContext.hasElementTranscludeDirective &&\n origAsyncDirective.replace)) {\n // it was cloned therefore we have to clone as well.\n linkNode = jqLiteClone(compileNode);\n }\n replaceWith(linkRootElement, jqLite(beforeTemplateLinkNode), linkNode);\n\n // Copy in CSS classes from original node\n safeAddClass(jqLite(linkNode), oldClasses);\n }\n if (afterTemplateNodeLinkFn.transcludeOnThisElement) {\n childBoundTranscludeFn = createBoundTranscludeFn(scope, afterTemplateNodeLinkFn.transclude, boundTranscludeFn);\n } else {\n childBoundTranscludeFn = boundTranscludeFn;\n }\n afterTemplateNodeLinkFn(afterTemplateChildLinkFn, scope, linkNode, $rootElement,\n childBoundTranscludeFn);\n }\n linkQueue = null;\n }).catch(function(error) {\n if (error instanceof Error) {\n $exceptionHandler(error);\n }\n }).catch(noop);\n\n return function delayedNodeLinkFn(ignoreChildLinkFn, scope, node, rootElement, boundTranscludeFn) {\n var childBoundTranscludeFn = boundTranscludeFn;\n if (scope.$$destroyed) return;\n if (linkQueue) {\n linkQueue.push(scope,\n node,\n rootElement,\n childBoundTranscludeFn);\n } else {\n if (afterTemplateNodeLinkFn.transcludeOnThisElement) {\n childBoundTranscludeFn = createBoundTranscludeFn(scope, afterTemplateNodeLinkFn.transclude, boundTranscludeFn);\n }\n afterTemplateNodeLinkFn(afterTemplateChildLinkFn, scope, node, rootElement, childBoundTranscludeFn);\n }\n };\n }\n\n\n /**\n * Sorting function for bound directives.\n */\n function byPriority(a, b) {\n var diff = b.priority - a.priority;\n if (diff !== 0) return diff;\n if (a.name !== b.name) return (a.name < b.name) ? -1 : 1;\n return a.index - b.index;\n }\n\n function assertNoDuplicate(what, previousDirective, directive, element) {\n\n function wrapModuleNameIfDefined(moduleName) {\n return moduleName ?\n (' (module: ' + moduleName + ')') :\n '';\n }\n\n if (previousDirective) {\n throw $compileMinErr('multidir', 'Multiple directives [{0}{1}, {2}{3}] asking for {4} on: {5}',\n previousDirective.name, wrapModuleNameIfDefined(previousDirective.$$moduleName),\n directive.name, wrapModuleNameIfDefined(directive.$$moduleName), what, startingTag(element));\n }\n }\n\n\n function addTextInterpolateDirective(directives, text) {\n var interpolateFn = $interpolate(text, true);\n if (interpolateFn) {\n directives.push({\n priority: 0,\n compile: function textInterpolateCompileFn(templateNode) {\n var templateNodeParent = templateNode.parent(),\n hasCompileParent = !!templateNodeParent.length;\n\n // When transcluding a template that has bindings in the root\n // we don't have a parent and thus need to add the class during linking fn.\n if (hasCompileParent) compile.$$addBindingClass(templateNodeParent);\n\n return function textInterpolateLinkFn(scope, node) {\n var parent = node.parent();\n if (!hasCompileParent) compile.$$addBindingClass(parent);\n compile.$$addBindingInfo(parent, interpolateFn.expressions);\n scope.$watch(interpolateFn, function interpolateFnWatchAction(value) {\n node[0].nodeValue = value;\n });\n };\n }\n });\n }\n }\n\n\n function wrapTemplate(type, template) {\n type = lowercase(type || 'html');\n switch (type) {\n case 'svg':\n case 'math':\n var wrapper = window.document.createElement('div');\n wrapper.innerHTML = '<' + type + '>' + template + '';\n return wrapper.childNodes[0].childNodes;\n default:\n return template;\n }\n }\n\n\n function getTrustedContext(node, attrNormalizedName) {\n if (attrNormalizedName === 'srcdoc') {\n return $sce.HTML;\n }\n var tag = nodeName_(node);\n // All tags with src attributes require a RESOURCE_URL value, except for\n // img and various html5 media tags.\n if (attrNormalizedName === 'src' || attrNormalizedName === 'ngSrc') {\n if (['img', 'video', 'audio', 'source', 'track'].indexOf(tag) === -1) {\n return $sce.RESOURCE_URL;\n }\n // maction[xlink:href] can source SVG. It's not limited to .\n } else if (attrNormalizedName === 'xlinkHref' ||\n (tag === 'form' && attrNormalizedName === 'action') ||\n // links can be stylesheets or imports, which can run script in the current origin\n (tag === 'link' && attrNormalizedName === 'href')\n ) {\n return $sce.RESOURCE_URL;\n }\n }\n\n\n function addAttrInterpolateDirective(node, directives, value, name, isNgAttr) {\n var trustedContext = getTrustedContext(node, name);\n var mustHaveExpression = !isNgAttr;\n var allOrNothing = ALL_OR_NOTHING_ATTRS[name] || isNgAttr;\n\n var interpolateFn = $interpolate(value, mustHaveExpression, trustedContext, allOrNothing);\n\n // no interpolation found -> ignore\n if (!interpolateFn) return;\n\n if (name === 'multiple' && nodeName_(node) === 'select') {\n throw $compileMinErr('selmulti',\n 'Binding to the \\'multiple\\' attribute is not supported. Element: {0}',\n startingTag(node));\n }\n\n if (EVENT_HANDLER_ATTR_REGEXP.test(name)) {\n throw $compileMinErr('nodomevents',\n 'Interpolations for HTML DOM event attributes are disallowed. Please use the ' +\n 'ng- versions (such as ng-click instead of onclick) instead.');\n }\n\n directives.push({\n priority: 100,\n compile: function() {\n return {\n pre: function attrInterpolatePreLinkFn(scope, element, attr) {\n var $$observers = (attr.$$observers || (attr.$$observers = createMap()));\n\n // If the attribute has changed since last $interpolate()ed\n var newValue = attr[name];\n if (newValue !== value) {\n // we need to interpolate again since the attribute value has been updated\n // (e.g. by another directive's compile function)\n // ensure unset/empty values make interpolateFn falsy\n interpolateFn = newValue && $interpolate(newValue, true, trustedContext, allOrNothing);\n value = newValue;\n }\n\n // if attribute was updated so that there is no interpolation going on we don't want to\n // register any observers\n if (!interpolateFn) return;\n\n // initialize attr object so that it's ready in case we need the value for isolate\n // scope initialization, otherwise the value would not be available from isolate\n // directive's linking fn during linking phase\n attr[name] = interpolateFn(scope);\n\n ($$observers[name] || ($$observers[name] = [])).$$inter = true;\n (attr.$$observers && attr.$$observers[name].$$scope || scope).\n $watch(interpolateFn, function interpolateFnWatchAction(newValue, oldValue) {\n //special case for class attribute addition + removal\n //so that class changes can tap into the animation\n //hooks provided by the $animate service. Be sure to\n //skip animations when the first digest occurs (when\n //both the new and the old values are the same) since\n //the CSS classes are the non-interpolated values\n if (name === 'class' && newValue !== oldValue) {\n attr.$updateClass(newValue, oldValue);\n } else {\n attr.$set(name, newValue);\n }\n });\n }\n };\n }\n });\n }\n\n\n /**\n * This is a special jqLite.replaceWith, which can replace items which\n * have no parents, provided that the containing jqLite collection is provided.\n *\n * @param {JqLite=} $rootElement The root of the compile tree. Used so that we can replace nodes\n * in the root of the tree.\n * @param {JqLite} elementsToRemove The jqLite element which we are going to replace. We keep\n * the shell, but replace its DOM node reference.\n * @param {Node} newNode The new DOM node.\n */\n function replaceWith($rootElement, elementsToRemove, newNode) {\n var firstElementToRemove = elementsToRemove[0],\n removeCount = elementsToRemove.length,\n parent = firstElementToRemove.parentNode,\n i, ii;\n\n if ($rootElement) {\n for (i = 0, ii = $rootElement.length; i < ii; i++) {\n if ($rootElement[i] === firstElementToRemove) {\n $rootElement[i++] = newNode;\n for (var j = i, j2 = j + removeCount - 1,\n jj = $rootElement.length;\n j < jj; j++, j2++) {\n if (j2 < jj) {\n $rootElement[j] = $rootElement[j2];\n } else {\n delete $rootElement[j];\n }\n }\n $rootElement.length -= removeCount - 1;\n\n // If the replaced element is also the jQuery .context then replace it\n // .context is a deprecated jQuery api, so we should set it only when jQuery set it\n // http://api.jquery.com/context/\n if ($rootElement.context === firstElementToRemove) {\n $rootElement.context = newNode;\n }\n break;\n }\n }\n }\n\n if (parent) {\n parent.replaceChild(newNode, firstElementToRemove);\n }\n\n // Append all the `elementsToRemove` to a fragment. This will...\n // - remove them from the DOM\n // - allow them to still be traversed with .nextSibling\n // - allow a single fragment.qSA to fetch all elements being removed\n var fragment = window.document.createDocumentFragment();\n for (i = 0; i < removeCount; i++) {\n fragment.appendChild(elementsToRemove[i]);\n }\n\n if (jqLite.hasData(firstElementToRemove)) {\n // Copy over user data (that includes Angular's $scope etc.). Don't copy private\n // data here because there's no public interface in jQuery to do that and copying over\n // event listeners (which is the main use of private data) wouldn't work anyway.\n jqLite.data(newNode, jqLite.data(firstElementToRemove));\n\n // Remove $destroy event listeners from `firstElementToRemove`\n jqLite(firstElementToRemove).off('$destroy');\n }\n\n // Cleanup any data/listeners on the elements and children.\n // This includes invoking the $destroy event on any elements with listeners.\n jqLite.cleanData(fragment.querySelectorAll('*'));\n\n // Update the jqLite collection to only contain the `newNode`\n for (i = 1; i < removeCount; i++) {\n delete elementsToRemove[i];\n }\n elementsToRemove[0] = newNode;\n elementsToRemove.length = 1;\n }\n\n\n function cloneAndAnnotateFn(fn, annotation) {\n return extend(function() { return fn.apply(null, arguments); }, fn, annotation);\n }\n\n\n function invokeLinkFn(linkFn, scope, $element, attrs, controllers, transcludeFn) {\n try {\n linkFn(scope, $element, attrs, controllers, transcludeFn);\n } catch (e) {\n $exceptionHandler(e, startingTag($element));\n }\n }\n\n\n // Set up $watches for isolate scope and controller bindings.\n function initializeDirectiveBindings(scope, attrs, destination, bindings, directive) {\n var removeWatchCollection = [];\n var initialChanges = {};\n var changes;\n forEach(bindings, function initializeBinding(definition, scopeName) {\n var attrName = definition.attrName,\n optional = definition.optional,\n mode = definition.mode, // @, =, <, or &\n lastValue,\n parentGet, parentSet, compare, removeWatch;\n\n switch (mode) {\n\n case '@':\n if (!optional && !hasOwnProperty.call(attrs, attrName)) {\n destination[scopeName] = attrs[attrName] = undefined;\n }\n removeWatch = attrs.$observe(attrName, function(value) {\n if (isString(value) || isBoolean(value)) {\n var oldValue = destination[scopeName];\n recordChanges(scopeName, value, oldValue);\n destination[scopeName] = value;\n }\n });\n attrs.$$observers[attrName].$$scope = scope;\n lastValue = attrs[attrName];\n if (isString(lastValue)) {\n // If the attribute has been provided then we trigger an interpolation to ensure\n // the value is there for use in the link fn\n destination[scopeName] = $interpolate(lastValue)(scope);\n } else if (isBoolean(lastValue)) {\n // If the attributes is one of the BOOLEAN_ATTR then Angular will have converted\n // the value to boolean rather than a string, so we special case this situation\n destination[scopeName] = lastValue;\n }\n initialChanges[scopeName] = new SimpleChange(_UNINITIALIZED_VALUE, destination[scopeName]);\n removeWatchCollection.push(removeWatch);\n break;\n\n case '=':\n if (!hasOwnProperty.call(attrs, attrName)) {\n if (optional) break;\n attrs[attrName] = undefined;\n }\n if (optional && !attrs[attrName]) break;\n\n parentGet = $parse(attrs[attrName]);\n if (parentGet.literal) {\n compare = equals;\n } else {\n // eslint-disable-next-line no-self-compare\n compare = function simpleCompare(a, b) { return a === b || (a !== a && b !== b); };\n }\n parentSet = parentGet.assign || function() {\n // reset the change, or we will throw this exception on every $digest\n lastValue = destination[scopeName] = parentGet(scope);\n throw $compileMinErr('nonassign',\n 'Expression \\'{0}\\' in attribute \\'{1}\\' used with directive \\'{2}\\' is non-assignable!',\n attrs[attrName], attrName, directive.name);\n };\n lastValue = destination[scopeName] = parentGet(scope);\n var parentValueWatch = function parentValueWatch(parentValue) {\n if (!compare(parentValue, destination[scopeName])) {\n // we are out of sync and need to copy\n if (!compare(parentValue, lastValue)) {\n // parent changed and it has precedence\n destination[scopeName] = parentValue;\n } else {\n // if the parent can be assigned then do so\n parentSet(scope, parentValue = destination[scopeName]);\n }\n }\n lastValue = parentValue;\n return lastValue;\n };\n parentValueWatch.$stateful = true;\n if (definition.collection) {\n removeWatch = scope.$watchCollection(attrs[attrName], parentValueWatch);\n } else {\n removeWatch = scope.$watch($parse(attrs[attrName], parentValueWatch), null, parentGet.literal);\n }\n removeWatchCollection.push(removeWatch);\n break;\n\n case '<':\n if (!hasOwnProperty.call(attrs, attrName)) {\n if (optional) break;\n attrs[attrName] = undefined;\n }\n if (optional && !attrs[attrName]) break;\n\n parentGet = $parse(attrs[attrName]);\n var deepWatch = parentGet.literal;\n\n var initialValue = destination[scopeName] = parentGet(scope);\n initialChanges[scopeName] = new SimpleChange(_UNINITIALIZED_VALUE, destination[scopeName]);\n\n removeWatch = scope.$watch(parentGet, function parentValueWatchAction(newValue, oldValue) {\n if (oldValue === newValue) {\n if (oldValue === initialValue || (deepWatch && equals(oldValue, initialValue))) {\n return;\n }\n oldValue = initialValue;\n }\n recordChanges(scopeName, newValue, oldValue);\n destination[scopeName] = newValue;\n }, deepWatch);\n\n removeWatchCollection.push(removeWatch);\n break;\n\n case '&':\n // Don't assign Object.prototype method to scope\n parentGet = attrs.hasOwnProperty(attrName) ? $parse(attrs[attrName]) : noop;\n\n // Don't assign noop to destination if expression is not valid\n if (parentGet === noop && optional) break;\n\n destination[scopeName] = function(locals) {\n return parentGet(scope, locals);\n };\n break;\n }\n });\n\n function recordChanges(key, currentValue, previousValue) {\n if (isFunction(destination.$onChanges) && currentValue !== previousValue &&\n // eslint-disable-next-line no-self-compare\n (currentValue === currentValue || previousValue === previousValue)) {\n // If we have not already scheduled the top level onChangesQueue handler then do so now\n if (!onChangesQueue) {\n scope.$$postDigest(flushOnChangesQueue);\n onChangesQueue = [];\n }\n // If we have not already queued a trigger of onChanges for this controller then do so now\n if (!changes) {\n changes = {};\n onChangesQueue.push(triggerOnChangesHook);\n }\n // If the has been a change on this property already then we need to reuse the previous value\n if (changes[key]) {\n previousValue = changes[key].previousValue;\n }\n // Store this change\n changes[key] = new SimpleChange(previousValue, currentValue);\n }\n }\n\n function triggerOnChangesHook() {\n destination.$onChanges(changes);\n // Now clear the changes so that we schedule onChanges when more changes arrive\n changes = undefined;\n }\n\n return {\n initialChanges: initialChanges,\n removeWatches: removeWatchCollection.length && function removeWatches() {\n for (var i = 0, ii = removeWatchCollection.length; i < ii; ++i) {\n removeWatchCollection[i]();\n }\n }\n };\n }\n }];\n}\n\nfunction SimpleChange(previous, current) {\n this.previousValue = previous;\n this.currentValue = current;\n}\nSimpleChange.prototype.isFirstChange = function() { return this.previousValue === _UNINITIALIZED_VALUE; };\n\n\nvar PREFIX_REGEXP = /^((?:x|data)[:\\-_])/i;\nvar SPECIAL_CHARS_REGEXP = /[:\\-_]+(.)/g;\n\n/**\n * Converts all accepted directives format into proper directive name.\n * @param name Name to normalize\n */\nfunction directiveNormalize(name) {\n return name\n .replace(PREFIX_REGEXP, '')\n .replace(SPECIAL_CHARS_REGEXP, fnCamelCaseReplace);\n}\n\n/**\n * @ngdoc type\n * @name $compile.directive.Attributes\n *\n * @description\n * A shared object between directive compile / linking functions which contains normalized DOM\n * element attributes. The values reflect current binding state `{{ }}`. The normalization is\n * needed since all of these are treated as equivalent in Angular:\n *\n * ```\n * \n * ```\n */\n\n/**\n * @ngdoc property\n * @name $compile.directive.Attributes#$attr\n *\n * @description\n * A map of DOM element attribute names to the normalized name. This is\n * needed to do reverse lookup from normalized name back to actual name.\n */\n\n\n/**\n * @ngdoc method\n * @name $compile.directive.Attributes#$set\n * @kind function\n *\n * @description\n * Set DOM element attribute value.\n *\n *\n * @param {string} name Normalized element attribute name of the property to modify. The name is\n * reverse-translated using the {@link ng.$compile.directive.Attributes#$attr $attr}\n * property to the original name.\n * @param {string} value Value to set the attribute to. The value can be an interpolated string.\n */\n\n\n\n/**\n * Closure compiler type information\n */\n\nfunction nodesetLinkingFn(\n /* angular.Scope */ scope,\n /* NodeList */ nodeList,\n /* Element */ rootElement,\n /* function(Function) */ boundTranscludeFn\n) {}\n\nfunction directiveLinkingFn(\n /* nodesetLinkingFn */ nodesetLinkingFn,\n /* angular.Scope */ scope,\n /* Node */ node,\n /* Element */ rootElement,\n /* function(Function) */ boundTranscludeFn\n) {}\n\nfunction tokenDifference(str1, str2) {\n var values = '',\n tokens1 = str1.split(/\\s+/),\n tokens2 = str2.split(/\\s+/);\n\n outer:\n for (var i = 0; i < tokens1.length; i++) {\n var token = tokens1[i];\n for (var j = 0; j < tokens2.length; j++) {\n if (token === tokens2[j]) continue outer;\n }\n values += (values.length > 0 ? ' ' : '') + token;\n }\n return values;\n}\n\nfunction removeComments(jqNodes) {\n jqNodes = jqLite(jqNodes);\n var i = jqNodes.length;\n\n if (i <= 1) {\n return jqNodes;\n }\n\n while (i--) {\n var node = jqNodes[i];\n if (node.nodeType === NODE_TYPE_COMMENT ||\n (node.nodeType === NODE_TYPE_TEXT && node.nodeValue.trim() === '')) {\n splice.call(jqNodes, i, 1);\n }\n }\n return jqNodes;\n}\n\nvar $controllerMinErr = minErr('$controller');\n\n\nvar CNTRL_REG = /^(\\S+)(\\s+as\\s+([\\w$]+))?$/;\nfunction identifierForController(controller, ident) {\n if (ident && isString(ident)) return ident;\n if (isString(controller)) {\n var match = CNTRL_REG.exec(controller);\n if (match) return match[3];\n }\n}\n\n\n/**\n * @ngdoc provider\n * @name $controllerProvider\n * @this\n *\n * @description\n * The {@link ng.$controller $controller service} is used by Angular to create new\n * controllers.\n *\n * This provider allows controller registration via the\n * {@link ng.$controllerProvider#register register} method.\n */\nfunction $ControllerProvider() {\n var controllers = {},\n globals = false;\n\n /**\n * @ngdoc method\n * @name $controllerProvider#has\n * @param {string} name Controller name to check.\n */\n this.has = function(name) {\n return controllers.hasOwnProperty(name);\n };\n\n /**\n * @ngdoc method\n * @name $controllerProvider#register\n * @param {string|Object} name Controller name, or an object map of controllers where the keys are\n * the names and the values are the constructors.\n * @param {Function|Array} constructor Controller constructor fn (optionally decorated with DI\n * annotations in the array notation).\n */\n this.register = function(name, constructor) {\n assertNotHasOwnProperty(name, 'controller');\n if (isObject(name)) {\n extend(controllers, name);\n } else {\n controllers[name] = constructor;\n }\n };\n\n /**\n * @ngdoc method\n * @name $controllerProvider#allowGlobals\n * @description If called, allows `$controller` to find controller constructors on `window`\n *\n * @deprecated\n * sinceVersion=\"v1.3.0\"\n * removeVersion=\"v1.7.0\"\n * This method of finding controllers has been deprecated.\n */\n this.allowGlobals = function() {\n globals = true;\n };\n\n\n this.$get = ['$injector', '$window', function($injector, $window) {\n\n /**\n * @ngdoc service\n * @name $controller\n * @requires $injector\n *\n * @param {Function|string} constructor If called with a function then it's considered to be the\n * controller constructor function. Otherwise it's considered to be a string which is used\n * to retrieve the controller constructor using the following steps:\n *\n * * check if a controller with given name is registered via `$controllerProvider`\n * * check if evaluating the string on the current scope returns a constructor\n * * if $controllerProvider#allowGlobals, check `window[constructor]` on the global\n * `window` object (deprecated, not recommended)\n *\n * The string can use the `controller as property` syntax, where the controller instance is published\n * as the specified property on the `scope`; the `scope` must be injected into `locals` param for this\n * to work correctly.\n *\n * @param {Object} locals Injection locals for Controller.\n * @return {Object} Instance of given controller.\n *\n * @description\n * `$controller` service is responsible for instantiating controllers.\n *\n * It's just a simple call to {@link auto.$injector $injector}, but extracted into\n * a service, so that one can override this service with [BC version](https://gist.github.com/1649788).\n */\n return function $controller(expression, locals, later, ident) {\n // PRIVATE API:\n // param `later` --- indicates that the controller's constructor is invoked at a later time.\n // If true, $controller will allocate the object with the correct\n // prototype chain, but will not invoke the controller until a returned\n // callback is invoked.\n // param `ident` --- An optional label which overrides the label parsed from the controller\n // expression, if any.\n var instance, match, constructor, identifier;\n later = later === true;\n if (ident && isString(ident)) {\n identifier = ident;\n }\n\n if (isString(expression)) {\n match = expression.match(CNTRL_REG);\n if (!match) {\n throw $controllerMinErr('ctrlfmt',\n 'Badly formed controller string \\'{0}\\'. ' +\n 'Must match `__name__ as __id__` or `__name__`.', expression);\n }\n constructor = match[1];\n identifier = identifier || match[3];\n expression = controllers.hasOwnProperty(constructor)\n ? controllers[constructor]\n : getter(locals.$scope, constructor, true) ||\n (globals ? getter($window, constructor, true) : undefined);\n\n if (!expression) {\n throw $controllerMinErr('ctrlreg',\n 'The controller with the name \\'{0}\\' is not registered.', constructor);\n }\n\n assertArgFn(expression, constructor, true);\n }\n\n if (later) {\n // Instantiate controller later:\n // This machinery is used to create an instance of the object before calling the\n // controller's constructor itself.\n //\n // This allows properties to be added to the controller before the constructor is\n // invoked. Primarily, this is used for isolate scope bindings in $compile.\n //\n // This feature is not intended for use by applications, and is thus not documented\n // publicly.\n // Object creation: http://jsperf.com/create-constructor/2\n var controllerPrototype = (isArray(expression) ?\n expression[expression.length - 1] : expression).prototype;\n instance = Object.create(controllerPrototype || null);\n\n if (identifier) {\n addIdentifier(locals, identifier, instance, constructor || expression.name);\n }\n\n return extend(function $controllerInit() {\n var result = $injector.invoke(expression, instance, locals, constructor);\n if (result !== instance && (isObject(result) || isFunction(result))) {\n instance = result;\n if (identifier) {\n // If result changed, re-assign controllerAs value to scope.\n addIdentifier(locals, identifier, instance, constructor || expression.name);\n }\n }\n return instance;\n }, {\n instance: instance,\n identifier: identifier\n });\n }\n\n instance = $injector.instantiate(expression, locals, constructor);\n\n if (identifier) {\n addIdentifier(locals, identifier, instance, constructor || expression.name);\n }\n\n return instance;\n };\n\n function addIdentifier(locals, identifier, instance, name) {\n if (!(locals && isObject(locals.$scope))) {\n throw minErr('$controller')('noscp',\n 'Cannot export controller \\'{0}\\' as \\'{1}\\'! No $scope object provided via `locals`.',\n name, identifier);\n }\n\n locals.$scope[identifier] = instance;\n }\n }];\n}\n\n/**\n * @ngdoc service\n * @name $document\n * @requires $window\n * @this\n *\n * @description\n * A {@link angular.element jQuery or jqLite} wrapper for the browser's `window.document` object.\n *\n * @example\n \n \n
\n

$document title:

\n

window.document title:

\n
\n
\n \n angular.module('documentExample', [])\n .controller('ExampleController', ['$scope', '$document', function($scope, $document) {\n $scope.title = $document[0].title;\n $scope.windowTitle = angular.element(window.document)[0].title;\n }]);\n \n
\n */\nfunction $DocumentProvider() {\n this.$get = ['$window', function(window) {\n return jqLite(window.document);\n }];\n}\n\n\n/**\n * @private\n * @this\n * Listens for document visibility change and makes the current status accessible.\n */\nfunction $$IsDocumentHiddenProvider() {\n this.$get = ['$document', '$rootScope', function($document, $rootScope) {\n var doc = $document[0];\n var hidden = doc && doc.hidden;\n\n $document.on('visibilitychange', changeListener);\n\n $rootScope.$on('$destroy', function() {\n $document.off('visibilitychange', changeListener);\n });\n\n function changeListener() {\n hidden = doc.hidden;\n }\n\n return function() {\n return hidden;\n };\n }];\n}\n\n/**\n * @ngdoc service\n * @name $exceptionHandler\n * @requires ng.$log\n * @this\n *\n * @description\n * Any uncaught exception in angular expressions is delegated to this service.\n * The default implementation simply delegates to `$log.error` which logs it into\n * the browser console.\n *\n * In unit tests, if `angular-mocks.js` is loaded, this service is overridden by\n * {@link ngMock.$exceptionHandler mock $exceptionHandler} which aids in testing.\n *\n * ## Example:\n *\n * The example below will overwrite the default `$exceptionHandler` in order to (a) log uncaught\n * errors to the backend for later inspection by the developers and (b) to use `$log.warn()` instead\n * of `$log.error()`.\n *\n * ```js\n * angular.\n * module('exceptionOverwrite', []).\n * factory('$exceptionHandler', ['$log', 'logErrorsToBackend', function($log, logErrorsToBackend) {\n * return function myExceptionHandler(exception, cause) {\n * logErrorsToBackend(exception, cause);\n * $log.warn(exception, cause);\n * };\n * }]);\n * ```\n *\n *
\n * Note, that code executed in event-listeners (even those registered using jqLite's `on`/`bind`\n * methods) does not delegate exceptions to the {@link ng.$exceptionHandler $exceptionHandler}\n * (unless executed during a digest).\n *\n * If you wish, you can manually delegate exceptions, e.g.\n * `try { ... } catch(e) { $exceptionHandler(e); }`\n *\n * @param {Error} exception Exception associated with the error.\n * @param {string=} cause Optional information about the context in which\n * the error was thrown.\n *\n */\nfunction $ExceptionHandlerProvider() {\n this.$get = ['$log', function($log) {\n return function(exception, cause) {\n $log.error.apply($log, arguments);\n };\n }];\n}\n\nvar $$ForceReflowProvider = /** @this */ function() {\n this.$get = ['$document', function($document) {\n return function(domNode) {\n //the line below will force the browser to perform a repaint so\n //that all the animated elements within the animation frame will\n //be properly updated and drawn on screen. This is required to\n //ensure that the preparation animation is properly flushed so that\n //the active state picks up from there. DO NOT REMOVE THIS LINE.\n //DO NOT OPTIMIZE THIS LINE. THE MINIFIER WILL REMOVE IT OTHERWISE WHICH\n //WILL RESULT IN AN UNPREDICTABLE BUG THAT IS VERY HARD TO TRACK DOWN AND\n //WILL TAKE YEARS AWAY FROM YOUR LIFE.\n if (domNode) {\n if (!domNode.nodeType && domNode instanceof jqLite) {\n domNode = domNode[0];\n }\n } else {\n domNode = $document[0].body;\n }\n return domNode.offsetWidth + 1;\n };\n }];\n};\n\nvar APPLICATION_JSON = 'application/json';\nvar CONTENT_TYPE_APPLICATION_JSON = {'Content-Type': APPLICATION_JSON + ';charset=utf-8'};\nvar JSON_START = /^\\[|^\\{(?!\\{)/;\nvar JSON_ENDS = {\n '[': /]$/,\n '{': /}$/\n};\nvar JSON_PROTECTION_PREFIX = /^\\)]\\}',?\\n/;\nvar $httpMinErr = minErr('$http');\n\nfunction serializeValue(v) {\n if (isObject(v)) {\n return isDate(v) ? v.toISOString() : toJson(v);\n }\n return v;\n}\n\n\n/** @this */\nfunction $HttpParamSerializerProvider() {\n /**\n * @ngdoc service\n * @name $httpParamSerializer\n * @description\n *\n * Default {@link $http `$http`} params serializer that converts objects to strings\n * according to the following rules:\n *\n * * `{'foo': 'bar'}` results in `foo=bar`\n * * `{'foo': Date.now()}` results in `foo=2015-04-01T09%3A50%3A49.262Z` (`toISOString()` and encoded representation of a Date object)\n * * `{'foo': ['bar', 'baz']}` results in `foo=bar&foo=baz` (repeated key for each array element)\n * * `{'foo': {'bar':'baz'}}` results in `foo=%7B%22bar%22%3A%22baz%22%7D` (stringified and encoded representation of an object)\n *\n * Note that serializer will sort the request parameters alphabetically.\n * */\n\n this.$get = function() {\n return function ngParamSerializer(params) {\n if (!params) return '';\n var parts = [];\n forEachSorted(params, function(value, key) {\n if (value === null || isUndefined(value)) return;\n if (isArray(value)) {\n forEach(value, function(v) {\n parts.push(encodeUriQuery(key) + '=' + encodeUriQuery(serializeValue(v)));\n });\n } else {\n parts.push(encodeUriQuery(key) + '=' + encodeUriQuery(serializeValue(value)));\n }\n });\n\n return parts.join('&');\n };\n };\n}\n\n/** @this */\nfunction $HttpParamSerializerJQLikeProvider() {\n /**\n * @ngdoc service\n * @name $httpParamSerializerJQLike\n *\n * @description\n *\n * Alternative {@link $http `$http`} params serializer that follows\n * jQuery's [`param()`](http://api.jquery.com/jquery.param/) method logic.\n * The serializer will also sort the params alphabetically.\n *\n * To use it for serializing `$http` request parameters, set it as the `paramSerializer` property:\n *\n * ```js\n * $http({\n * url: myUrl,\n * method: 'GET',\n * params: myParams,\n * paramSerializer: '$httpParamSerializerJQLike'\n * });\n * ```\n *\n * It is also possible to set it as the default `paramSerializer` in the\n * {@link $httpProvider#defaults `$httpProvider`}.\n *\n * Additionally, you can inject the serializer and use it explicitly, for example to serialize\n * form data for submission:\n *\n * ```js\n * .controller(function($http, $httpParamSerializerJQLike) {\n * //...\n *\n * $http({\n * url: myUrl,\n * method: 'POST',\n * data: $httpParamSerializerJQLike(myData),\n * headers: {\n * 'Content-Type': 'application/x-www-form-urlencoded'\n * }\n * });\n *\n * });\n * ```\n *\n * */\n this.$get = function() {\n return function jQueryLikeParamSerializer(params) {\n if (!params) return '';\n var parts = [];\n serialize(params, '', true);\n return parts.join('&');\n\n function serialize(toSerialize, prefix, topLevel) {\n if (toSerialize === null || isUndefined(toSerialize)) return;\n if (isArray(toSerialize)) {\n forEach(toSerialize, function(value, index) {\n serialize(value, prefix + '[' + (isObject(value) ? index : '') + ']');\n });\n } else if (isObject(toSerialize) && !isDate(toSerialize)) {\n forEachSorted(toSerialize, function(value, key) {\n serialize(value, prefix +\n (topLevel ? '' : '[') +\n key +\n (topLevel ? '' : ']'));\n });\n } else {\n parts.push(encodeUriQuery(prefix) + '=' + encodeUriQuery(serializeValue(toSerialize)));\n }\n }\n };\n };\n}\n\nfunction defaultHttpResponseTransform(data, headers) {\n if (isString(data)) {\n // Strip json vulnerability protection prefix and trim whitespace\n var tempData = data.replace(JSON_PROTECTION_PREFIX, '').trim();\n\n if (tempData) {\n var contentType = headers('Content-Type');\n if ((contentType && (contentType.indexOf(APPLICATION_JSON) === 0)) || isJsonLike(tempData)) {\n data = fromJson(tempData);\n }\n }\n }\n\n return data;\n}\n\nfunction isJsonLike(str) {\n var jsonStart = str.match(JSON_START);\n return jsonStart && JSON_ENDS[jsonStart[0]].test(str);\n}\n\n/**\n * Parse headers into key value object\n *\n * @param {string} headers Raw headers as a string\n * @returns {Object} Parsed headers as key value object\n */\nfunction parseHeaders(headers) {\n var parsed = createMap(), i;\n\n function fillInParsed(key, val) {\n if (key) {\n parsed[key] = parsed[key] ? parsed[key] + ', ' + val : val;\n }\n }\n\n if (isString(headers)) {\n forEach(headers.split('\\n'), function(line) {\n i = line.indexOf(':');\n fillInParsed(lowercase(trim(line.substr(0, i))), trim(line.substr(i + 1)));\n });\n } else if (isObject(headers)) {\n forEach(headers, function(headerVal, headerKey) {\n fillInParsed(lowercase(headerKey), trim(headerVal));\n });\n }\n\n return parsed;\n}\n\n\n/**\n * Returns a function that provides access to parsed headers.\n *\n * Headers are lazy parsed when first requested.\n * @see parseHeaders\n *\n * @param {(string|Object)} headers Headers to provide access to.\n * @returns {function(string=)} Returns a getter function which if called with:\n *\n * - if called with an argument returns a single header value or null\n * - if called with no arguments returns an object containing all headers.\n */\nfunction headersGetter(headers) {\n var headersObj;\n\n return function(name) {\n if (!headersObj) headersObj = parseHeaders(headers);\n\n if (name) {\n var value = headersObj[lowercase(name)];\n if (value === undefined) {\n value = null;\n }\n return value;\n }\n\n return headersObj;\n };\n}\n\n\n/**\n * Chain all given functions\n *\n * This function is used for both request and response transforming\n *\n * @param {*} data Data to transform.\n * @param {function(string=)} headers HTTP headers getter fn.\n * @param {number} status HTTP status code of the response.\n * @param {(Function|Array.)} fns Function or an array of functions.\n * @returns {*} Transformed data.\n */\nfunction transformData(data, headers, status, fns) {\n if (isFunction(fns)) {\n return fns(data, headers, status);\n }\n\n forEach(fns, function(fn) {\n data = fn(data, headers, status);\n });\n\n return data;\n}\n\n\nfunction isSuccess(status) {\n return 200 <= status && status < 300;\n}\n\n\n/**\n * @ngdoc provider\n * @name $httpProvider\n * @this\n *\n * @description\n * Use `$httpProvider` to change the default behavior of the {@link ng.$http $http} service.\n * */\nfunction $HttpProvider() {\n /**\n * @ngdoc property\n * @name $httpProvider#defaults\n * @description\n *\n * Object containing default values for all {@link ng.$http $http} requests.\n *\n * - **`defaults.cache`** - {boolean|Object} - A boolean value or object created with\n * {@link ng.$cacheFactory `$cacheFactory`} to enable or disable caching of HTTP responses\n * by default. See {@link $http#caching $http Caching} for more information.\n *\n * - **`defaults.xsrfCookieName`** - {string} - Name of cookie containing the XSRF token.\n * Defaults value is `'XSRF-TOKEN'`.\n *\n * - **`defaults.xsrfHeaderName`** - {string} - Name of HTTP header to populate with the\n * XSRF token. Defaults value is `'X-XSRF-TOKEN'`.\n *\n * - **`defaults.headers`** - {Object} - Default headers for all $http requests.\n * Refer to {@link ng.$http#setting-http-headers $http} for documentation on\n * setting default headers.\n * - **`defaults.headers.common`**\n * - **`defaults.headers.post`**\n * - **`defaults.headers.put`**\n * - **`defaults.headers.patch`**\n *\n *\n * - **`defaults.paramSerializer`** - `{string|function(Object):string}` - A function\n * used to the prepare string representation of request parameters (specified as an object).\n * If specified as string, it is interpreted as a function registered with the {@link auto.$injector $injector}.\n * Defaults to {@link ng.$httpParamSerializer $httpParamSerializer}.\n *\n * - **`defaults.jsonpCallbackParam`** - `{string}` - the name of the query parameter that passes the name of the\n * callback in a JSONP request. The value of this parameter will be replaced with the expression generated by the\n * {@link $jsonpCallbacks} service. Defaults to `'callback'`.\n *\n **/\n var defaults = this.defaults = {\n // transform incoming response data\n transformResponse: [defaultHttpResponseTransform],\n\n // transform outgoing request data\n transformRequest: [function(d) {\n return isObject(d) && !isFile(d) && !isBlob(d) && !isFormData(d) ? toJson(d) : d;\n }],\n\n // default headers\n headers: {\n common: {\n 'Accept': 'application/json, text/plain, */*'\n },\n post: shallowCopy(CONTENT_TYPE_APPLICATION_JSON),\n put: shallowCopy(CONTENT_TYPE_APPLICATION_JSON),\n patch: shallowCopy(CONTENT_TYPE_APPLICATION_JSON)\n },\n\n xsrfCookieName: 'XSRF-TOKEN',\n xsrfHeaderName: 'X-XSRF-TOKEN',\n\n paramSerializer: '$httpParamSerializer',\n\n jsonpCallbackParam: 'callback'\n };\n\n var useApplyAsync = false;\n /**\n * @ngdoc method\n * @name $httpProvider#useApplyAsync\n * @description\n *\n * Configure $http service to combine processing of multiple http responses received at around\n * the same time via {@link ng.$rootScope.Scope#$applyAsync $rootScope.$applyAsync}. This can result in\n * significant performance improvement for bigger applications that make many HTTP requests\n * concurrently (common during application bootstrap).\n *\n * Defaults to false. If no value is specified, returns the current configured value.\n *\n * @param {boolean=} value If true, when requests are loaded, they will schedule a deferred\n * \"apply\" on the next tick, giving time for subsequent requests in a roughly ~10ms window\n * to load and share the same digest cycle.\n *\n * @returns {boolean|Object} If a value is specified, returns the $httpProvider for chaining.\n * otherwise, returns the current configured value.\n **/\n this.useApplyAsync = function(value) {\n if (isDefined(value)) {\n useApplyAsync = !!value;\n return this;\n }\n return useApplyAsync;\n };\n\n /**\n * @ngdoc property\n * @name $httpProvider#interceptors\n * @description\n *\n * Array containing service factories for all synchronous or asynchronous {@link ng.$http $http}\n * pre-processing of request or postprocessing of responses.\n *\n * These service factories are ordered by request, i.e. they are applied in the same order as the\n * array, on request, but reverse order, on response.\n *\n * {@link ng.$http#interceptors Interceptors detailed info}\n **/\n var interceptorFactories = this.interceptors = [];\n\n this.$get = ['$browser', '$httpBackend', '$$cookieReader', '$cacheFactory', '$rootScope', '$q', '$injector', '$sce',\n function($browser, $httpBackend, $$cookieReader, $cacheFactory, $rootScope, $q, $injector, $sce) {\n\n var defaultCache = $cacheFactory('$http');\n\n /**\n * Make sure that default param serializer is exposed as a function\n */\n defaults.paramSerializer = isString(defaults.paramSerializer) ?\n $injector.get(defaults.paramSerializer) : defaults.paramSerializer;\n\n /**\n * Interceptors stored in reverse order. Inner interceptors before outer interceptors.\n * The reversal is needed so that we can build up the interception chain around the\n * server request.\n */\n var reversedInterceptors = [];\n\n forEach(interceptorFactories, function(interceptorFactory) {\n reversedInterceptors.unshift(isString(interceptorFactory)\n ? $injector.get(interceptorFactory) : $injector.invoke(interceptorFactory));\n });\n\n /**\n * @ngdoc service\n * @kind function\n * @name $http\n * @requires ng.$httpBackend\n * @requires $cacheFactory\n * @requires $rootScope\n * @requires $q\n * @requires $injector\n *\n * @description\n * The `$http` service is a core Angular service that facilitates communication with the remote\n * HTTP servers via the browser's [XMLHttpRequest](https://developer.mozilla.org/en/xmlhttprequest)\n * object or via [JSONP](http://en.wikipedia.org/wiki/JSONP).\n *\n * For unit testing applications that use `$http` service, see\n * {@link ngMock.$httpBackend $httpBackend mock}.\n *\n * For a higher level of abstraction, please check out the {@link ngResource.$resource\n * $resource} service.\n *\n * The $http API is based on the {@link ng.$q deferred/promise APIs} exposed by\n * the $q service. While for simple usage patterns this doesn't matter much, for advanced usage\n * it is important to familiarize yourself with these APIs and the guarantees they provide.\n *\n *\n * ## General usage\n * The `$http` service is a function which takes a single argument — a {@link $http#usage configuration object} —\n * that is used to generate an HTTP request and returns a {@link ng.$q promise}.\n *\n * ```js\n * // Simple GET request example:\n * $http({\n * method: 'GET',\n * url: '/someUrl'\n * }).then(function successCallback(response) {\n * // this callback will be called asynchronously\n * // when the response is available\n * }, function errorCallback(response) {\n * // called asynchronously if an error occurs\n * // or server returns response with an error status.\n * });\n * ```\n *\n * The response object has these properties:\n *\n * - **data** – `{string|Object}` – The response body transformed with the transform\n * functions.\n * - **status** – `{number}` – HTTP status code of the response.\n * - **headers** – `{function([headerName])}` – Header getter function.\n * - **config** – `{Object}` – The configuration object that was used to generate the request.\n * - **statusText** – `{string}` – HTTP status text of the response.\n *\n * A response status code between 200 and 299 is considered a success status and will result in\n * the success callback being called. Any response status code outside of that range is\n * considered an error status and will result in the error callback being called.\n * Also, status codes less than -1 are normalized to zero. -1 usually means the request was\n * aborted, e.g. using a `config.timeout`.\n * Note that if the response is a redirect, XMLHttpRequest will transparently follow it, meaning\n * that the outcome (success or error) will be determined by the final response status code.\n *\n *\n * ## Shortcut methods\n *\n * Shortcut methods are also available. All shortcut methods require passing in the URL, and\n * request data must be passed in for POST/PUT requests. An optional config can be passed as the\n * last argument.\n *\n * ```js\n * $http.get('/someUrl', config).then(successCallback, errorCallback);\n * $http.post('/someUrl', data, config).then(successCallback, errorCallback);\n * ```\n *\n * Complete list of shortcut methods:\n *\n * - {@link ng.$http#get $http.get}\n * - {@link ng.$http#head $http.head}\n * - {@link ng.$http#post $http.post}\n * - {@link ng.$http#put $http.put}\n * - {@link ng.$http#delete $http.delete}\n * - {@link ng.$http#jsonp $http.jsonp}\n * - {@link ng.$http#patch $http.patch}\n *\n *\n * ## Writing Unit Tests that use $http\n * When unit testing (using {@link ngMock ngMock}), it is necessary to call\n * {@link ngMock.$httpBackend#flush $httpBackend.flush()} to flush each pending\n * request using trained responses.\n *\n * ```\n * $httpBackend.expectGET(...);\n * $http.get(...);\n * $httpBackend.flush();\n * ```\n *\n * ## Setting HTTP Headers\n *\n * The $http service will automatically add certain HTTP headers to all requests. These defaults\n * can be fully configured by accessing the `$httpProvider.defaults.headers` configuration\n * object, which currently contains this default configuration:\n *\n * - `$httpProvider.defaults.headers.common` (headers that are common for all requests):\n * - Accept: application/json, text/plain, \\*/\\*\n * - `$httpProvider.defaults.headers.post`: (header defaults for POST requests)\n * - `Content-Type: application/json`\n * - `$httpProvider.defaults.headers.put` (header defaults for PUT requests)\n * - `Content-Type: application/json`\n *\n * To add or overwrite these defaults, simply add or remove a property from these configuration\n * objects. To add headers for an HTTP method other than POST or PUT, simply add a new object\n * with the lowercased HTTP method name as the key, e.g.\n * `$httpProvider.defaults.headers.get = { 'My-Header' : 'value' }`.\n *\n * The defaults can also be set at runtime via the `$http.defaults` object in the same\n * fashion. For example:\n *\n * ```\n * module.run(function($http) {\n * $http.defaults.headers.common.Authorization = 'Basic YmVlcDpib29w';\n * });\n * ```\n *\n * In addition, you can supply a `headers` property in the config object passed when\n * calling `$http(config)`, which overrides the defaults without changing them globally.\n *\n * To explicitly remove a header automatically added via $httpProvider.defaults.headers on a per request basis,\n * Use the `headers` property, setting the desired header to `undefined`. For example:\n *\n * ```js\n * var req = {\n * method: 'POST',\n * url: 'http://example.com',\n * headers: {\n * 'Content-Type': undefined\n * },\n * data: { test: 'test' }\n * }\n *\n * $http(req).then(function(){...}, function(){...});\n * ```\n *\n * ## Transforming Requests and Responses\n *\n * Both requests and responses can be transformed using transformation functions: `transformRequest`\n * and `transformResponse`. These properties can be a single function that returns\n * the transformed value (`function(data, headersGetter, status)`) or an array of such transformation functions,\n * which allows you to `push` or `unshift` a new transformation function into the transformation chain.\n *\n *
\n * **Note:** Angular does not make a copy of the `data` parameter before it is passed into the `transformRequest` pipeline.\n * That means changes to the properties of `data` are not local to the transform function (since Javascript passes objects by reference).\n * For example, when calling `$http.get(url, $scope.myObject)`, modifications to the object's properties in a transformRequest\n * function will be reflected on the scope and in any templates where the object is data-bound.\n * To prevent this, transform functions should have no side-effects.\n * If you need to modify properties, it is recommended to make a copy of the data, or create new object to return.\n *
\n *\n * ### Default Transformations\n *\n * The `$httpProvider` provider and `$http` service expose `defaults.transformRequest` and\n * `defaults.transformResponse` properties. If a request does not provide its own transformations\n * then these will be applied.\n *\n * You can augment or replace the default transformations by modifying these properties by adding to or\n * replacing the array.\n *\n * Angular provides the following default transformations:\n *\n * Request transformations (`$httpProvider.defaults.transformRequest` and `$http.defaults.transformRequest`):\n *\n * - If the `data` property of the request configuration object contains an object, serialize it\n * into JSON format.\n *\n * Response transformations (`$httpProvider.defaults.transformResponse` and `$http.defaults.transformResponse`):\n *\n * - If XSRF prefix is detected, strip it (see Security Considerations section below).\n * - If JSON response is detected, deserialize it using a JSON parser.\n *\n *\n * ### Overriding the Default Transformations Per Request\n *\n * If you wish to override the request/response transformations only for a single request then provide\n * `transformRequest` and/or `transformResponse` properties on the configuration object passed\n * into `$http`.\n *\n * Note that if you provide these properties on the config object the default transformations will be\n * overwritten. If you wish to augment the default transformations then you must include them in your\n * local transformation array.\n *\n * The following code demonstrates adding a new response transformation to be run after the default response\n * transformations have been run.\n *\n * ```js\n * function appendTransform(defaults, transform) {\n *\n * // We can't guarantee that the default transformation is an array\n * defaults = angular.isArray(defaults) ? defaults : [defaults];\n *\n * // Append the new transformation to the defaults\n * return defaults.concat(transform);\n * }\n *\n * $http({\n * url: '...',\n * method: 'GET',\n * transformResponse: appendTransform($http.defaults.transformResponse, function(value) {\n * return doTransform(value);\n * })\n * });\n * ```\n *\n *\n * ## Caching\n *\n * {@link ng.$http `$http`} responses are not cached by default. To enable caching, you must\n * set the config.cache value or the default cache value to TRUE or to a cache object (created\n * with {@link ng.$cacheFactory `$cacheFactory`}). If defined, the value of config.cache takes\n * precedence over the default cache value.\n *\n * In order to:\n * * cache all responses - set the default cache value to TRUE or to a cache object\n * * cache a specific response - set config.cache value to TRUE or to a cache object\n *\n * If caching is enabled, but neither the default cache nor config.cache are set to a cache object,\n * then the default `$cacheFactory(\"$http\")` object is used.\n *\n * The default cache value can be set by updating the\n * {@link ng.$http#defaults `$http.defaults.cache`} property or the\n * {@link $httpProvider#defaults `$httpProvider.defaults.cache`} property.\n *\n * When caching is enabled, {@link ng.$http `$http`} stores the response from the server using\n * the relevant cache object. The next time the same request is made, the response is returned\n * from the cache without sending a request to the server.\n *\n * Take note that:\n *\n * * Only GET and JSONP requests are cached.\n * * The cache key is the request URL including search parameters; headers are not considered.\n * * Cached responses are returned asynchronously, in the same way as responses from the server.\n * * If multiple identical requests are made using the same cache, which is not yet populated,\n * one request will be made to the server and remaining requests will return the same response.\n * * A cache-control header on the response does not affect if or how responses are cached.\n *\n *\n * ## Interceptors\n *\n * Before you start creating interceptors, be sure to understand the\n * {@link ng.$q $q and deferred/promise APIs}.\n *\n * For purposes of global error handling, authentication, or any kind of synchronous or\n * asynchronous pre-processing of request or postprocessing of responses, it is desirable to be\n * able to intercept requests before they are handed to the server and\n * responses before they are handed over to the application code that\n * initiated these requests. The interceptors leverage the {@link ng.$q\n * promise APIs} to fulfill this need for both synchronous and asynchronous pre-processing.\n *\n * The interceptors are service factories that are registered with the `$httpProvider` by\n * adding them to the `$httpProvider.interceptors` array. The factory is called and\n * injected with dependencies (if specified) and returns the interceptor.\n *\n * There are two kinds of interceptors (and two kinds of rejection interceptors):\n *\n * * `request`: interceptors get called with a http {@link $http#usage config} object. The function is free to\n * modify the `config` object or create a new one. The function needs to return the `config`\n * object directly, or a promise containing the `config` or a new `config` object.\n * * `requestError`: interceptor gets called when a previous interceptor threw an error or\n * resolved with a rejection.\n * * `response`: interceptors get called with http `response` object. The function is free to\n * modify the `response` object or create a new one. The function needs to return the `response`\n * object directly, or as a promise containing the `response` or a new `response` object.\n * * `responseError`: interceptor gets called when a previous interceptor threw an error or\n * resolved with a rejection.\n *\n *\n * ```js\n * // register the interceptor as a service\n * $provide.factory('myHttpInterceptor', function($q, dependency1, dependency2) {\n * return {\n * // optional method\n * 'request': function(config) {\n * // do something on success\n * return config;\n * },\n *\n * // optional method\n * 'requestError': function(rejection) {\n * // do something on error\n * if (canRecover(rejection)) {\n * return responseOrNewPromise\n * }\n * return $q.reject(rejection);\n * },\n *\n *\n *\n * // optional method\n * 'response': function(response) {\n * // do something on success\n * return response;\n * },\n *\n * // optional method\n * 'responseError': function(rejection) {\n * // do something on error\n * if (canRecover(rejection)) {\n * return responseOrNewPromise\n * }\n * return $q.reject(rejection);\n * }\n * };\n * });\n *\n * $httpProvider.interceptors.push('myHttpInterceptor');\n *\n *\n * // alternatively, register the interceptor via an anonymous factory\n * $httpProvider.interceptors.push(function($q, dependency1, dependency2) {\n * return {\n * 'request': function(config) {\n * // same as above\n * },\n *\n * 'response': function(response) {\n * // same as above\n * }\n * };\n * });\n * ```\n *\n * ## Security Considerations\n *\n * When designing web applications, consider security threats from:\n *\n * - [JSON vulnerability](http://haacked.com/archive/2008/11/20/anatomy-of-a-subtle-json-vulnerability.aspx)\n * - [XSRF](http://en.wikipedia.org/wiki/Cross-site_request_forgery)\n *\n * Both server and the client must cooperate in order to eliminate these threats. Angular comes\n * pre-configured with strategies that address these issues, but for this to work backend server\n * cooperation is required.\n *\n * ### JSON Vulnerability Protection\n *\n * A [JSON vulnerability](http://haacked.com/archive/2008/11/20/anatomy-of-a-subtle-json-vulnerability.aspx)\n * allows third party website to turn your JSON resource URL into\n * [JSONP](http://en.wikipedia.org/wiki/JSONP) request under some conditions. To\n * counter this your server can prefix all JSON requests with following string `\")]}',\\n\"`.\n * Angular will automatically strip the prefix before processing it as JSON.\n *\n * For example if your server needs to return:\n * ```js\n * ['one','two']\n * ```\n *\n * which is vulnerable to attack, your server can return:\n * ```js\n * )]}',\n * ['one','two']\n * ```\n *\n * Angular will strip the prefix, before processing the JSON.\n *\n *\n * ### Cross Site Request Forgery (XSRF) Protection\n *\n * [XSRF](http://en.wikipedia.org/wiki/Cross-site_request_forgery) is an attack technique by\n * which the attacker can trick an authenticated user into unknowingly executing actions on your\n * website. Angular provides a mechanism to counter XSRF. When performing XHR requests, the\n * $http service reads a token from a cookie (by default, `XSRF-TOKEN`) and sets it as an HTTP\n * header (`X-XSRF-TOKEN`). Since only JavaScript that runs on your domain could read the\n * cookie, your server can be assured that the XHR came from JavaScript running on your domain.\n * The header will not be set for cross-domain requests.\n *\n * To take advantage of this, your server needs to set a token in a JavaScript readable session\n * cookie called `XSRF-TOKEN` on the first HTTP GET request. On subsequent XHR requests the\n * server can verify that the cookie matches `X-XSRF-TOKEN` HTTP header, and therefore be sure\n * that only JavaScript running on your domain could have sent the request. The token must be\n * unique for each user and must be verifiable by the server (to prevent the JavaScript from\n * making up its own tokens). We recommend that the token is a digest of your site's\n * authentication cookie with a [salt](https://en.wikipedia.org/wiki/Salt_(cryptography))\n * for added security.\n *\n * The name of the headers can be specified using the xsrfHeaderName and xsrfCookieName\n * properties of either $httpProvider.defaults at config-time, $http.defaults at run-time,\n * or the per-request config object.\n *\n * In order to prevent collisions in environments where multiple Angular apps share the\n * same domain or subdomain, we recommend that each application uses unique cookie name.\n *\n * @param {object} config Object describing the request to be made and how it should be\n * processed. The object has following properties:\n *\n * - **method** – `{string}` – HTTP method (e.g. 'GET', 'POST', etc)\n * - **url** – `{string|TrustedObject}` – Absolute or relative URL of the resource that is being requested;\n * or an object created by a call to `$sce.trustAsResourceUrl(url)`.\n * - **params** – `{Object.}` – Map of strings or objects which will be serialized\n * with the `paramSerializer` and appended as GET parameters.\n * - **data** – `{string|Object}` – Data to be sent as the request message data.\n * - **headers** – `{Object}` – Map of strings or functions which return strings representing\n * HTTP headers to send to the server. If the return value of a function is null, the\n * header will not be sent. Functions accept a config object as an argument.\n * - **eventHandlers** - `{Object}` - Event listeners to be bound to the XMLHttpRequest object.\n * To bind events to the XMLHttpRequest upload object, use `uploadEventHandlers`.\n * The handler will be called in the context of a `$apply` block.\n * - **uploadEventHandlers** - `{Object}` - Event listeners to be bound to the XMLHttpRequest upload\n * object. To bind events to the XMLHttpRequest object, use `eventHandlers`.\n * The handler will be called in the context of a `$apply` block.\n * - **xsrfHeaderName** – `{string}` – Name of HTTP header to populate with the XSRF token.\n * - **xsrfCookieName** – `{string}` – Name of cookie containing the XSRF token.\n * - **transformRequest** –\n * `{function(data, headersGetter)|Array.}` –\n * transform function or an array of such functions. The transform function takes the http\n * request body and headers and returns its transformed (typically serialized) version.\n * See {@link ng.$http#overriding-the-default-transformations-per-request\n * Overriding the Default Transformations}\n * - **transformResponse** –\n * `{function(data, headersGetter, status)|Array.}` –\n * transform function or an array of such functions. The transform function takes the http\n * response body, headers and status and returns its transformed (typically deserialized) version.\n * See {@link ng.$http#overriding-the-default-transformations-per-request\n * Overriding the Default Transformations}\n * - **paramSerializer** - `{string|function(Object):string}` - A function used to\n * prepare the string representation of request parameters (specified as an object).\n * If specified as string, it is interpreted as function registered with the\n * {@link $injector $injector}, which means you can create your own serializer\n * by registering it as a {@link auto.$provide#service service}.\n * The default serializer is the {@link $httpParamSerializer $httpParamSerializer};\n * alternatively, you can use the {@link $httpParamSerializerJQLike $httpParamSerializerJQLike}\n * - **cache** – `{boolean|Object}` – A boolean value or object created with\n * {@link ng.$cacheFactory `$cacheFactory`} to enable or disable caching of the HTTP response.\n * See {@link $http#caching $http Caching} for more information.\n * - **timeout** – `{number|Promise}` – timeout in milliseconds, or {@link ng.$q promise}\n * that should abort the request when resolved.\n * - **withCredentials** - `{boolean}` - whether to set the `withCredentials` flag on the\n * XHR object. See [requests with credentials](https://developer.mozilla.org/docs/Web/HTTP/Access_control_CORS#Requests_with_credentials)\n * for more information.\n * - **responseType** - `{string}` - see\n * [XMLHttpRequest.responseType](https://developer.mozilla.org/en-US/docs/Web/API/XMLHttpRequest#xmlhttprequest-responsetype).\n *\n * @returns {HttpPromise} Returns a {@link ng.$q `Promise}` that will be resolved to a response object\n * when the request succeeds or fails.\n *\n *\n * @property {Array.} pendingRequests Array of config objects for currently pending\n * requests. This is primarily meant to be used for debugging purposes.\n *\n *\n * @example\n\n\n
\n \n \n
\n \n \n \n
http status code: {{status}}
\n
http response data: {{data}}
\n
\n
\n\n angular.module('httpExample', [])\n .config(['$sceDelegateProvider', function($sceDelegateProvider) {\n // We must whitelist the JSONP endpoint that we are using to show that we trust it\n $sceDelegateProvider.resourceUrlWhitelist([\n 'self',\n 'https://angularjs.org/**'\n ]);\n }])\n .controller('FetchController', ['$scope', '$http', '$templateCache',\n function($scope, $http, $templateCache) {\n $scope.method = 'GET';\n $scope.url = 'http-hello.html';\n\n $scope.fetch = function() {\n $scope.code = null;\n $scope.response = null;\n\n $http({method: $scope.method, url: $scope.url, cache: $templateCache}).\n then(function(response) {\n $scope.status = response.status;\n $scope.data = response.data;\n }, function(response) {\n $scope.data = response.data || 'Request failed';\n $scope.status = response.status;\n });\n };\n\n $scope.updateModel = function(method, url) {\n $scope.method = method;\n $scope.url = url;\n };\n }]);\n\n\n Hello, $http!\n\n\n var status = element(by.binding('status'));\n var data = element(by.binding('data'));\n var fetchBtn = element(by.id('fetchbtn'));\n var sampleGetBtn = element(by.id('samplegetbtn'));\n var invalidJsonpBtn = element(by.id('invalidjsonpbtn'));\n\n it('should make an xhr GET request', function() {\n sampleGetBtn.click();\n fetchBtn.click();\n expect(status.getText()).toMatch('200');\n expect(data.getText()).toMatch(/Hello, \\$http!/);\n });\n\n// Commented out due to flakes. See https://github.com/angular/angular.js/issues/9185\n// it('should make a JSONP request to angularjs.org', function() {\n// var sampleJsonpBtn = element(by.id('samplejsonpbtn'));\n// sampleJsonpBtn.click();\n// fetchBtn.click();\n// expect(status.getText()).toMatch('200');\n// expect(data.getText()).toMatch(/Super Hero!/);\n// });\n\n it('should make JSONP request to invalid URL and invoke the error handler',\n function() {\n invalidJsonpBtn.click();\n fetchBtn.click();\n expect(status.getText()).toMatch('0');\n expect(data.getText()).toMatch('Request failed');\n });\n\n
\n */\n function $http(requestConfig) {\n\n if (!isObject(requestConfig)) {\n throw minErr('$http')('badreq', 'Http request configuration must be an object. Received: {0}', requestConfig);\n }\n\n if (!isString($sce.valueOf(requestConfig.url))) {\n throw minErr('$http')('badreq', 'Http request configuration url must be a string or a $sce trusted object. Received: {0}', requestConfig.url);\n }\n\n var config = extend({\n method: 'get',\n transformRequest: defaults.transformRequest,\n transformResponse: defaults.transformResponse,\n paramSerializer: defaults.paramSerializer,\n jsonpCallbackParam: defaults.jsonpCallbackParam\n }, requestConfig);\n\n config.headers = mergeHeaders(requestConfig);\n config.method = uppercase(config.method);\n config.paramSerializer = isString(config.paramSerializer) ?\n $injector.get(config.paramSerializer) : config.paramSerializer;\n\n $browser.$$incOutstandingRequestCount();\n\n var requestInterceptors = [];\n var responseInterceptors = [];\n var promise = $q.resolve(config);\n\n // apply interceptors\n forEach(reversedInterceptors, function(interceptor) {\n if (interceptor.request || interceptor.requestError) {\n requestInterceptors.unshift(interceptor.request, interceptor.requestError);\n }\n if (interceptor.response || interceptor.responseError) {\n responseInterceptors.push(interceptor.response, interceptor.responseError);\n }\n });\n\n promise = chainInterceptors(promise, requestInterceptors);\n promise = promise.then(serverRequest);\n promise = chainInterceptors(promise, responseInterceptors);\n promise = promise.finally(completeOutstandingRequest);\n\n return promise;\n\n\n function chainInterceptors(promise, interceptors) {\n for (var i = 0, ii = interceptors.length; i < ii;) {\n var thenFn = interceptors[i++];\n var rejectFn = interceptors[i++];\n\n promise = promise.then(thenFn, rejectFn);\n }\n\n interceptors.length = 0;\n\n return promise;\n }\n\n function completeOutstandingRequest() {\n $browser.$$completeOutstandingRequest(noop);\n }\n\n function executeHeaderFns(headers, config) {\n var headerContent, processedHeaders = {};\n\n forEach(headers, function(headerFn, header) {\n if (isFunction(headerFn)) {\n headerContent = headerFn(config);\n if (headerContent != null) {\n processedHeaders[header] = headerContent;\n }\n } else {\n processedHeaders[header] = headerFn;\n }\n });\n\n return processedHeaders;\n }\n\n function mergeHeaders(config) {\n var defHeaders = defaults.headers,\n reqHeaders = extend({}, config.headers),\n defHeaderName, lowercaseDefHeaderName, reqHeaderName;\n\n defHeaders = extend({}, defHeaders.common, defHeaders[lowercase(config.method)]);\n\n // using for-in instead of forEach to avoid unnecessary iteration after header has been found\n defaultHeadersIteration:\n for (defHeaderName in defHeaders) {\n lowercaseDefHeaderName = lowercase(defHeaderName);\n\n for (reqHeaderName in reqHeaders) {\n if (lowercase(reqHeaderName) === lowercaseDefHeaderName) {\n continue defaultHeadersIteration;\n }\n }\n\n reqHeaders[defHeaderName] = defHeaders[defHeaderName];\n }\n\n // execute if header value is a function for merged headers\n return executeHeaderFns(reqHeaders, shallowCopy(config));\n }\n\n function serverRequest(config) {\n var headers = config.headers;\n var reqData = transformData(config.data, headersGetter(headers), undefined, config.transformRequest);\n\n // strip content-type if data is undefined\n if (isUndefined(reqData)) {\n forEach(headers, function(value, header) {\n if (lowercase(header) === 'content-type') {\n delete headers[header];\n }\n });\n }\n\n if (isUndefined(config.withCredentials) && !isUndefined(defaults.withCredentials)) {\n config.withCredentials = defaults.withCredentials;\n }\n\n // send request\n return sendReq(config, reqData).then(transformResponse, transformResponse);\n }\n\n function transformResponse(response) {\n // make a copy since the response must be cacheable\n var resp = extend({}, response);\n resp.data = transformData(response.data, response.headers, response.status,\n config.transformResponse);\n return (isSuccess(response.status))\n ? resp\n : $q.reject(resp);\n }\n }\n\n $http.pendingRequests = [];\n\n /**\n * @ngdoc method\n * @name $http#get\n *\n * @description\n * Shortcut method to perform `GET` request.\n *\n * @param {string|TrustedObject} url Absolute or relative URL of the resource that is being requested;\n * or an object created by a call to `$sce.trustAsResourceUrl(url)`.\n * @param {Object=} config Optional configuration object\n * @returns {HttpPromise} Future object\n */\n\n /**\n * @ngdoc method\n * @name $http#delete\n *\n * @description\n * Shortcut method to perform `DELETE` request.\n *\n * @param {string|TrustedObject} url Absolute or relative URL of the resource that is being requested;\n * or an object created by a call to `$sce.trustAsResourceUrl(url)`.\n * @param {Object=} config Optional configuration object\n * @returns {HttpPromise} Future object\n */\n\n /**\n * @ngdoc method\n * @name $http#head\n *\n * @description\n * Shortcut method to perform `HEAD` request.\n *\n * @param {string|TrustedObject} url Absolute or relative URL of the resource that is being requested;\n * or an object created by a call to `$sce.trustAsResourceUrl(url)`.\n * @param {Object=} config Optional configuration object\n * @returns {HttpPromise} Future object\n */\n\n /**\n * @ngdoc method\n * @name $http#jsonp\n *\n * @description\n * Shortcut method to perform `JSONP` request.\n *\n * Note that, since JSONP requests are sensitive because the response is given full access to the browser,\n * the url must be declared, via {@link $sce} as a trusted resource URL.\n * You can trust a URL by adding it to the whitelist via\n * {@link $sceDelegateProvider#resourceUrlWhitelist `$sceDelegateProvider.resourceUrlWhitelist`} or\n * by explicitly trusting the URL via {@link $sce#trustAsResourceUrl `$sce.trustAsResourceUrl(url)`}.\n *\n * JSONP requests must specify a callback to be used in the response from the server. This callback\n * is passed as a query parameter in the request. You must specify the name of this parameter by\n * setting the `jsonpCallbackParam` property on the request config object.\n *\n * ```\n * $http.jsonp('some/trusted/url', {jsonpCallbackParam: 'callback'})\n * ```\n *\n * You can also specify a default callback parameter name in `$http.defaults.jsonpCallbackParam`.\n * Initially this is set to `'callback'`.\n *\n *
\n * You can no longer use the `JSON_CALLBACK` string as a placeholder for specifying where the callback\n * parameter value should go.\n *
\n *\n * If you would like to customise where and how the callbacks are stored then try overriding\n * or decorating the {@link $jsonpCallbacks} service.\n *\n * @param {string|TrustedObject} url Absolute or relative URL of the resource that is being requested;\n * or an object created by a call to `$sce.trustAsResourceUrl(url)`.\n * @param {Object=} config Optional configuration object\n * @returns {HttpPromise} Future object\n */\n createShortMethods('get', 'delete', 'head', 'jsonp');\n\n /**\n * @ngdoc method\n * @name $http#post\n *\n * @description\n * Shortcut method to perform `POST` request.\n *\n * @param {string} url Relative or absolute URL specifying the destination of the request\n * @param {*} data Request content\n * @param {Object=} config Optional configuration object\n * @returns {HttpPromise} Future object\n */\n\n /**\n * @ngdoc method\n * @name $http#put\n *\n * @description\n * Shortcut method to perform `PUT` request.\n *\n * @param {string} url Relative or absolute URL specifying the destination of the request\n * @param {*} data Request content\n * @param {Object=} config Optional configuration object\n * @returns {HttpPromise} Future object\n */\n\n /**\n * @ngdoc method\n * @name $http#patch\n *\n * @description\n * Shortcut method to perform `PATCH` request.\n *\n * @param {string} url Relative or absolute URL specifying the destination of the request\n * @param {*} data Request content\n * @param {Object=} config Optional configuration object\n * @returns {HttpPromise} Future object\n */\n createShortMethodsWithData('post', 'put', 'patch');\n\n /**\n * @ngdoc property\n * @name $http#defaults\n *\n * @description\n * Runtime equivalent of the `$httpProvider.defaults` property. Allows configuration of\n * default headers, withCredentials as well as request and response transformations.\n *\n * See \"Setting HTTP Headers\" and \"Transforming Requests and Responses\" sections above.\n */\n $http.defaults = defaults;\n\n\n return $http;\n\n\n function createShortMethods(names) {\n forEach(arguments, function(name) {\n $http[name] = function(url, config) {\n return $http(extend({}, config || {}, {\n method: name,\n url: url\n }));\n };\n });\n }\n\n\n function createShortMethodsWithData(name) {\n forEach(arguments, function(name) {\n $http[name] = function(url, data, config) {\n return $http(extend({}, config || {}, {\n method: name,\n url: url,\n data: data\n }));\n };\n });\n }\n\n\n /**\n * Makes the request.\n *\n * !!! ACCESSES CLOSURE VARS:\n * $httpBackend, defaults, $log, $rootScope, defaultCache, $http.pendingRequests\n */\n function sendReq(config, reqData) {\n var deferred = $q.defer(),\n promise = deferred.promise,\n cache,\n cachedResp,\n reqHeaders = config.headers,\n isJsonp = lowercase(config.method) === 'jsonp',\n url = config.url;\n\n if (isJsonp) {\n // JSONP is a pretty sensitive operation where we're allowing a script to have full access to\n // our DOM and JS space. So we require that the URL satisfies SCE.RESOURCE_URL.\n url = $sce.getTrustedResourceUrl(url);\n } else if (!isString(url)) {\n // If it is not a string then the URL must be a $sce trusted object\n url = $sce.valueOf(url);\n }\n\n url = buildUrl(url, config.paramSerializer(config.params));\n\n if (isJsonp) {\n // Check the url and add the JSONP callback placeholder\n url = sanitizeJsonpCallbackParam(url, config.jsonpCallbackParam);\n }\n\n $http.pendingRequests.push(config);\n promise.then(removePendingReq, removePendingReq);\n\n if ((config.cache || defaults.cache) && config.cache !== false &&\n (config.method === 'GET' || config.method === 'JSONP')) {\n cache = isObject(config.cache) ? config.cache\n : isObject(defaults.cache) ? defaults.cache\n : defaultCache;\n }\n\n if (cache) {\n cachedResp = cache.get(url);\n if (isDefined(cachedResp)) {\n if (isPromiseLike(cachedResp)) {\n // cached request has already been sent, but there is no response yet\n cachedResp.then(resolvePromiseWithResult, resolvePromiseWithResult);\n } else {\n // serving from cache\n if (isArray(cachedResp)) {\n resolvePromise(cachedResp[1], cachedResp[0], shallowCopy(cachedResp[2]), cachedResp[3]);\n } else {\n resolvePromise(cachedResp, 200, {}, 'OK');\n }\n }\n } else {\n // put the promise for the non-transformed response into cache as a placeholder\n cache.put(url, promise);\n }\n }\n\n\n // if we won't have the response in cache, set the xsrf headers and\n // send the request to the backend\n if (isUndefined(cachedResp)) {\n var xsrfValue = urlIsSameOrigin(config.url)\n ? $$cookieReader()[config.xsrfCookieName || defaults.xsrfCookieName]\n : undefined;\n if (xsrfValue) {\n reqHeaders[(config.xsrfHeaderName || defaults.xsrfHeaderName)] = xsrfValue;\n }\n\n $httpBackend(config.method, url, reqData, done, reqHeaders, config.timeout,\n config.withCredentials, config.responseType,\n createApplyHandlers(config.eventHandlers),\n createApplyHandlers(config.uploadEventHandlers));\n }\n\n return promise;\n\n function createApplyHandlers(eventHandlers) {\n if (eventHandlers) {\n var applyHandlers = {};\n forEach(eventHandlers, function(eventHandler, key) {\n applyHandlers[key] = function(event) {\n if (useApplyAsync) {\n $rootScope.$applyAsync(callEventHandler);\n } else if ($rootScope.$$phase) {\n callEventHandler();\n } else {\n $rootScope.$apply(callEventHandler);\n }\n\n function callEventHandler() {\n eventHandler(event);\n }\n };\n });\n return applyHandlers;\n }\n }\n\n\n /**\n * Callback registered to $httpBackend():\n * - caches the response if desired\n * - resolves the raw $http promise\n * - calls $apply\n */\n function done(status, response, headersString, statusText) {\n if (cache) {\n if (isSuccess(status)) {\n cache.put(url, [status, response, parseHeaders(headersString), statusText]);\n } else {\n // remove promise from the cache\n cache.remove(url);\n }\n }\n\n function resolveHttpPromise() {\n resolvePromise(response, status, headersString, statusText);\n }\n\n if (useApplyAsync) {\n $rootScope.$applyAsync(resolveHttpPromise);\n } else {\n resolveHttpPromise();\n if (!$rootScope.$$phase) $rootScope.$apply();\n }\n }\n\n\n /**\n * Resolves the raw $http promise.\n */\n function resolvePromise(response, status, headers, statusText) {\n //status: HTTP response status code, 0, -1 (aborted by timeout / promise)\n status = status >= -1 ? status : 0;\n\n (isSuccess(status) ? deferred.resolve : deferred.reject)({\n data: response,\n status: status,\n headers: headersGetter(headers),\n config: config,\n statusText: statusText\n });\n }\n\n function resolvePromiseWithResult(result) {\n resolvePromise(result.data, result.status, shallowCopy(result.headers()), result.statusText);\n }\n\n function removePendingReq() {\n var idx = $http.pendingRequests.indexOf(config);\n if (idx !== -1) $http.pendingRequests.splice(idx, 1);\n }\n }\n\n\n function buildUrl(url, serializedParams) {\n if (serializedParams.length > 0) {\n url += ((url.indexOf('?') === -1) ? '?' : '&') + serializedParams;\n }\n return url;\n }\n\n function sanitizeJsonpCallbackParam(url, key) {\n if (/[&?][^=]+=JSON_CALLBACK/.test(url)) {\n // Throw if the url already contains a reference to JSON_CALLBACK\n throw $httpMinErr('badjsonp', 'Illegal use of JSON_CALLBACK in url, \"{0}\"', url);\n }\n\n var callbackParamRegex = new RegExp('[&?]' + key + '=');\n if (callbackParamRegex.test(url)) {\n // Throw if the callback param was already provided\n throw $httpMinErr('badjsonp', 'Illegal use of callback param, \"{0}\", in url, \"{1}\"', key, url);\n }\n\n // Add in the JSON_CALLBACK callback param value\n url += ((url.indexOf('?') === -1) ? '?' : '&') + key + '=JSON_CALLBACK';\n\n return url;\n }\n }];\n}\n\n/**\n * @ngdoc service\n * @name $xhrFactory\n * @this\n *\n * @description\n * Factory function used to create XMLHttpRequest objects.\n *\n * Replace or decorate this service to create your own custom XMLHttpRequest objects.\n *\n * ```\n * angular.module('myApp', [])\n * .factory('$xhrFactory', function() {\n * return function createXhr(method, url) {\n * return new window.XMLHttpRequest({mozSystem: true});\n * };\n * });\n * ```\n *\n * @param {string} method HTTP method of the request (GET, POST, PUT, ..)\n * @param {string} url URL of the request.\n */\nfunction $xhrFactoryProvider() {\n this.$get = function() {\n return function createXhr() {\n return new window.XMLHttpRequest();\n };\n };\n}\n\n/**\n * @ngdoc service\n * @name $httpBackend\n * @requires $jsonpCallbacks\n * @requires $document\n * @requires $xhrFactory\n * @this\n *\n * @description\n * HTTP backend used by the {@link ng.$http service} that delegates to\n * XMLHttpRequest object or JSONP and deals with browser incompatibilities.\n *\n * You should never need to use this service directly, instead use the higher-level abstractions:\n * {@link ng.$http $http} or {@link ngResource.$resource $resource}.\n *\n * During testing this implementation is swapped with {@link ngMock.$httpBackend mock\n * $httpBackend} which can be trained with responses.\n */\nfunction $HttpBackendProvider() {\n this.$get = ['$browser', '$jsonpCallbacks', '$document', '$xhrFactory', function($browser, $jsonpCallbacks, $document, $xhrFactory) {\n return createHttpBackend($browser, $xhrFactory, $browser.defer, $jsonpCallbacks, $document[0]);\n }];\n}\n\nfunction createHttpBackend($browser, createXhr, $browserDefer, callbacks, rawDocument) {\n // TODO(vojta): fix the signature\n return function(method, url, post, callback, headers, timeout, withCredentials, responseType, eventHandlers, uploadEventHandlers) {\n url = url || $browser.url();\n\n if (lowercase(method) === 'jsonp') {\n var callbackPath = callbacks.createCallback(url);\n var jsonpDone = jsonpReq(url, callbackPath, function(status, text) {\n // jsonpReq only ever sets status to 200 (OK), 404 (ERROR) or -1 (WAITING)\n var response = (status === 200) && callbacks.getResponse(callbackPath);\n completeRequest(callback, status, response, '', text);\n callbacks.removeCallback(callbackPath);\n });\n } else {\n\n var xhr = createXhr(method, url);\n\n xhr.open(method, url, true);\n forEach(headers, function(value, key) {\n if (isDefined(value)) {\n xhr.setRequestHeader(key, value);\n }\n });\n\n xhr.onload = function requestLoaded() {\n var statusText = xhr.statusText || '';\n\n // responseText is the old-school way of retrieving response (supported by IE9)\n // response/responseType properties were introduced in XHR Level2 spec (supported by IE10)\n var response = ('response' in xhr) ? xhr.response : xhr.responseText;\n\n // normalize IE9 bug (http://bugs.jquery.com/ticket/1450)\n var status = xhr.status === 1223 ? 204 : xhr.status;\n\n // fix status code when it is 0 (0 status is undocumented).\n // Occurs when accessing file resources or on Android 4.1 stock browser\n // while retrieving files from application cache.\n if (status === 0) {\n status = response ? 200 : urlResolve(url).protocol === 'file' ? 404 : 0;\n }\n\n completeRequest(callback,\n status,\n response,\n xhr.getAllResponseHeaders(),\n statusText);\n };\n\n var requestError = function() {\n // The response is always empty\n // See https://xhr.spec.whatwg.org/#request-error-steps and https://fetch.spec.whatwg.org/#concept-network-error\n completeRequest(callback, -1, null, null, '');\n };\n\n xhr.onerror = requestError;\n xhr.onabort = requestError;\n xhr.ontimeout = requestError;\n\n forEach(eventHandlers, function(value, key) {\n xhr.addEventListener(key, value);\n });\n\n forEach(uploadEventHandlers, function(value, key) {\n xhr.upload.addEventListener(key, value);\n });\n\n if (withCredentials) {\n xhr.withCredentials = true;\n }\n\n if (responseType) {\n try {\n xhr.responseType = responseType;\n } catch (e) {\n // WebKit added support for the json responseType value on 09/03/2013\n // https://bugs.webkit.org/show_bug.cgi?id=73648. Versions of Safari prior to 7 are\n // known to throw when setting the value \"json\" as the response type. Other older\n // browsers implementing the responseType\n //\n // The json response type can be ignored if not supported, because JSON payloads are\n // parsed on the client-side regardless.\n if (responseType !== 'json') {\n throw e;\n }\n }\n }\n\n xhr.send(isUndefined(post) ? null : post);\n }\n\n if (timeout > 0) {\n var timeoutId = $browserDefer(timeoutRequest, timeout);\n } else if (isPromiseLike(timeout)) {\n timeout.then(timeoutRequest);\n }\n\n\n function timeoutRequest() {\n if (jsonpDone) {\n jsonpDone();\n }\n if (xhr) {\n xhr.abort();\n }\n }\n\n function completeRequest(callback, status, response, headersString, statusText) {\n // cancel timeout and subsequent timeout promise resolution\n if (isDefined(timeoutId)) {\n $browserDefer.cancel(timeoutId);\n }\n jsonpDone = xhr = null;\n\n callback(status, response, headersString, statusText);\n }\n };\n\n function jsonpReq(url, callbackPath, done) {\n url = url.replace('JSON_CALLBACK', callbackPath);\n // we can't use jQuery/jqLite here because jQuery does crazy stuff with script elements, e.g.:\n // - fetches local scripts via XHR and evals them\n // - adds and immediately removes script elements from the document\n var script = rawDocument.createElement('script'), callback = null;\n script.type = 'text/javascript';\n script.src = url;\n script.async = true;\n\n callback = function(event) {\n script.removeEventListener('load', callback);\n script.removeEventListener('error', callback);\n rawDocument.body.removeChild(script);\n script = null;\n var status = -1;\n var text = 'unknown';\n\n if (event) {\n if (event.type === 'load' && !callbacks.wasCalled(callbackPath)) {\n event = { type: 'error' };\n }\n text = event.type;\n status = event.type === 'error' ? 404 : 200;\n }\n\n if (done) {\n done(status, text);\n }\n };\n\n script.addEventListener('load', callback);\n script.addEventListener('error', callback);\n rawDocument.body.appendChild(script);\n return callback;\n }\n}\n\nvar $interpolateMinErr = angular.$interpolateMinErr = minErr('$interpolate');\n$interpolateMinErr.throwNoconcat = function(text) {\n throw $interpolateMinErr('noconcat',\n 'Error while interpolating: {0}\\nStrict Contextual Escaping disallows ' +\n 'interpolations that concatenate multiple expressions when a trusted value is ' +\n 'required. See http://docs.angularjs.org/api/ng.$sce', text);\n};\n\n$interpolateMinErr.interr = function(text, err) {\n return $interpolateMinErr('interr', 'Can\\'t interpolate: {0}\\n{1}', text, err.toString());\n};\n\n/**\n * @ngdoc provider\n * @name $interpolateProvider\n * @this\n *\n * @description\n *\n * Used for configuring the interpolation markup. Defaults to `{{` and `}}`.\n *\n *
\n * This feature is sometimes used to mix different markup languages, e.g. to wrap an Angular\n * template within a Python Jinja template (or any other template language). Mixing templating\n * languages is **very dangerous**. The embedding template language will not safely escape Angular\n * expressions, so any user-controlled values in the template will cause Cross Site Scripting (XSS)\n * security bugs!\n *
\n *\n * @example\n\n\n\n
\n //demo.label//\n
\n
\n\n it('should interpolate binding with custom symbols', function() {\n expect(element(by.binding('demo.label')).getText()).toBe('This binding is brought you by // interpolation symbols.');\n });\n\n
\n */\nfunction $InterpolateProvider() {\n var startSymbol = '{{';\n var endSymbol = '}}';\n\n /**\n * @ngdoc method\n * @name $interpolateProvider#startSymbol\n * @description\n * Symbol to denote start of expression in the interpolated string. Defaults to `{{`.\n *\n * @param {string=} value new value to set the starting symbol to.\n * @returns {string|self} Returns the symbol when used as getter and self if used as setter.\n */\n this.startSymbol = function(value) {\n if (value) {\n startSymbol = value;\n return this;\n } else {\n return startSymbol;\n }\n };\n\n /**\n * @ngdoc method\n * @name $interpolateProvider#endSymbol\n * @description\n * Symbol to denote the end of expression in the interpolated string. Defaults to `}}`.\n *\n * @param {string=} value new value to set the ending symbol to.\n * @returns {string|self} Returns the symbol when used as getter and self if used as setter.\n */\n this.endSymbol = function(value) {\n if (value) {\n endSymbol = value;\n return this;\n } else {\n return endSymbol;\n }\n };\n\n\n this.$get = ['$parse', '$exceptionHandler', '$sce', function($parse, $exceptionHandler, $sce) {\n var startSymbolLength = startSymbol.length,\n endSymbolLength = endSymbol.length,\n escapedStartRegexp = new RegExp(startSymbol.replace(/./g, escape), 'g'),\n escapedEndRegexp = new RegExp(endSymbol.replace(/./g, escape), 'g');\n\n function escape(ch) {\n return '\\\\\\\\\\\\' + ch;\n }\n\n function unescapeText(text) {\n return text.replace(escapedStartRegexp, startSymbol).\n replace(escapedEndRegexp, endSymbol);\n }\n\n // TODO: this is the same as the constantWatchDelegate in parse.js\n function constantWatchDelegate(scope, listener, objectEquality, constantInterp) {\n var unwatch = scope.$watch(function constantInterpolateWatch(scope) {\n unwatch();\n return constantInterp(scope);\n }, listener, objectEquality);\n return unwatch;\n }\n\n /**\n * @ngdoc service\n * @name $interpolate\n * @kind function\n *\n * @requires $parse\n * @requires $sce\n *\n * @description\n *\n * Compiles a string with markup into an interpolation function. This service is used by the\n * HTML {@link ng.$compile $compile} service for data binding. See\n * {@link ng.$interpolateProvider $interpolateProvider} for configuring the\n * interpolation markup.\n *\n *\n * ```js\n * var $interpolate = ...; // injected\n * var exp = $interpolate('Hello {{name | uppercase}}!');\n * expect(exp({name:'Angular'})).toEqual('Hello ANGULAR!');\n * ```\n *\n * `$interpolate` takes an optional fourth argument, `allOrNothing`. If `allOrNothing` is\n * `true`, the interpolation function will return `undefined` unless all embedded expressions\n * evaluate to a value other than `undefined`.\n *\n * ```js\n * var $interpolate = ...; // injected\n * var context = {greeting: 'Hello', name: undefined };\n *\n * // default \"forgiving\" mode\n * var exp = $interpolate('{{greeting}} {{name}}!');\n * expect(exp(context)).toEqual('Hello !');\n *\n * // \"allOrNothing\" mode\n * exp = $interpolate('{{greeting}} {{name}}!', false, null, true);\n * expect(exp(context)).toBeUndefined();\n * context.name = 'Angular';\n * expect(exp(context)).toEqual('Hello Angular!');\n * ```\n *\n * `allOrNothing` is useful for interpolating URLs. `ngSrc` and `ngSrcset` use this behavior.\n *\n * #### Escaped Interpolation\n * $interpolate provides a mechanism for escaping interpolation markers. Start and end markers\n * can be escaped by preceding each of their characters with a REVERSE SOLIDUS U+005C (backslash).\n * It will be rendered as a regular start/end marker, and will not be interpreted as an expression\n * or binding.\n *\n * This enables web-servers to prevent script injection attacks and defacing attacks, to some\n * degree, while also enabling code examples to work without relying on the\n * {@link ng.directive:ngNonBindable ngNonBindable} directive.\n *\n * **For security purposes, it is strongly encouraged that web servers escape user-supplied data,\n * replacing angle brackets (<, >) with &lt; and &gt; respectively, and replacing all\n * interpolation start/end markers with their escaped counterparts.**\n *\n * Escaped interpolation markers are only replaced with the actual interpolation markers in rendered\n * output when the $interpolate service processes the text. So, for HTML elements interpolated\n * by {@link ng.$compile $compile}, or otherwise interpolated with the `mustHaveExpression` parameter\n * set to `true`, the interpolated text must contain an unescaped interpolation expression. As such,\n * this is typically useful only when user-data is used in rendering a template from the server, or\n * when otherwise untrusted data is used by a directive.\n *\n * \n * \n *
\n *

{{apptitle}}: \\{\\{ username = \"defaced value\"; \\}\\}\n *

\n *

{{username}} attempts to inject code which will deface the\n * application, but fails to accomplish their task, because the server has correctly\n * escaped the interpolation start/end markers with REVERSE SOLIDUS U+005C (backslash)\n * characters.

\n *

Instead, the result of the attempted script injection is visible, and can be removed\n * from the database by an administrator.

\n *
\n *
\n *
\n *\n * @knownIssue\n * It is currently not possible for an interpolated expression to contain the interpolation end\n * symbol. For example, `{{ '}}' }}` will be incorrectly interpreted as `{{ ' }}` + `' }}`, i.e.\n * an interpolated expression consisting of a single-quote (`'`) and the `' }}` string.\n *\n * @knownIssue\n * All directives and components must use the standard `{{` `}}` interpolation symbols\n * in their templates. If you change the application interpolation symbols the {@link $compile}\n * service will attempt to denormalize the standard symbols to the custom symbols.\n * The denormalization process is not clever enough to know not to replace instances of the standard\n * symbols where they would not normally be treated as interpolation symbols. For example in the following\n * code snippet the closing braces of the literal object will get incorrectly denormalized:\n *\n * ```\n *
\n * ```\n *\n * See https://github.com/angular/angular.js/pull/14610#issuecomment-219401099 for more information.\n *\n * @param {string} text The text with markup to interpolate.\n * @param {boolean=} mustHaveExpression if set to true then the interpolation string must have\n * embedded expression in order to return an interpolation function. Strings with no\n * embedded expression will return null for the interpolation function.\n * @param {string=} trustedContext when provided, the returned function passes the interpolated\n * result through {@link ng.$sce#getTrusted $sce.getTrusted(interpolatedResult,\n * trustedContext)} before returning it. Refer to the {@link ng.$sce $sce} service that\n * provides Strict Contextual Escaping for details.\n * @param {boolean=} allOrNothing if `true`, then the returned function returns undefined\n * unless all embedded expressions evaluate to a value other than `undefined`.\n * @returns {function(context)} an interpolation function which is used to compute the\n * interpolated string. The function has these parameters:\n *\n * - `context`: evaluation context for all expressions embedded in the interpolated text\n */\n function $interpolate(text, mustHaveExpression, trustedContext, allOrNothing) {\n // Provide a quick exit and simplified result function for text with no interpolation\n if (!text.length || text.indexOf(startSymbol) === -1) {\n var constantInterp;\n if (!mustHaveExpression) {\n var unescapedText = unescapeText(text);\n constantInterp = valueFn(unescapedText);\n constantInterp.exp = text;\n constantInterp.expressions = [];\n constantInterp.$$watchDelegate = constantWatchDelegate;\n }\n return constantInterp;\n }\n\n allOrNothing = !!allOrNothing;\n var startIndex,\n endIndex,\n index = 0,\n expressions = [],\n parseFns = [],\n textLength = text.length,\n exp,\n concat = [],\n expressionPositions = [];\n\n while (index < textLength) {\n if (((startIndex = text.indexOf(startSymbol, index)) !== -1) &&\n ((endIndex = text.indexOf(endSymbol, startIndex + startSymbolLength)) !== -1)) {\n if (index !== startIndex) {\n concat.push(unescapeText(text.substring(index, startIndex)));\n }\n exp = text.substring(startIndex + startSymbolLength, endIndex);\n expressions.push(exp);\n parseFns.push($parse(exp, parseStringifyInterceptor));\n index = endIndex + endSymbolLength;\n expressionPositions.push(concat.length);\n concat.push('');\n } else {\n // we did not find an interpolation, so we have to add the remainder to the separators array\n if (index !== textLength) {\n concat.push(unescapeText(text.substring(index)));\n }\n break;\n }\n }\n\n // Concatenating expressions makes it hard to reason about whether some combination of\n // concatenated values are unsafe to use and could easily lead to XSS. By requiring that a\n // single expression be used for iframe[src], object[src], etc., we ensure that the value\n // that's used is assigned or constructed by some JS code somewhere that is more testable or\n // make it obvious that you bound the value to some user controlled value. This helps reduce\n // the load when auditing for XSS issues.\n if (trustedContext && concat.length > 1) {\n $interpolateMinErr.throwNoconcat(text);\n }\n\n if (!mustHaveExpression || expressions.length) {\n var compute = function(values) {\n for (var i = 0, ii = expressions.length; i < ii; i++) {\n if (allOrNothing && isUndefined(values[i])) return;\n concat[expressionPositions[i]] = values[i];\n }\n return concat.join('');\n };\n\n var getValue = function(value) {\n return trustedContext ?\n $sce.getTrusted(trustedContext, value) :\n $sce.valueOf(value);\n };\n\n return extend(function interpolationFn(context) {\n var i = 0;\n var ii = expressions.length;\n var values = new Array(ii);\n\n try {\n for (; i < ii; i++) {\n values[i] = parseFns[i](context);\n }\n\n return compute(values);\n } catch (err) {\n $exceptionHandler($interpolateMinErr.interr(text, err));\n }\n\n }, {\n // all of these properties are undocumented for now\n exp: text, //just for compatibility with regular watchers created via $watch\n expressions: expressions,\n $$watchDelegate: function(scope, listener) {\n var lastValue;\n return scope.$watchGroup(parseFns, /** @this */ function interpolateFnWatcher(values, oldValues) {\n var currValue = compute(values);\n if (isFunction(listener)) {\n listener.call(this, currValue, values !== oldValues ? lastValue : currValue, scope);\n }\n lastValue = currValue;\n });\n }\n });\n }\n\n function parseStringifyInterceptor(value) {\n try {\n value = getValue(value);\n return allOrNothing && !isDefined(value) ? value : stringify(value);\n } catch (err) {\n $exceptionHandler($interpolateMinErr.interr(text, err));\n }\n }\n }\n\n\n /**\n * @ngdoc method\n * @name $interpolate#startSymbol\n * @description\n * Symbol to denote the start of expression in the interpolated string. Defaults to `{{`.\n *\n * Use {@link ng.$interpolateProvider#startSymbol `$interpolateProvider.startSymbol`} to change\n * the symbol.\n *\n * @returns {string} start symbol.\n */\n $interpolate.startSymbol = function() {\n return startSymbol;\n };\n\n\n /**\n * @ngdoc method\n * @name $interpolate#endSymbol\n * @description\n * Symbol to denote the end of expression in the interpolated string. Defaults to `}}`.\n *\n * Use {@link ng.$interpolateProvider#endSymbol `$interpolateProvider.endSymbol`} to change\n * the symbol.\n *\n * @returns {string} end symbol.\n */\n $interpolate.endSymbol = function() {\n return endSymbol;\n };\n\n return $interpolate;\n }];\n}\n\n/** @this */\nfunction $IntervalProvider() {\n this.$get = ['$rootScope', '$window', '$q', '$$q', '$browser',\n function($rootScope, $window, $q, $$q, $browser) {\n var intervals = {};\n\n\n /**\n * @ngdoc service\n * @name $interval\n *\n * @description\n * Angular's wrapper for `window.setInterval`. The `fn` function is executed every `delay`\n * milliseconds.\n *\n * The return value of registering an interval function is a promise. This promise will be\n * notified upon each tick of the interval, and will be resolved after `count` iterations, or\n * run indefinitely if `count` is not defined. The value of the notification will be the\n * number of iterations that have run.\n * To cancel an interval, call `$interval.cancel(promise)`.\n *\n * In tests you can use {@link ngMock.$interval#flush `$interval.flush(millis)`} to\n * move forward by `millis` milliseconds and trigger any functions scheduled to run in that\n * time.\n *\n *
\n * **Note**: Intervals created by this service must be explicitly destroyed when you are finished\n * with them. In particular they are not automatically destroyed when a controller's scope or a\n * directive's element are destroyed.\n * You should take this into consideration and make sure to always cancel the interval at the\n * appropriate moment. See the example below for more details on how and when to do this.\n *
\n *\n * @param {function()} fn A function that should be called repeatedly.\n * @param {number} delay Number of milliseconds between each function call.\n * @param {number=} [count=0] Number of times to repeat. If not set, or 0, will repeat\n * indefinitely.\n * @param {boolean=} [invokeApply=true] If set to `false` skips model dirty checking, otherwise\n * will invoke `fn` within the {@link ng.$rootScope.Scope#$apply $apply} block.\n * @param {...*=} Pass additional parameters to the executed function.\n * @returns {promise} A promise which will be notified on each iteration.\n *\n * @example\n * \n * \n * \n *\n *
\n *
\n *
\n * Current time is: \n *
\n * Blood 1 : {{blood_1}}\n * Blood 2 : {{blood_2}}\n * \n * \n * \n *
\n *
\n *\n *
\n *
\n */\n function interval(fn, delay, count, invokeApply) {\n var hasParams = arguments.length > 4,\n args = hasParams ? sliceArgs(arguments, 4) : [],\n setInterval = $window.setInterval,\n clearInterval = $window.clearInterval,\n iteration = 0,\n skipApply = (isDefined(invokeApply) && !invokeApply),\n deferred = (skipApply ? $$q : $q).defer(),\n promise = deferred.promise;\n\n count = isDefined(count) ? count : 0;\n\n promise.$$intervalId = setInterval(function tick() {\n if (skipApply) {\n $browser.defer(callback);\n } else {\n $rootScope.$evalAsync(callback);\n }\n deferred.notify(iteration++);\n\n if (count > 0 && iteration >= count) {\n deferred.resolve(iteration);\n clearInterval(promise.$$intervalId);\n delete intervals[promise.$$intervalId];\n }\n\n if (!skipApply) $rootScope.$apply();\n\n }, delay);\n\n intervals[promise.$$intervalId] = deferred;\n\n return promise;\n\n function callback() {\n if (!hasParams) {\n fn(iteration);\n } else {\n fn.apply(null, args);\n }\n }\n }\n\n\n /**\n * @ngdoc method\n * @name $interval#cancel\n *\n * @description\n * Cancels a task associated with the `promise`.\n *\n * @param {Promise=} promise returned by the `$interval` function.\n * @returns {boolean} Returns `true` if the task was successfully canceled.\n */\n interval.cancel = function(promise) {\n if (promise && promise.$$intervalId in intervals) {\n // Interval cancels should not report as unhandled promise.\n intervals[promise.$$intervalId].promise.catch(noop);\n intervals[promise.$$intervalId].reject('canceled');\n $window.clearInterval(promise.$$intervalId);\n delete intervals[promise.$$intervalId];\n return true;\n }\n return false;\n };\n\n return interval;\n }];\n}\n\n/**\n * @ngdoc service\n * @name $jsonpCallbacks\n * @requires $window\n * @description\n * This service handles the lifecycle of callbacks to handle JSONP requests.\n * Override this service if you wish to customise where the callbacks are stored and\n * how they vary compared to the requested url.\n */\nvar $jsonpCallbacksProvider = /** @this */ function() {\n this.$get = ['$window', function($window) {\n var callbacks = $window.angular.callbacks;\n var callbackMap = {};\n\n function createCallback(callbackId) {\n var callback = function(data) {\n callback.data = data;\n callback.called = true;\n };\n callback.id = callbackId;\n return callback;\n }\n\n return {\n /**\n * @ngdoc method\n * @name $jsonpCallbacks#createCallback\n * @param {string} url the url of the JSONP request\n * @returns {string} the callback path to send to the server as part of the JSONP request\n * @description\n * {@link $httpBackend} calls this method to create a callback and get hold of the path to the callback\n * to pass to the server, which will be used to call the callback with its payload in the JSONP response.\n */\n createCallback: function(url) {\n var callbackId = '_' + (callbacks.$$counter++).toString(36);\n var callbackPath = 'angular.callbacks.' + callbackId;\n var callback = createCallback(callbackId);\n callbackMap[callbackPath] = callbacks[callbackId] = callback;\n return callbackPath;\n },\n /**\n * @ngdoc method\n * @name $jsonpCallbacks#wasCalled\n * @param {string} callbackPath the path to the callback that was sent in the JSONP request\n * @returns {boolean} whether the callback has been called, as a result of the JSONP response\n * @description\n * {@link $httpBackend} calls this method to find out whether the JSONP response actually called the\n * callback that was passed in the request.\n */\n wasCalled: function(callbackPath) {\n return callbackMap[callbackPath].called;\n },\n /**\n * @ngdoc method\n * @name $jsonpCallbacks#getResponse\n * @param {string} callbackPath the path to the callback that was sent in the JSONP request\n * @returns {*} the data received from the response via the registered callback\n * @description\n * {@link $httpBackend} calls this method to get hold of the data that was provided to the callback\n * in the JSONP response.\n */\n getResponse: function(callbackPath) {\n return callbackMap[callbackPath].data;\n },\n /**\n * @ngdoc method\n * @name $jsonpCallbacks#removeCallback\n * @param {string} callbackPath the path to the callback that was sent in the JSONP request\n * @description\n * {@link $httpBackend} calls this method to remove the callback after the JSONP request has\n * completed or timed-out.\n */\n removeCallback: function(callbackPath) {\n var callback = callbackMap[callbackPath];\n delete callbacks[callback.id];\n delete callbackMap[callbackPath];\n }\n };\n }];\n};\n\n/**\n * @ngdoc service\n * @name $locale\n *\n * @description\n * $locale service provides localization rules for various Angular components. As of right now the\n * only public api is:\n *\n * * `id` – `{string}` – locale id formatted as `languageId-countryId` (e.g. `en-us`)\n */\n\nvar PATH_MATCH = /^([^?#]*)(\\?([^#]*))?(#(.*))?$/,\n DEFAULT_PORTS = {'http': 80, 'https': 443, 'ftp': 21};\nvar $locationMinErr = minErr('$location');\n\n\n/**\n * Encode path using encodeUriSegment, ignoring forward slashes\n *\n * @param {string} path Path to encode\n * @returns {string}\n */\nfunction encodePath(path) {\n var segments = path.split('/'),\n i = segments.length;\n\n while (i--) {\n segments[i] = encodeUriSegment(segments[i]);\n }\n\n return segments.join('/');\n}\n\nfunction parseAbsoluteUrl(absoluteUrl, locationObj) {\n var parsedUrl = urlResolve(absoluteUrl);\n\n locationObj.$$protocol = parsedUrl.protocol;\n locationObj.$$host = parsedUrl.hostname;\n locationObj.$$port = toInt(parsedUrl.port) || DEFAULT_PORTS[parsedUrl.protocol] || null;\n}\n\nvar DOUBLE_SLASH_REGEX = /^\\s*[\\\\/]{2,}/;\nfunction parseAppUrl(url, locationObj) {\n\n if (DOUBLE_SLASH_REGEX.test(url)) {\n throw $locationMinErr('badpath', 'Invalid url \"{0}\".', url);\n }\n\n var prefixed = (url.charAt(0) !== '/');\n if (prefixed) {\n url = '/' + url;\n }\n var match = urlResolve(url);\n locationObj.$$path = decodeURIComponent(prefixed && match.pathname.charAt(0) === '/' ?\n match.pathname.substring(1) : match.pathname);\n locationObj.$$search = parseKeyValue(match.search);\n locationObj.$$hash = decodeURIComponent(match.hash);\n\n // make sure path starts with '/';\n if (locationObj.$$path && locationObj.$$path.charAt(0) !== '/') {\n locationObj.$$path = '/' + locationObj.$$path;\n }\n}\n\nfunction startsWith(str, search) {\n return str.slice(0, search.length) === search;\n}\n\n/**\n *\n * @param {string} base\n * @param {string} url\n * @returns {string} returns text from `url` after `base` or `undefined` if it does not begin with\n * the expected string.\n */\nfunction stripBaseUrl(base, url) {\n if (startsWith(url, base)) {\n return url.substr(base.length);\n }\n}\n\n\nfunction stripHash(url) {\n var index = url.indexOf('#');\n return index === -1 ? url : url.substr(0, index);\n}\n\nfunction trimEmptyHash(url) {\n return url.replace(/(#.+)|#$/, '$1');\n}\n\n\nfunction stripFile(url) {\n return url.substr(0, stripHash(url).lastIndexOf('/') + 1);\n}\n\n/* return the server only (scheme://host:port) */\nfunction serverBase(url) {\n return url.substring(0, url.indexOf('/', url.indexOf('//') + 2));\n}\n\n\n/**\n * LocationHtml5Url represents a URL\n * This object is exposed as $location service when HTML5 mode is enabled and supported\n *\n * @constructor\n * @param {string} appBase application base URL\n * @param {string} appBaseNoFile application base URL stripped of any filename\n * @param {string} basePrefix URL path prefix\n */\nfunction LocationHtml5Url(appBase, appBaseNoFile, basePrefix) {\n this.$$html5 = true;\n basePrefix = basePrefix || '';\n parseAbsoluteUrl(appBase, this);\n\n\n /**\n * Parse given HTML5 (regular) URL string into properties\n * @param {string} url HTML5 URL\n * @private\n */\n this.$$parse = function(url) {\n var pathUrl = stripBaseUrl(appBaseNoFile, url);\n if (!isString(pathUrl)) {\n throw $locationMinErr('ipthprfx', 'Invalid url \"{0}\", missing path prefix \"{1}\".', url,\n appBaseNoFile);\n }\n\n parseAppUrl(pathUrl, this);\n\n if (!this.$$path) {\n this.$$path = '/';\n }\n\n this.$$compose();\n };\n\n /**\n * Compose url and update `absUrl` property\n * @private\n */\n this.$$compose = function() {\n var search = toKeyValue(this.$$search),\n hash = this.$$hash ? '#' + encodeUriSegment(this.$$hash) : '';\n\n this.$$url = encodePath(this.$$path) + (search ? '?' + search : '') + hash;\n this.$$absUrl = appBaseNoFile + this.$$url.substr(1); // first char is always '/'\n };\n\n this.$$parseLinkUrl = function(url, relHref) {\n if (relHref && relHref[0] === '#') {\n // special case for links to hash fragments:\n // keep the old url and only replace the hash fragment\n this.hash(relHref.slice(1));\n return true;\n }\n var appUrl, prevAppUrl;\n var rewrittenUrl;\n\n\n if (isDefined(appUrl = stripBaseUrl(appBase, url))) {\n prevAppUrl = appUrl;\n if (basePrefix && isDefined(appUrl = stripBaseUrl(basePrefix, appUrl))) {\n rewrittenUrl = appBaseNoFile + (stripBaseUrl('/', appUrl) || appUrl);\n } else {\n rewrittenUrl = appBase + prevAppUrl;\n }\n } else if (isDefined(appUrl = stripBaseUrl(appBaseNoFile, url))) {\n rewrittenUrl = appBaseNoFile + appUrl;\n } else if (appBaseNoFile === url + '/') {\n rewrittenUrl = appBaseNoFile;\n }\n if (rewrittenUrl) {\n this.$$parse(rewrittenUrl);\n }\n return !!rewrittenUrl;\n };\n}\n\n\n/**\n * LocationHashbangUrl represents URL\n * This object is exposed as $location service when developer doesn't opt into html5 mode.\n * It also serves as the base class for html5 mode fallback on legacy browsers.\n *\n * @constructor\n * @param {string} appBase application base URL\n * @param {string} appBaseNoFile application base URL stripped of any filename\n * @param {string} hashPrefix hashbang prefix\n */\nfunction LocationHashbangUrl(appBase, appBaseNoFile, hashPrefix) {\n\n parseAbsoluteUrl(appBase, this);\n\n\n /**\n * Parse given hashbang URL into properties\n * @param {string} url Hashbang URL\n * @private\n */\n this.$$parse = function(url) {\n var withoutBaseUrl = stripBaseUrl(appBase, url) || stripBaseUrl(appBaseNoFile, url);\n var withoutHashUrl;\n\n if (!isUndefined(withoutBaseUrl) && withoutBaseUrl.charAt(0) === '#') {\n\n // The rest of the URL starts with a hash so we have\n // got either a hashbang path or a plain hash fragment\n withoutHashUrl = stripBaseUrl(hashPrefix, withoutBaseUrl);\n if (isUndefined(withoutHashUrl)) {\n // There was no hashbang prefix so we just have a hash fragment\n withoutHashUrl = withoutBaseUrl;\n }\n\n } else {\n // There was no hashbang path nor hash fragment:\n // If we are in HTML5 mode we use what is left as the path;\n // Otherwise we ignore what is left\n if (this.$$html5) {\n withoutHashUrl = withoutBaseUrl;\n } else {\n withoutHashUrl = '';\n if (isUndefined(withoutBaseUrl)) {\n appBase = url;\n this.replace();\n }\n }\n }\n\n parseAppUrl(withoutHashUrl, this);\n\n this.$$path = removeWindowsDriveName(this.$$path, withoutHashUrl, appBase);\n\n this.$$compose();\n\n /*\n * In Windows, on an anchor node on documents loaded from\n * the filesystem, the browser will return a pathname\n * prefixed with the drive name ('/C:/path') when a\n * pathname without a drive is set:\n * * a.setAttribute('href', '/foo')\n * * a.pathname === '/C:/foo' //true\n *\n * Inside of Angular, we're always using pathnames that\n * do not include drive names for routing.\n */\n function removeWindowsDriveName(path, url, base) {\n /*\n Matches paths for file protocol on windows,\n such as /C:/foo/bar, and captures only /foo/bar.\n */\n var windowsFilePathExp = /^\\/[A-Z]:(\\/.*)/;\n\n var firstPathSegmentMatch;\n\n //Get the relative path from the input URL.\n if (startsWith(url, base)) {\n url = url.replace(base, '');\n }\n\n // The input URL intentionally contains a first path segment that ends with a colon.\n if (windowsFilePathExp.exec(url)) {\n return path;\n }\n\n firstPathSegmentMatch = windowsFilePathExp.exec(path);\n return firstPathSegmentMatch ? firstPathSegmentMatch[1] : path;\n }\n };\n\n /**\n * Compose hashbang URL and update `absUrl` property\n * @private\n */\n this.$$compose = function() {\n var search = toKeyValue(this.$$search),\n hash = this.$$hash ? '#' + encodeUriSegment(this.$$hash) : '';\n\n this.$$url = encodePath(this.$$path) + (search ? '?' + search : '') + hash;\n this.$$absUrl = appBase + (this.$$url ? hashPrefix + this.$$url : '');\n };\n\n this.$$parseLinkUrl = function(url, relHref) {\n if (stripHash(appBase) === stripHash(url)) {\n this.$$parse(url);\n return true;\n }\n return false;\n };\n}\n\n\n/**\n * LocationHashbangUrl represents URL\n * This object is exposed as $location service when html5 history api is enabled but the browser\n * does not support it.\n *\n * @constructor\n * @param {string} appBase application base URL\n * @param {string} appBaseNoFile application base URL stripped of any filename\n * @param {string} hashPrefix hashbang prefix\n */\nfunction LocationHashbangInHtml5Url(appBase, appBaseNoFile, hashPrefix) {\n this.$$html5 = true;\n LocationHashbangUrl.apply(this, arguments);\n\n this.$$parseLinkUrl = function(url, relHref) {\n if (relHref && relHref[0] === '#') {\n // special case for links to hash fragments:\n // keep the old url and only replace the hash fragment\n this.hash(relHref.slice(1));\n return true;\n }\n\n var rewrittenUrl;\n var appUrl;\n\n if (appBase === stripHash(url)) {\n rewrittenUrl = url;\n } else if ((appUrl = stripBaseUrl(appBaseNoFile, url))) {\n rewrittenUrl = appBase + hashPrefix + appUrl;\n } else if (appBaseNoFile === url + '/') {\n rewrittenUrl = appBaseNoFile;\n }\n if (rewrittenUrl) {\n this.$$parse(rewrittenUrl);\n }\n return !!rewrittenUrl;\n };\n\n this.$$compose = function() {\n var search = toKeyValue(this.$$search),\n hash = this.$$hash ? '#' + encodeUriSegment(this.$$hash) : '';\n\n this.$$url = encodePath(this.$$path) + (search ? '?' + search : '') + hash;\n // include hashPrefix in $$absUrl when $$url is empty so IE9 does not reload page because of removal of '#'\n this.$$absUrl = appBase + hashPrefix + this.$$url;\n };\n\n}\n\n\nvar locationPrototype = {\n\n /**\n * Ensure absolute URL is initialized.\n * @private\n */\n $$absUrl:'',\n\n /**\n * Are we in html5 mode?\n * @private\n */\n $$html5: false,\n\n /**\n * Has any change been replacing?\n * @private\n */\n $$replace: false,\n\n /**\n * @ngdoc method\n * @name $location#absUrl\n *\n * @description\n * This method is getter only.\n *\n * Return full URL representation with all segments encoded according to rules specified in\n * [RFC 3986](http://www.ietf.org/rfc/rfc3986.txt).\n *\n *\n * ```js\n * // given URL http://example.com/#/some/path?foo=bar&baz=xoxo\n * var absUrl = $location.absUrl();\n * // => \"http://example.com/#/some/path?foo=bar&baz=xoxo\"\n * ```\n *\n * @return {string} full URL\n */\n absUrl: locationGetter('$$absUrl'),\n\n /**\n * @ngdoc method\n * @name $location#url\n *\n * @description\n * This method is getter / setter.\n *\n * Return URL (e.g. `/path?a=b#hash`) when called without any parameter.\n *\n * Change path, search and hash, when called with parameter and return `$location`.\n *\n *\n * ```js\n * // given URL http://example.com/#/some/path?foo=bar&baz=xoxo\n * var url = $location.url();\n * // => \"/some/path?foo=bar&baz=xoxo\"\n * ```\n *\n * @param {string=} url New URL without base prefix (e.g. `/path?a=b#hash`)\n * @return {string} url\n */\n url: function(url) {\n if (isUndefined(url)) {\n return this.$$url;\n }\n\n var match = PATH_MATCH.exec(url);\n if (match[1] || url === '') this.path(decodeURIComponent(match[1]));\n if (match[2] || match[1] || url === '') this.search(match[3] || '');\n this.hash(match[5] || '');\n\n return this;\n },\n\n /**\n * @ngdoc method\n * @name $location#protocol\n *\n * @description\n * This method is getter only.\n *\n * Return protocol of current URL.\n *\n *\n * ```js\n * // given URL http://example.com/#/some/path?foo=bar&baz=xoxo\n * var protocol = $location.protocol();\n * // => \"http\"\n * ```\n *\n * @return {string} protocol of current URL\n */\n protocol: locationGetter('$$protocol'),\n\n /**\n * @ngdoc method\n * @name $location#host\n *\n * @description\n * This method is getter only.\n *\n * Return host of current URL.\n *\n * Note: compared to the non-angular version `location.host` which returns `hostname:port`, this returns the `hostname` portion only.\n *\n *\n * ```js\n * // given URL http://example.com/#/some/path?foo=bar&baz=xoxo\n * var host = $location.host();\n * // => \"example.com\"\n *\n * // given URL http://user:password@example.com:8080/#/some/path?foo=bar&baz=xoxo\n * host = $location.host();\n * // => \"example.com\"\n * host = location.host;\n * // => \"example.com:8080\"\n * ```\n *\n * @return {string} host of current URL.\n */\n host: locationGetter('$$host'),\n\n /**\n * @ngdoc method\n * @name $location#port\n *\n * @description\n * This method is getter only.\n *\n * Return port of current URL.\n *\n *\n * ```js\n * // given URL http://example.com/#/some/path?foo=bar&baz=xoxo\n * var port = $location.port();\n * // => 80\n * ```\n *\n * @return {Number} port\n */\n port: locationGetter('$$port'),\n\n /**\n * @ngdoc method\n * @name $location#path\n *\n * @description\n * This method is getter / setter.\n *\n * Return path of current URL when called without any parameter.\n *\n * Change path when called with parameter and return `$location`.\n *\n * Note: Path should always begin with forward slash (/), this method will add the forward slash\n * if it is missing.\n *\n *\n * ```js\n * // given URL http://example.com/#/some/path?foo=bar&baz=xoxo\n * var path = $location.path();\n * // => \"/some/path\"\n * ```\n *\n * @param {(string|number)=} path New path\n * @return {(string|object)} path if called with no parameters, or `$location` if called with a parameter\n */\n path: locationGetterSetter('$$path', function(path) {\n path = path !== null ? path.toString() : '';\n return path.charAt(0) === '/' ? path : '/' + path;\n }),\n\n /**\n * @ngdoc method\n * @name $location#search\n *\n * @description\n * This method is getter / setter.\n *\n * Return search part (as object) of current URL when called without any parameter.\n *\n * Change search part when called with parameter and return `$location`.\n *\n *\n * ```js\n * // given URL http://example.com/#/some/path?foo=bar&baz=xoxo\n * var searchObject = $location.search();\n * // => {foo: 'bar', baz: 'xoxo'}\n *\n * // set foo to 'yipee'\n * $location.search('foo', 'yipee');\n * // $location.search() => {foo: 'yipee', baz: 'xoxo'}\n * ```\n *\n * @param {string|Object.|Object.>} search New search params - string or\n * hash object.\n *\n * When called with a single argument the method acts as a setter, setting the `search` component\n * of `$location` to the specified value.\n *\n * If the argument is a hash object containing an array of values, these values will be encoded\n * as duplicate search parameters in the URL.\n *\n * @param {(string|Number|Array|boolean)=} paramValue If `search` is a string or number, then `paramValue`\n * will override only a single search property.\n *\n * If `paramValue` is an array, it will override the property of the `search` component of\n * `$location` specified via the first argument.\n *\n * If `paramValue` is `null`, the property specified via the first argument will be deleted.\n *\n * If `paramValue` is `true`, the property specified via the first argument will be added with no\n * value nor trailing equal sign.\n *\n * @return {Object} If called with no arguments returns the parsed `search` object. If called with\n * one or more arguments returns `$location` object itself.\n */\n search: function(search, paramValue) {\n switch (arguments.length) {\n case 0:\n return this.$$search;\n case 1:\n if (isString(search) || isNumber(search)) {\n search = search.toString();\n this.$$search = parseKeyValue(search);\n } else if (isObject(search)) {\n search = copy(search, {});\n // remove object undefined or null properties\n forEach(search, function(value, key) {\n if (value == null) delete search[key];\n });\n\n this.$$search = search;\n } else {\n throw $locationMinErr('isrcharg',\n 'The first argument of the `$location#search()` call must be a string or an object.');\n }\n break;\n default:\n if (isUndefined(paramValue) || paramValue === null) {\n delete this.$$search[search];\n } else {\n this.$$search[search] = paramValue;\n }\n }\n\n this.$$compose();\n return this;\n },\n\n /**\n * @ngdoc method\n * @name $location#hash\n *\n * @description\n * This method is getter / setter.\n *\n * Returns the hash fragment when called without any parameters.\n *\n * Changes the hash fragment when called with a parameter and returns `$location`.\n *\n *\n * ```js\n * // given URL http://example.com/#/some/path?foo=bar&baz=xoxo#hashValue\n * var hash = $location.hash();\n * // => \"hashValue\"\n * ```\n *\n * @param {(string|number)=} hash New hash fragment\n * @return {string} hash\n */\n hash: locationGetterSetter('$$hash', function(hash) {\n return hash !== null ? hash.toString() : '';\n }),\n\n /**\n * @ngdoc method\n * @name $location#replace\n *\n * @description\n * If called, all changes to $location during the current `$digest` will replace the current history\n * record, instead of adding a new one.\n */\n replace: function() {\n this.$$replace = true;\n return this;\n }\n};\n\nforEach([LocationHashbangInHtml5Url, LocationHashbangUrl, LocationHtml5Url], function(Location) {\n Location.prototype = Object.create(locationPrototype);\n\n /**\n * @ngdoc method\n * @name $location#state\n *\n * @description\n * This method is getter / setter.\n *\n * Return the history state object when called without any parameter.\n *\n * Change the history state object when called with one parameter and return `$location`.\n * The state object is later passed to `pushState` or `replaceState`.\n *\n * NOTE: This method is supported only in HTML5 mode and only in browsers supporting\n * the HTML5 History API (i.e. methods `pushState` and `replaceState`). If you need to support\n * older browsers (like IE9 or Android < 4.0), don't use this method.\n *\n * @param {object=} state State object for pushState or replaceState\n * @return {object} state\n */\n Location.prototype.state = function(state) {\n if (!arguments.length) {\n return this.$$state;\n }\n\n if (Location !== LocationHtml5Url || !this.$$html5) {\n throw $locationMinErr('nostate', 'History API state support is available only ' +\n 'in HTML5 mode and only in browsers supporting HTML5 History API');\n }\n // The user might modify `stateObject` after invoking `$location.state(stateObject)`\n // but we're changing the $$state reference to $browser.state() during the $digest\n // so the modification window is narrow.\n this.$$state = isUndefined(state) ? null : state;\n\n return this;\n };\n});\n\n\nfunction locationGetter(property) {\n return /** @this */ function() {\n return this[property];\n };\n}\n\n\nfunction locationGetterSetter(property, preprocess) {\n return /** @this */ function(value) {\n if (isUndefined(value)) {\n return this[property];\n }\n\n this[property] = preprocess(value);\n this.$$compose();\n\n return this;\n };\n}\n\n\n/**\n * @ngdoc service\n * @name $location\n *\n * @requires $rootElement\n *\n * @description\n * The $location service parses the URL in the browser address bar (based on the\n * [window.location](https://developer.mozilla.org/en/window.location)) and makes the URL\n * available to your application. Changes to the URL in the address bar are reflected into\n * $location service and changes to $location are reflected into the browser address bar.\n *\n * **The $location service:**\n *\n * - Exposes the current URL in the browser address bar, so you can\n * - Watch and observe the URL.\n * - Change the URL.\n * - Synchronizes the URL with the browser when the user\n * - Changes the address bar.\n * - Clicks the back or forward button (or clicks a History link).\n * - Clicks on a link.\n * - Represents the URL object as a set of methods (protocol, host, port, path, search, hash).\n *\n * For more information see {@link guide/$location Developer Guide: Using $location}\n */\n\n/**\n * @ngdoc provider\n * @name $locationProvider\n * @this\n *\n * @description\n * Use the `$locationProvider` to configure how the application deep linking paths are stored.\n */\nfunction $LocationProvider() {\n var hashPrefix = '!',\n html5Mode = {\n enabled: false,\n requireBase: true,\n rewriteLinks: true\n };\n\n /**\n * @ngdoc method\n * @name $locationProvider#hashPrefix\n * @description\n * The default value for the prefix is `'!'`.\n * @param {string=} prefix Prefix for hash part (containing path and search)\n * @returns {*} current value if used as getter or itself (chaining) if used as setter\n */\n this.hashPrefix = function(prefix) {\n if (isDefined(prefix)) {\n hashPrefix = prefix;\n return this;\n } else {\n return hashPrefix;\n }\n };\n\n /**\n * @ngdoc method\n * @name $locationProvider#html5Mode\n * @description\n * @param {(boolean|Object)=} mode If boolean, sets `html5Mode.enabled` to value.\n * If object, sets `enabled`, `requireBase` and `rewriteLinks` to respective values. Supported\n * properties:\n * - **enabled** – `{boolean}` – (default: false) If true, will rely on `history.pushState` to\n * change urls where supported. Will fall back to hash-prefixed paths in browsers that do not\n * support `pushState`.\n * - **requireBase** - `{boolean}` - (default: `true`) When html5Mode is enabled, specifies\n * whether or not a tag is required to be present. If `enabled` and `requireBase` are\n * true, and a base tag is not present, an error will be thrown when `$location` is injected.\n * See the {@link guide/$location $location guide for more information}\n * - **rewriteLinks** - `{boolean|string}` - (default: `true`) When html5Mode is enabled,\n * enables/disables URL rewriting for relative links. If set to a string, URL rewriting will\n * only happen on links with an attribute that matches the given string. For example, if set\n * to `'internal-link'`, then the URL will only be rewritten for `` links.\n * Note that [attribute name normalization](guide/directive#normalization) does not apply\n * here, so `'internalLink'` will **not** match `'internal-link'`.\n *\n * @returns {Object} html5Mode object if used as getter or itself (chaining) if used as setter\n */\n this.html5Mode = function(mode) {\n if (isBoolean(mode)) {\n html5Mode.enabled = mode;\n return this;\n } else if (isObject(mode)) {\n\n if (isBoolean(mode.enabled)) {\n html5Mode.enabled = mode.enabled;\n }\n\n if (isBoolean(mode.requireBase)) {\n html5Mode.requireBase = mode.requireBase;\n }\n\n if (isBoolean(mode.rewriteLinks) || isString(mode.rewriteLinks)) {\n html5Mode.rewriteLinks = mode.rewriteLinks;\n }\n\n return this;\n } else {\n return html5Mode;\n }\n };\n\n /**\n * @ngdoc event\n * @name $location#$locationChangeStart\n * @eventType broadcast on root scope\n * @description\n * Broadcasted before a URL will change.\n *\n * This change can be prevented by calling\n * `preventDefault` method of the event. See {@link ng.$rootScope.Scope#$on} for more\n * details about event object. Upon successful change\n * {@link ng.$location#$locationChangeSuccess $locationChangeSuccess} is fired.\n *\n * The `newState` and `oldState` parameters may be defined only in HTML5 mode and when\n * the browser supports the HTML5 History API.\n *\n * @param {Object} angularEvent Synthetic event object.\n * @param {string} newUrl New URL\n * @param {string=} oldUrl URL that was before it was changed.\n * @param {string=} newState New history state object\n * @param {string=} oldState History state object that was before it was changed.\n */\n\n /**\n * @ngdoc event\n * @name $location#$locationChangeSuccess\n * @eventType broadcast on root scope\n * @description\n * Broadcasted after a URL was changed.\n *\n * The `newState` and `oldState` parameters may be defined only in HTML5 mode and when\n * the browser supports the HTML5 History API.\n *\n * @param {Object} angularEvent Synthetic event object.\n * @param {string} newUrl New URL\n * @param {string=} oldUrl URL that was before it was changed.\n * @param {string=} newState New history state object\n * @param {string=} oldState History state object that was before it was changed.\n */\n\n this.$get = ['$rootScope', '$browser', '$sniffer', '$rootElement', '$window',\n function($rootScope, $browser, $sniffer, $rootElement, $window) {\n var $location,\n LocationMode,\n baseHref = $browser.baseHref(), // if base[href] is undefined, it defaults to ''\n initialUrl = $browser.url(),\n appBase;\n\n if (html5Mode.enabled) {\n if (!baseHref && html5Mode.requireBase) {\n throw $locationMinErr('nobase',\n '$location in HTML5 mode requires a tag to be present!');\n }\n appBase = serverBase(initialUrl) + (baseHref || '/');\n LocationMode = $sniffer.history ? LocationHtml5Url : LocationHashbangInHtml5Url;\n } else {\n appBase = stripHash(initialUrl);\n LocationMode = LocationHashbangUrl;\n }\n var appBaseNoFile = stripFile(appBase);\n\n $location = new LocationMode(appBase, appBaseNoFile, '#' + hashPrefix);\n $location.$$parseLinkUrl(initialUrl, initialUrl);\n\n $location.$$state = $browser.state();\n\n var IGNORE_URI_REGEXP = /^\\s*(javascript|mailto):/i;\n\n function setBrowserUrlWithFallback(url, replace, state) {\n var oldUrl = $location.url();\n var oldState = $location.$$state;\n try {\n $browser.url(url, replace, state);\n\n // Make sure $location.state() returns referentially identical (not just deeply equal)\n // state object; this makes possible quick checking if the state changed in the digest\n // loop. Checking deep equality would be too expensive.\n $location.$$state = $browser.state();\n } catch (e) {\n // Restore old values if pushState fails\n $location.url(oldUrl);\n $location.$$state = oldState;\n\n throw e;\n }\n }\n\n $rootElement.on('click', function(event) {\n var rewriteLinks = html5Mode.rewriteLinks;\n // TODO(vojta): rewrite link when opening in new tab/window (in legacy browser)\n // currently we open nice url link and redirect then\n\n if (!rewriteLinks || event.ctrlKey || event.metaKey || event.shiftKey || event.which === 2 || event.button === 2) return;\n\n var elm = jqLite(event.target);\n\n // traverse the DOM up to find first A tag\n while (nodeName_(elm[0]) !== 'a') {\n // ignore rewriting if no A tag (reached root element, or no parent - removed from document)\n if (elm[0] === $rootElement[0] || !(elm = elm.parent())[0]) return;\n }\n\n if (isString(rewriteLinks) && isUndefined(elm.attr(rewriteLinks))) return;\n\n var absHref = elm.prop('href');\n // get the actual href attribute - see\n // http://msdn.microsoft.com/en-us/library/ie/dd347148(v=vs.85).aspx\n var relHref = elm.attr('href') || elm.attr('xlink:href');\n\n if (isObject(absHref) && absHref.toString() === '[object SVGAnimatedString]') {\n // SVGAnimatedString.animVal should be identical to SVGAnimatedString.baseVal, unless during\n // an animation.\n absHref = urlResolve(absHref.animVal).href;\n }\n\n // Ignore when url is started with javascript: or mailto:\n if (IGNORE_URI_REGEXP.test(absHref)) return;\n\n if (absHref && !elm.attr('target') && !event.isDefaultPrevented()) {\n if ($location.$$parseLinkUrl(absHref, relHref)) {\n // We do a preventDefault for all urls that are part of the angular application,\n // in html5mode and also without, so that we are able to abort navigation without\n // getting double entries in the location history.\n event.preventDefault();\n // update location manually\n if ($location.absUrl() !== $browser.url()) {\n $rootScope.$apply();\n // hack to work around FF6 bug 684208 when scenario runner clicks on links\n $window.angular['ff-684208-preventDefault'] = true;\n }\n }\n }\n });\n\n\n // rewrite hashbang url <> html5 url\n if (trimEmptyHash($location.absUrl()) !== trimEmptyHash(initialUrl)) {\n $browser.url($location.absUrl(), true);\n }\n\n var initializing = true;\n\n // update $location when $browser url changes\n $browser.onUrlChange(function(newUrl, newState) {\n\n if (!startsWith(newUrl, appBaseNoFile)) {\n // If we are navigating outside of the app then force a reload\n $window.location.href = newUrl;\n return;\n }\n\n $rootScope.$evalAsync(function() {\n var oldUrl = $location.absUrl();\n var oldState = $location.$$state;\n var defaultPrevented;\n newUrl = trimEmptyHash(newUrl);\n $location.$$parse(newUrl);\n $location.$$state = newState;\n\n defaultPrevented = $rootScope.$broadcast('$locationChangeStart', newUrl, oldUrl,\n newState, oldState).defaultPrevented;\n\n // if the location was changed by a `$locationChangeStart` handler then stop\n // processing this location change\n if ($location.absUrl() !== newUrl) return;\n\n if (defaultPrevented) {\n $location.$$parse(oldUrl);\n $location.$$state = oldState;\n setBrowserUrlWithFallback(oldUrl, false, oldState);\n } else {\n initializing = false;\n afterLocationChange(oldUrl, oldState);\n }\n });\n if (!$rootScope.$$phase) $rootScope.$digest();\n });\n\n // update browser\n $rootScope.$watch(function $locationWatch() {\n var oldUrl = trimEmptyHash($browser.url());\n var newUrl = trimEmptyHash($location.absUrl());\n var oldState = $browser.state();\n var currentReplace = $location.$$replace;\n var urlOrStateChanged = oldUrl !== newUrl ||\n ($location.$$html5 && $sniffer.history && oldState !== $location.$$state);\n\n if (initializing || urlOrStateChanged) {\n initializing = false;\n\n $rootScope.$evalAsync(function() {\n var newUrl = $location.absUrl();\n var defaultPrevented = $rootScope.$broadcast('$locationChangeStart', newUrl, oldUrl,\n $location.$$state, oldState).defaultPrevented;\n\n // if the location was changed by a `$locationChangeStart` handler then stop\n // processing this location change\n if ($location.absUrl() !== newUrl) return;\n\n if (defaultPrevented) {\n $location.$$parse(oldUrl);\n $location.$$state = oldState;\n } else {\n if (urlOrStateChanged) {\n setBrowserUrlWithFallback(newUrl, currentReplace,\n oldState === $location.$$state ? null : $location.$$state);\n }\n afterLocationChange(oldUrl, oldState);\n }\n });\n }\n\n $location.$$replace = false;\n\n // we don't need to return anything because $evalAsync will make the digest loop dirty when\n // there is a change\n });\n\n return $location;\n\n function afterLocationChange(oldUrl, oldState) {\n $rootScope.$broadcast('$locationChangeSuccess', $location.absUrl(), oldUrl,\n $location.$$state, oldState);\n }\n}];\n}\n\n/**\n * @ngdoc service\n * @name $log\n * @requires $window\n *\n * @description\n * Simple service for logging. Default implementation safely writes the message\n * into the browser's console (if present).\n *\n * The main purpose of this service is to simplify debugging and troubleshooting.\n *\n * The default is to log `debug` messages. You can use\n * {@link ng.$logProvider ng.$logProvider#debugEnabled} to change this.\n *\n * @example\n \n \n angular.module('logExample', [])\n .controller('LogController', ['$scope', '$log', function($scope, $log) {\n $scope.$log = $log;\n $scope.message = 'Hello World!';\n }]);\n \n \n
\n

Reload this page with open console, enter text and hit the log button...

\n \n \n \n \n \n \n
\n
\n
\n */\n\n/**\n * @ngdoc provider\n * @name $logProvider\n * @this\n *\n * @description\n * Use the `$logProvider` to configure how the application logs messages\n */\nfunction $LogProvider() {\n var debug = true,\n self = this;\n\n /**\n * @ngdoc method\n * @name $logProvider#debugEnabled\n * @description\n * @param {boolean=} flag enable or disable debug level messages\n * @returns {*} current value if used as getter or itself (chaining) if used as setter\n */\n this.debugEnabled = function(flag) {\n if (isDefined(flag)) {\n debug = flag;\n return this;\n } else {\n return debug;\n }\n };\n\n this.$get = ['$window', function($window) {\n return {\n /**\n * @ngdoc method\n * @name $log#log\n *\n * @description\n * Write a log message\n */\n log: consoleLog('log'),\n\n /**\n * @ngdoc method\n * @name $log#info\n *\n * @description\n * Write an information message\n */\n info: consoleLog('info'),\n\n /**\n * @ngdoc method\n * @name $log#warn\n *\n * @description\n * Write a warning message\n */\n warn: consoleLog('warn'),\n\n /**\n * @ngdoc method\n * @name $log#error\n *\n * @description\n * Write an error message\n */\n error: consoleLog('error'),\n\n /**\n * @ngdoc method\n * @name $log#debug\n *\n * @description\n * Write a debug message\n */\n debug: (function() {\n var fn = consoleLog('debug');\n\n return function() {\n if (debug) {\n fn.apply(self, arguments);\n }\n };\n })()\n };\n\n function formatError(arg) {\n if (arg instanceof Error) {\n if (arg.stack) {\n arg = (arg.message && arg.stack.indexOf(arg.message) === -1)\n ? 'Error: ' + arg.message + '\\n' + arg.stack\n : arg.stack;\n } else if (arg.sourceURL) {\n arg = arg.message + '\\n' + arg.sourceURL + ':' + arg.line;\n }\n }\n return arg;\n }\n\n function consoleLog(type) {\n var console = $window.console || {},\n logFn = console[type] || console.log || noop,\n hasApply = false;\n\n // Note: reading logFn.apply throws an error in IE11 in IE8 document mode.\n // The reason behind this is that console.log has type \"object\" in IE8...\n try {\n hasApply = !!logFn.apply;\n } catch (e) { /* empty */ }\n\n if (hasApply) {\n return function() {\n var args = [];\n forEach(arguments, function(arg) {\n args.push(formatError(arg));\n });\n return logFn.apply(console, args);\n };\n }\n\n // we are IE which either doesn't have window.console => this is noop and we do nothing,\n // or we are IE where console.log doesn't have apply so we log at least first 2 args\n return function(arg1, arg2) {\n logFn(arg1, arg2 == null ? '' : arg2);\n };\n }\n }];\n}\n\n/* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *\n * Any commits to this file should be reviewed with security in mind. *\n * Changes to this file can potentially create security vulnerabilities. *\n * An approval from 2 Core members with history of modifying *\n * this file is required. *\n * *\n * Does the change somehow allow for arbitrary javascript to be executed? *\n * Or allows for someone to change the prototype of built-in objects? *\n * Or gives undesired access to variables likes document or window? *\n * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */\n\nvar $parseMinErr = minErr('$parse');\n\nvar objectValueOf = {}.constructor.prototype.valueOf;\n\n// Sandboxing Angular Expressions\n// ------------------------------\n// Angular expressions are no longer sandboxed. So it is now even easier to access arbitrary JS code by\n// various means such as obtaining a reference to native JS functions like the Function constructor.\n//\n// As an example, consider the following Angular expression:\n//\n// {}.toString.constructor('alert(\"evil JS code\")')\n//\n// It is important to realize that if you create an expression from a string that contains user provided\n// content then it is possible that your application contains a security vulnerability to an XSS style attack.\n//\n// See https://docs.angularjs.org/guide/security\n\n\nfunction getStringValue(name) {\n // Property names must be strings. This means that non-string objects cannot be used\n // as keys in an object. Any non-string object, including a number, is typecasted\n // into a string via the toString method.\n // -- MDN, https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Operators/Property_accessors#Property_names\n //\n // So, to ensure that we are checking the same `name` that JavaScript would use, we cast it\n // to a string. It's not always possible. If `name` is an object and its `toString` method is\n // 'broken' (doesn't return a string, isn't a function, etc.), an error will be thrown:\n //\n // TypeError: Cannot convert object to primitive value\n //\n // For performance reasons, we don't catch this error here and allow it to propagate up the call\n // stack. Note that you'll get the same error in JavaScript if you try to access a property using\n // such a 'broken' object as a key.\n return name + '';\n}\n\n\nvar OPERATORS = createMap();\nforEach('+ - * / % === !== == != < > <= >= && || ! = |'.split(' '), function(operator) { OPERATORS[operator] = true; });\nvar ESCAPE = {'n':'\\n', 'f':'\\f', 'r':'\\r', 't':'\\t', 'v':'\\v', '\\'':'\\'', '\"':'\"'};\n\n\n/////////////////////////////////////////\n\n\n/**\n * @constructor\n */\nvar Lexer = function Lexer(options) {\n this.options = options;\n};\n\nLexer.prototype = {\n constructor: Lexer,\n\n lex: function(text) {\n this.text = text;\n this.index = 0;\n this.tokens = [];\n\n while (this.index < this.text.length) {\n var ch = this.text.charAt(this.index);\n if (ch === '\"' || ch === '\\'') {\n this.readString(ch);\n } else if (this.isNumber(ch) || ch === '.' && this.isNumber(this.peek())) {\n this.readNumber();\n } else if (this.isIdentifierStart(this.peekMultichar())) {\n this.readIdent();\n } else if (this.is(ch, '(){}[].,;:?')) {\n this.tokens.push({index: this.index, text: ch});\n this.index++;\n } else if (this.isWhitespace(ch)) {\n this.index++;\n } else {\n var ch2 = ch + this.peek();\n var ch3 = ch2 + this.peek(2);\n var op1 = OPERATORS[ch];\n var op2 = OPERATORS[ch2];\n var op3 = OPERATORS[ch3];\n if (op1 || op2 || op3) {\n var token = op3 ? ch3 : (op2 ? ch2 : ch);\n this.tokens.push({index: this.index, text: token, operator: true});\n this.index += token.length;\n } else {\n this.throwError('Unexpected next character ', this.index, this.index + 1);\n }\n }\n }\n return this.tokens;\n },\n\n is: function(ch, chars) {\n return chars.indexOf(ch) !== -1;\n },\n\n peek: function(i) {\n var num = i || 1;\n return (this.index + num < this.text.length) ? this.text.charAt(this.index + num) : false;\n },\n\n isNumber: function(ch) {\n return ('0' <= ch && ch <= '9') && typeof ch === 'string';\n },\n\n isWhitespace: function(ch) {\n // IE treats non-breaking space as \\u00A0\n return (ch === ' ' || ch === '\\r' || ch === '\\t' ||\n ch === '\\n' || ch === '\\v' || ch === '\\u00A0');\n },\n\n isIdentifierStart: function(ch) {\n return this.options.isIdentifierStart ?\n this.options.isIdentifierStart(ch, this.codePointAt(ch)) :\n this.isValidIdentifierStart(ch);\n },\n\n isValidIdentifierStart: function(ch) {\n return ('a' <= ch && ch <= 'z' ||\n 'A' <= ch && ch <= 'Z' ||\n '_' === ch || ch === '$');\n },\n\n isIdentifierContinue: function(ch) {\n return this.options.isIdentifierContinue ?\n this.options.isIdentifierContinue(ch, this.codePointAt(ch)) :\n this.isValidIdentifierContinue(ch);\n },\n\n isValidIdentifierContinue: function(ch, cp) {\n return this.isValidIdentifierStart(ch, cp) || this.isNumber(ch);\n },\n\n codePointAt: function(ch) {\n if (ch.length === 1) return ch.charCodeAt(0);\n // eslint-disable-next-line no-bitwise\n return (ch.charCodeAt(0) << 10) + ch.charCodeAt(1) - 0x35FDC00;\n },\n\n peekMultichar: function() {\n var ch = this.text.charAt(this.index);\n var peek = this.peek();\n if (!peek) {\n return ch;\n }\n var cp1 = ch.charCodeAt(0);\n var cp2 = peek.charCodeAt(0);\n if (cp1 >= 0xD800 && cp1 <= 0xDBFF && cp2 >= 0xDC00 && cp2 <= 0xDFFF) {\n return ch + peek;\n }\n return ch;\n },\n\n isExpOperator: function(ch) {\n return (ch === '-' || ch === '+' || this.isNumber(ch));\n },\n\n throwError: function(error, start, end) {\n end = end || this.index;\n var colStr = (isDefined(start)\n ? 's ' + start + '-' + this.index + ' [' + this.text.substring(start, end) + ']'\n : ' ' + end);\n throw $parseMinErr('lexerr', 'Lexer Error: {0} at column{1} in expression [{2}].',\n error, colStr, this.text);\n },\n\n readNumber: function() {\n var number = '';\n var start = this.index;\n while (this.index < this.text.length) {\n var ch = lowercase(this.text.charAt(this.index));\n if (ch === '.' || this.isNumber(ch)) {\n number += ch;\n } else {\n var peekCh = this.peek();\n if (ch === 'e' && this.isExpOperator(peekCh)) {\n number += ch;\n } else if (this.isExpOperator(ch) &&\n peekCh && this.isNumber(peekCh) &&\n number.charAt(number.length - 1) === 'e') {\n number += ch;\n } else if (this.isExpOperator(ch) &&\n (!peekCh || !this.isNumber(peekCh)) &&\n number.charAt(number.length - 1) === 'e') {\n this.throwError('Invalid exponent');\n } else {\n break;\n }\n }\n this.index++;\n }\n this.tokens.push({\n index: start,\n text: number,\n constant: true,\n value: Number(number)\n });\n },\n\n readIdent: function() {\n var start = this.index;\n this.index += this.peekMultichar().length;\n while (this.index < this.text.length) {\n var ch = this.peekMultichar();\n if (!this.isIdentifierContinue(ch)) {\n break;\n }\n this.index += ch.length;\n }\n this.tokens.push({\n index: start,\n text: this.text.slice(start, this.index),\n identifier: true\n });\n },\n\n readString: function(quote) {\n var start = this.index;\n this.index++;\n var string = '';\n var rawString = quote;\n var escape = false;\n while (this.index < this.text.length) {\n var ch = this.text.charAt(this.index);\n rawString += ch;\n if (escape) {\n if (ch === 'u') {\n var hex = this.text.substring(this.index + 1, this.index + 5);\n if (!hex.match(/[\\da-f]{4}/i)) {\n this.throwError('Invalid unicode escape [\\\\u' + hex + ']');\n }\n this.index += 4;\n string += String.fromCharCode(parseInt(hex, 16));\n } else {\n var rep = ESCAPE[ch];\n string = string + (rep || ch);\n }\n escape = false;\n } else if (ch === '\\\\') {\n escape = true;\n } else if (ch === quote) {\n this.index++;\n this.tokens.push({\n index: start,\n text: rawString,\n constant: true,\n value: string\n });\n return;\n } else {\n string += ch;\n }\n this.index++;\n }\n this.throwError('Unterminated quote', start);\n }\n};\n\nvar AST = function AST(lexer, options) {\n this.lexer = lexer;\n this.options = options;\n};\n\nAST.Program = 'Program';\nAST.ExpressionStatement = 'ExpressionStatement';\nAST.AssignmentExpression = 'AssignmentExpression';\nAST.ConditionalExpression = 'ConditionalExpression';\nAST.LogicalExpression = 'LogicalExpression';\nAST.BinaryExpression = 'BinaryExpression';\nAST.UnaryExpression = 'UnaryExpression';\nAST.CallExpression = 'CallExpression';\nAST.MemberExpression = 'MemberExpression';\nAST.Identifier = 'Identifier';\nAST.Literal = 'Literal';\nAST.ArrayExpression = 'ArrayExpression';\nAST.Property = 'Property';\nAST.ObjectExpression = 'ObjectExpression';\nAST.ThisExpression = 'ThisExpression';\nAST.LocalsExpression = 'LocalsExpression';\n\n// Internal use only\nAST.NGValueParameter = 'NGValueParameter';\n\nAST.prototype = {\n ast: function(text) {\n this.text = text;\n this.tokens = this.lexer.lex(text);\n\n var value = this.program();\n\n if (this.tokens.length !== 0) {\n this.throwError('is an unexpected token', this.tokens[0]);\n }\n\n return value;\n },\n\n program: function() {\n var body = [];\n while (true) {\n if (this.tokens.length > 0 && !this.peek('}', ')', ';', ']'))\n body.push(this.expressionStatement());\n if (!this.expect(';')) {\n return { type: AST.Program, body: body};\n }\n }\n },\n\n expressionStatement: function() {\n return { type: AST.ExpressionStatement, expression: this.filterChain() };\n },\n\n filterChain: function() {\n var left = this.expression();\n while (this.expect('|')) {\n left = this.filter(left);\n }\n return left;\n },\n\n expression: function() {\n return this.assignment();\n },\n\n assignment: function() {\n var result = this.ternary();\n if (this.expect('=')) {\n if (!isAssignable(result)) {\n throw $parseMinErr('lval', 'Trying to assign a value to a non l-value');\n }\n\n result = { type: AST.AssignmentExpression, left: result, right: this.assignment(), operator: '='};\n }\n return result;\n },\n\n ternary: function() {\n var test = this.logicalOR();\n var alternate;\n var consequent;\n if (this.expect('?')) {\n alternate = this.expression();\n if (this.consume(':')) {\n consequent = this.expression();\n return { type: AST.ConditionalExpression, test: test, alternate: alternate, consequent: consequent};\n }\n }\n return test;\n },\n\n logicalOR: function() {\n var left = this.logicalAND();\n while (this.expect('||')) {\n left = { type: AST.LogicalExpression, operator: '||', left: left, right: this.logicalAND() };\n }\n return left;\n },\n\n logicalAND: function() {\n var left = this.equality();\n while (this.expect('&&')) {\n left = { type: AST.LogicalExpression, operator: '&&', left: left, right: this.equality()};\n }\n return left;\n },\n\n equality: function() {\n var left = this.relational();\n var token;\n while ((token = this.expect('==','!=','===','!=='))) {\n left = { type: AST.BinaryExpression, operator: token.text, left: left, right: this.relational() };\n }\n return left;\n },\n\n relational: function() {\n var left = this.additive();\n var token;\n while ((token = this.expect('<', '>', '<=', '>='))) {\n left = { type: AST.BinaryExpression, operator: token.text, left: left, right: this.additive() };\n }\n return left;\n },\n\n additive: function() {\n var left = this.multiplicative();\n var token;\n while ((token = this.expect('+','-'))) {\n left = { type: AST.BinaryExpression, operator: token.text, left: left, right: this.multiplicative() };\n }\n return left;\n },\n\n multiplicative: function() {\n var left = this.unary();\n var token;\n while ((token = this.expect('*','/','%'))) {\n left = { type: AST.BinaryExpression, operator: token.text, left: left, right: this.unary() };\n }\n return left;\n },\n\n unary: function() {\n var token;\n if ((token = this.expect('+', '-', '!'))) {\n return { type: AST.UnaryExpression, operator: token.text, prefix: true, argument: this.unary() };\n } else {\n return this.primary();\n }\n },\n\n primary: function() {\n var primary;\n if (this.expect('(')) {\n primary = this.filterChain();\n this.consume(')');\n } else if (this.expect('[')) {\n primary = this.arrayDeclaration();\n } else if (this.expect('{')) {\n primary = this.object();\n } else if (this.selfReferential.hasOwnProperty(this.peek().text)) {\n primary = copy(this.selfReferential[this.consume().text]);\n } else if (this.options.literals.hasOwnProperty(this.peek().text)) {\n primary = { type: AST.Literal, value: this.options.literals[this.consume().text]};\n } else if (this.peek().identifier) {\n primary = this.identifier();\n } else if (this.peek().constant) {\n primary = this.constant();\n } else {\n this.throwError('not a primary expression', this.peek());\n }\n\n var next;\n while ((next = this.expect('(', '[', '.'))) {\n if (next.text === '(') {\n primary = {type: AST.CallExpression, callee: primary, arguments: this.parseArguments() };\n this.consume(')');\n } else if (next.text === '[') {\n primary = { type: AST.MemberExpression, object: primary, property: this.expression(), computed: true };\n this.consume(']');\n } else if (next.text === '.') {\n primary = { type: AST.MemberExpression, object: primary, property: this.identifier(), computed: false };\n } else {\n this.throwError('IMPOSSIBLE');\n }\n }\n return primary;\n },\n\n filter: function(baseExpression) {\n var args = [baseExpression];\n var result = {type: AST.CallExpression, callee: this.identifier(), arguments: args, filter: true};\n\n while (this.expect(':')) {\n args.push(this.expression());\n }\n\n return result;\n },\n\n parseArguments: function() {\n var args = [];\n if (this.peekToken().text !== ')') {\n do {\n args.push(this.filterChain());\n } while (this.expect(','));\n }\n return args;\n },\n\n identifier: function() {\n var token = this.consume();\n if (!token.identifier) {\n this.throwError('is not a valid identifier', token);\n }\n return { type: AST.Identifier, name: token.text };\n },\n\n constant: function() {\n // TODO check that it is a constant\n return { type: AST.Literal, value: this.consume().value };\n },\n\n arrayDeclaration: function() {\n var elements = [];\n if (this.peekToken().text !== ']') {\n do {\n if (this.peek(']')) {\n // Support trailing commas per ES5.1.\n break;\n }\n elements.push(this.expression());\n } while (this.expect(','));\n }\n this.consume(']');\n\n return { type: AST.ArrayExpression, elements: elements };\n },\n\n object: function() {\n var properties = [], property;\n if (this.peekToken().text !== '}') {\n do {\n if (this.peek('}')) {\n // Support trailing commas per ES5.1.\n break;\n }\n property = {type: AST.Property, kind: 'init'};\n if (this.peek().constant) {\n property.key = this.constant();\n property.computed = false;\n this.consume(':');\n property.value = this.expression();\n } else if (this.peek().identifier) {\n property.key = this.identifier();\n property.computed = false;\n if (this.peek(':')) {\n this.consume(':');\n property.value = this.expression();\n } else {\n property.value = property.key;\n }\n } else if (this.peek('[')) {\n this.consume('[');\n property.key = this.expression();\n this.consume(']');\n property.computed = true;\n this.consume(':');\n property.value = this.expression();\n } else {\n this.throwError('invalid key', this.peek());\n }\n properties.push(property);\n } while (this.expect(','));\n }\n this.consume('}');\n\n return {type: AST.ObjectExpression, properties: properties };\n },\n\n throwError: function(msg, token) {\n throw $parseMinErr('syntax',\n 'Syntax Error: Token \\'{0}\\' {1} at column {2} of the expression [{3}] starting at [{4}].',\n token.text, msg, (token.index + 1), this.text, this.text.substring(token.index));\n },\n\n consume: function(e1) {\n if (this.tokens.length === 0) {\n throw $parseMinErr('ueoe', 'Unexpected end of expression: {0}', this.text);\n }\n\n var token = this.expect(e1);\n if (!token) {\n this.throwError('is unexpected, expecting [' + e1 + ']', this.peek());\n }\n return token;\n },\n\n peekToken: function() {\n if (this.tokens.length === 0) {\n throw $parseMinErr('ueoe', 'Unexpected end of expression: {0}', this.text);\n }\n return this.tokens[0];\n },\n\n peek: function(e1, e2, e3, e4) {\n return this.peekAhead(0, e1, e2, e3, e4);\n },\n\n peekAhead: function(i, e1, e2, e3, e4) {\n if (this.tokens.length > i) {\n var token = this.tokens[i];\n var t = token.text;\n if (t === e1 || t === e2 || t === e3 || t === e4 ||\n (!e1 && !e2 && !e3 && !e4)) {\n return token;\n }\n }\n return false;\n },\n\n expect: function(e1, e2, e3, e4) {\n var token = this.peek(e1, e2, e3, e4);\n if (token) {\n this.tokens.shift();\n return token;\n }\n return false;\n },\n\n selfReferential: {\n 'this': {type: AST.ThisExpression },\n '$locals': {type: AST.LocalsExpression }\n }\n};\n\nfunction ifDefined(v, d) {\n return typeof v !== 'undefined' ? v : d;\n}\n\nfunction plusFn(l, r) {\n if (typeof l === 'undefined') return r;\n if (typeof r === 'undefined') return l;\n return l + r;\n}\n\nfunction isStateless($filter, filterName) {\n var fn = $filter(filterName);\n return !fn.$stateful;\n}\n\nfunction findConstantAndWatchExpressions(ast, $filter) {\n var allConstants;\n var argsToWatch;\n var isStatelessFilter;\n switch (ast.type) {\n case AST.Program:\n allConstants = true;\n forEach(ast.body, function(expr) {\n findConstantAndWatchExpressions(expr.expression, $filter);\n allConstants = allConstants && expr.expression.constant;\n });\n ast.constant = allConstants;\n break;\n case AST.Literal:\n ast.constant = true;\n ast.toWatch = [];\n break;\n case AST.UnaryExpression:\n findConstantAndWatchExpressions(ast.argument, $filter);\n ast.constant = ast.argument.constant;\n ast.toWatch = ast.argument.toWatch;\n break;\n case AST.BinaryExpression:\n findConstantAndWatchExpressions(ast.left, $filter);\n findConstantAndWatchExpressions(ast.right, $filter);\n ast.constant = ast.left.constant && ast.right.constant;\n ast.toWatch = ast.left.toWatch.concat(ast.right.toWatch);\n break;\n case AST.LogicalExpression:\n findConstantAndWatchExpressions(ast.left, $filter);\n findConstantAndWatchExpressions(ast.right, $filter);\n ast.constant = ast.left.constant && ast.right.constant;\n ast.toWatch = ast.constant ? [] : [ast];\n break;\n case AST.ConditionalExpression:\n findConstantAndWatchExpressions(ast.test, $filter);\n findConstantAndWatchExpressions(ast.alternate, $filter);\n findConstantAndWatchExpressions(ast.consequent, $filter);\n ast.constant = ast.test.constant && ast.alternate.constant && ast.consequent.constant;\n ast.toWatch = ast.constant ? [] : [ast];\n break;\n case AST.Identifier:\n ast.constant = false;\n ast.toWatch = [ast];\n break;\n case AST.MemberExpression:\n findConstantAndWatchExpressions(ast.object, $filter);\n if (ast.computed) {\n findConstantAndWatchExpressions(ast.property, $filter);\n }\n ast.constant = ast.object.constant && (!ast.computed || ast.property.constant);\n ast.toWatch = [ast];\n break;\n case AST.CallExpression:\n isStatelessFilter = ast.filter ? isStateless($filter, ast.callee.name) : false;\n allConstants = isStatelessFilter;\n argsToWatch = [];\n forEach(ast.arguments, function(expr) {\n findConstantAndWatchExpressions(expr, $filter);\n allConstants = allConstants && expr.constant;\n if (!expr.constant) {\n argsToWatch.push.apply(argsToWatch, expr.toWatch);\n }\n });\n ast.constant = allConstants;\n ast.toWatch = isStatelessFilter ? argsToWatch : [ast];\n break;\n case AST.AssignmentExpression:\n findConstantAndWatchExpressions(ast.left, $filter);\n findConstantAndWatchExpressions(ast.right, $filter);\n ast.constant = ast.left.constant && ast.right.constant;\n ast.toWatch = [ast];\n break;\n case AST.ArrayExpression:\n allConstants = true;\n argsToWatch = [];\n forEach(ast.elements, function(expr) {\n findConstantAndWatchExpressions(expr, $filter);\n allConstants = allConstants && expr.constant;\n if (!expr.constant) {\n argsToWatch.push.apply(argsToWatch, expr.toWatch);\n }\n });\n ast.constant = allConstants;\n ast.toWatch = argsToWatch;\n break;\n case AST.ObjectExpression:\n allConstants = true;\n argsToWatch = [];\n forEach(ast.properties, function(property) {\n findConstantAndWatchExpressions(property.value, $filter);\n allConstants = allConstants && property.value.constant && !property.computed;\n if (!property.value.constant) {\n argsToWatch.push.apply(argsToWatch, property.value.toWatch);\n }\n });\n ast.constant = allConstants;\n ast.toWatch = argsToWatch;\n break;\n case AST.ThisExpression:\n ast.constant = false;\n ast.toWatch = [];\n break;\n case AST.LocalsExpression:\n ast.constant = false;\n ast.toWatch = [];\n break;\n }\n}\n\nfunction getInputs(body) {\n if (body.length !== 1) return;\n var lastExpression = body[0].expression;\n var candidate = lastExpression.toWatch;\n if (candidate.length !== 1) return candidate;\n return candidate[0] !== lastExpression ? candidate : undefined;\n}\n\nfunction isAssignable(ast) {\n return ast.type === AST.Identifier || ast.type === AST.MemberExpression;\n}\n\nfunction assignableAST(ast) {\n if (ast.body.length === 1 && isAssignable(ast.body[0].expression)) {\n return {type: AST.AssignmentExpression, left: ast.body[0].expression, right: {type: AST.NGValueParameter}, operator: '='};\n }\n}\n\nfunction isLiteral(ast) {\n return ast.body.length === 0 ||\n ast.body.length === 1 && (\n ast.body[0].expression.type === AST.Literal ||\n ast.body[0].expression.type === AST.ArrayExpression ||\n ast.body[0].expression.type === AST.ObjectExpression);\n}\n\nfunction isConstant(ast) {\n return ast.constant;\n}\n\nfunction ASTCompiler(astBuilder, $filter) {\n this.astBuilder = astBuilder;\n this.$filter = $filter;\n}\n\nASTCompiler.prototype = {\n compile: function(expression) {\n var self = this;\n var ast = this.astBuilder.ast(expression);\n this.state = {\n nextId: 0,\n filters: {},\n fn: {vars: [], body: [], own: {}},\n assign: {vars: [], body: [], own: {}},\n inputs: []\n };\n findConstantAndWatchExpressions(ast, self.$filter);\n var extra = '';\n var assignable;\n this.stage = 'assign';\n if ((assignable = assignableAST(ast))) {\n this.state.computing = 'assign';\n var result = this.nextId();\n this.recurse(assignable, result);\n this.return_(result);\n extra = 'fn.assign=' + this.generateFunction('assign', 's,v,l');\n }\n var toWatch = getInputs(ast.body);\n self.stage = 'inputs';\n forEach(toWatch, function(watch, key) {\n var fnKey = 'fn' + key;\n self.state[fnKey] = {vars: [], body: [], own: {}};\n self.state.computing = fnKey;\n var intoId = self.nextId();\n self.recurse(watch, intoId);\n self.return_(intoId);\n self.state.inputs.push(fnKey);\n watch.watchId = key;\n });\n this.state.computing = 'fn';\n this.stage = 'main';\n this.recurse(ast);\n var fnString =\n // The build and minification steps remove the string \"use strict\" from the code, but this is done using a regex.\n // This is a workaround for this until we do a better job at only removing the prefix only when we should.\n '\"' + this.USE + ' ' + this.STRICT + '\";\\n' +\n this.filterPrefix() +\n 'var fn=' + this.generateFunction('fn', 's,l,a,i') +\n extra +\n this.watchFns() +\n 'return fn;';\n\n // eslint-disable-next-line no-new-func\n var fn = (new Function('$filter',\n 'getStringValue',\n 'ifDefined',\n 'plus',\n fnString))(\n this.$filter,\n getStringValue,\n ifDefined,\n plusFn);\n this.state = this.stage = undefined;\n fn.literal = isLiteral(ast);\n fn.constant = isConstant(ast);\n return fn;\n },\n\n USE: 'use',\n\n STRICT: 'strict',\n\n watchFns: function() {\n var result = [];\n var fns = this.state.inputs;\n var self = this;\n forEach(fns, function(name) {\n result.push('var ' + name + '=' + self.generateFunction(name, 's'));\n });\n if (fns.length) {\n result.push('fn.inputs=[' + fns.join(',') + '];');\n }\n return result.join('');\n },\n\n generateFunction: function(name, params) {\n return 'function(' + params + '){' +\n this.varsPrefix(name) +\n this.body(name) +\n '};';\n },\n\n filterPrefix: function() {\n var parts = [];\n var self = this;\n forEach(this.state.filters, function(id, filter) {\n parts.push(id + '=$filter(' + self.escape(filter) + ')');\n });\n if (parts.length) return 'var ' + parts.join(',') + ';';\n return '';\n },\n\n varsPrefix: function(section) {\n return this.state[section].vars.length ? 'var ' + this.state[section].vars.join(',') + ';' : '';\n },\n\n body: function(section) {\n return this.state[section].body.join('');\n },\n\n recurse: function(ast, intoId, nameId, recursionFn, create, skipWatchIdCheck) {\n var left, right, self = this, args, expression, computed;\n recursionFn = recursionFn || noop;\n if (!skipWatchIdCheck && isDefined(ast.watchId)) {\n intoId = intoId || this.nextId();\n this.if_('i',\n this.lazyAssign(intoId, this.computedMember('i', ast.watchId)),\n this.lazyRecurse(ast, intoId, nameId, recursionFn, create, true)\n );\n return;\n }\n switch (ast.type) {\n case AST.Program:\n forEach(ast.body, function(expression, pos) {\n self.recurse(expression.expression, undefined, undefined, function(expr) { right = expr; });\n if (pos !== ast.body.length - 1) {\n self.current().body.push(right, ';');\n } else {\n self.return_(right);\n }\n });\n break;\n case AST.Literal:\n expression = this.escape(ast.value);\n this.assign(intoId, expression);\n recursionFn(intoId || expression);\n break;\n case AST.UnaryExpression:\n this.recurse(ast.argument, undefined, undefined, function(expr) { right = expr; });\n expression = ast.operator + '(' + this.ifDefined(right, 0) + ')';\n this.assign(intoId, expression);\n recursionFn(expression);\n break;\n case AST.BinaryExpression:\n this.recurse(ast.left, undefined, undefined, function(expr) { left = expr; });\n this.recurse(ast.right, undefined, undefined, function(expr) { right = expr; });\n if (ast.operator === '+') {\n expression = this.plus(left, right);\n } else if (ast.operator === '-') {\n expression = this.ifDefined(left, 0) + ast.operator + this.ifDefined(right, 0);\n } else {\n expression = '(' + left + ')' + ast.operator + '(' + right + ')';\n }\n this.assign(intoId, expression);\n recursionFn(expression);\n break;\n case AST.LogicalExpression:\n intoId = intoId || this.nextId();\n self.recurse(ast.left, intoId);\n self.if_(ast.operator === '&&' ? intoId : self.not(intoId), self.lazyRecurse(ast.right, intoId));\n recursionFn(intoId);\n break;\n case AST.ConditionalExpression:\n intoId = intoId || this.nextId();\n self.recurse(ast.test, intoId);\n self.if_(intoId, self.lazyRecurse(ast.alternate, intoId), self.lazyRecurse(ast.consequent, intoId));\n recursionFn(intoId);\n break;\n case AST.Identifier:\n intoId = intoId || this.nextId();\n if (nameId) {\n nameId.context = self.stage === 'inputs' ? 's' : this.assign(this.nextId(), this.getHasOwnProperty('l', ast.name) + '?l:s');\n nameId.computed = false;\n nameId.name = ast.name;\n }\n self.if_(self.stage === 'inputs' || self.not(self.getHasOwnProperty('l', ast.name)),\n function() {\n self.if_(self.stage === 'inputs' || 's', function() {\n if (create && create !== 1) {\n self.if_(\n self.isNull(self.nonComputedMember('s', ast.name)),\n self.lazyAssign(self.nonComputedMember('s', ast.name), '{}'));\n }\n self.assign(intoId, self.nonComputedMember('s', ast.name));\n });\n }, intoId && self.lazyAssign(intoId, self.nonComputedMember('l', ast.name))\n );\n recursionFn(intoId);\n break;\n case AST.MemberExpression:\n left = nameId && (nameId.context = this.nextId()) || this.nextId();\n intoId = intoId || this.nextId();\n self.recurse(ast.object, left, undefined, function() {\n self.if_(self.notNull(left), function() {\n if (ast.computed) {\n right = self.nextId();\n self.recurse(ast.property, right);\n self.getStringValue(right);\n if (create && create !== 1) {\n self.if_(self.not(self.computedMember(left, right)), self.lazyAssign(self.computedMember(left, right), '{}'));\n }\n expression = self.computedMember(left, right);\n self.assign(intoId, expression);\n if (nameId) {\n nameId.computed = true;\n nameId.name = right;\n }\n } else {\n if (create && create !== 1) {\n self.if_(self.isNull(self.nonComputedMember(left, ast.property.name)), self.lazyAssign(self.nonComputedMember(left, ast.property.name), '{}'));\n }\n expression = self.nonComputedMember(left, ast.property.name);\n self.assign(intoId, expression);\n if (nameId) {\n nameId.computed = false;\n nameId.name = ast.property.name;\n }\n }\n }, function() {\n self.assign(intoId, 'undefined');\n });\n recursionFn(intoId);\n }, !!create);\n break;\n case AST.CallExpression:\n intoId = intoId || this.nextId();\n if (ast.filter) {\n right = self.filter(ast.callee.name);\n args = [];\n forEach(ast.arguments, function(expr) {\n var argument = self.nextId();\n self.recurse(expr, argument);\n args.push(argument);\n });\n expression = right + '(' + args.join(',') + ')';\n self.assign(intoId, expression);\n recursionFn(intoId);\n } else {\n right = self.nextId();\n left = {};\n args = [];\n self.recurse(ast.callee, right, left, function() {\n self.if_(self.notNull(right), function() {\n forEach(ast.arguments, function(expr) {\n self.recurse(expr, ast.constant ? undefined : self.nextId(), undefined, function(argument) {\n args.push(argument);\n });\n });\n if (left.name) {\n expression = self.member(left.context, left.name, left.computed) + '(' + args.join(',') + ')';\n } else {\n expression = right + '(' + args.join(',') + ')';\n }\n self.assign(intoId, expression);\n }, function() {\n self.assign(intoId, 'undefined');\n });\n recursionFn(intoId);\n });\n }\n break;\n case AST.AssignmentExpression:\n right = this.nextId();\n left = {};\n this.recurse(ast.left, undefined, left, function() {\n self.if_(self.notNull(left.context), function() {\n self.recurse(ast.right, right);\n expression = self.member(left.context, left.name, left.computed) + ast.operator + right;\n self.assign(intoId, expression);\n recursionFn(intoId || expression);\n });\n }, 1);\n break;\n case AST.ArrayExpression:\n args = [];\n forEach(ast.elements, function(expr) {\n self.recurse(expr, ast.constant ? undefined : self.nextId(), undefined, function(argument) {\n args.push(argument);\n });\n });\n expression = '[' + args.join(',') + ']';\n this.assign(intoId, expression);\n recursionFn(intoId || expression);\n break;\n case AST.ObjectExpression:\n args = [];\n computed = false;\n forEach(ast.properties, function(property) {\n if (property.computed) {\n computed = true;\n }\n });\n if (computed) {\n intoId = intoId || this.nextId();\n this.assign(intoId, '{}');\n forEach(ast.properties, function(property) {\n if (property.computed) {\n left = self.nextId();\n self.recurse(property.key, left);\n } else {\n left = property.key.type === AST.Identifier ?\n property.key.name :\n ('' + property.key.value);\n }\n right = self.nextId();\n self.recurse(property.value, right);\n self.assign(self.member(intoId, left, property.computed), right);\n });\n } else {\n forEach(ast.properties, function(property) {\n self.recurse(property.value, ast.constant ? undefined : self.nextId(), undefined, function(expr) {\n args.push(self.escape(\n property.key.type === AST.Identifier ? property.key.name :\n ('' + property.key.value)) +\n ':' + expr);\n });\n });\n expression = '{' + args.join(',') + '}';\n this.assign(intoId, expression);\n }\n recursionFn(intoId || expression);\n break;\n case AST.ThisExpression:\n this.assign(intoId, 's');\n recursionFn(intoId || 's');\n break;\n case AST.LocalsExpression:\n this.assign(intoId, 'l');\n recursionFn(intoId || 'l');\n break;\n case AST.NGValueParameter:\n this.assign(intoId, 'v');\n recursionFn(intoId || 'v');\n break;\n }\n },\n\n getHasOwnProperty: function(element, property) {\n var key = element + '.' + property;\n var own = this.current().own;\n if (!own.hasOwnProperty(key)) {\n own[key] = this.nextId(false, element + '&&(' + this.escape(property) + ' in ' + element + ')');\n }\n return own[key];\n },\n\n assign: function(id, value) {\n if (!id) return;\n this.current().body.push(id, '=', value, ';');\n return id;\n },\n\n filter: function(filterName) {\n if (!this.state.filters.hasOwnProperty(filterName)) {\n this.state.filters[filterName] = this.nextId(true);\n }\n return this.state.filters[filterName];\n },\n\n ifDefined: function(id, defaultValue) {\n return 'ifDefined(' + id + ',' + this.escape(defaultValue) + ')';\n },\n\n plus: function(left, right) {\n return 'plus(' + left + ',' + right + ')';\n },\n\n return_: function(id) {\n this.current().body.push('return ', id, ';');\n },\n\n if_: function(test, alternate, consequent) {\n if (test === true) {\n alternate();\n } else {\n var body = this.current().body;\n body.push('if(', test, '){');\n alternate();\n body.push('}');\n if (consequent) {\n body.push('else{');\n consequent();\n body.push('}');\n }\n }\n },\n\n not: function(expression) {\n return '!(' + expression + ')';\n },\n\n isNull: function(expression) {\n return expression + '==null';\n },\n\n notNull: function(expression) {\n return expression + '!=null';\n },\n\n nonComputedMember: function(left, right) {\n var SAFE_IDENTIFIER = /^[$_a-zA-Z][$_a-zA-Z0-9]*$/;\n var UNSAFE_CHARACTERS = /[^$_a-zA-Z0-9]/g;\n if (SAFE_IDENTIFIER.test(right)) {\n return left + '.' + right;\n } else {\n return left + '[\"' + right.replace(UNSAFE_CHARACTERS, this.stringEscapeFn) + '\"]';\n }\n },\n\n computedMember: function(left, right) {\n return left + '[' + right + ']';\n },\n\n member: function(left, right, computed) {\n if (computed) return this.computedMember(left, right);\n return this.nonComputedMember(left, right);\n },\n\n getStringValue: function(item) {\n this.assign(item, 'getStringValue(' + item + ')');\n },\n\n lazyRecurse: function(ast, intoId, nameId, recursionFn, create, skipWatchIdCheck) {\n var self = this;\n return function() {\n self.recurse(ast, intoId, nameId, recursionFn, create, skipWatchIdCheck);\n };\n },\n\n lazyAssign: function(id, value) {\n var self = this;\n return function() {\n self.assign(id, value);\n };\n },\n\n stringEscapeRegex: /[^ a-zA-Z0-9]/g,\n\n stringEscapeFn: function(c) {\n return '\\\\u' + ('0000' + c.charCodeAt(0).toString(16)).slice(-4);\n },\n\n escape: function(value) {\n if (isString(value)) return '\\'' + value.replace(this.stringEscapeRegex, this.stringEscapeFn) + '\\'';\n if (isNumber(value)) return value.toString();\n if (value === true) return 'true';\n if (value === false) return 'false';\n if (value === null) return 'null';\n if (typeof value === 'undefined') return 'undefined';\n\n throw $parseMinErr('esc', 'IMPOSSIBLE');\n },\n\n nextId: function(skip, init) {\n var id = 'v' + (this.state.nextId++);\n if (!skip) {\n this.current().vars.push(id + (init ? '=' + init : ''));\n }\n return id;\n },\n\n current: function() {\n return this.state[this.state.computing];\n }\n};\n\n\nfunction ASTInterpreter(astBuilder, $filter) {\n this.astBuilder = astBuilder;\n this.$filter = $filter;\n}\n\nASTInterpreter.prototype = {\n compile: function(expression) {\n var self = this;\n var ast = this.astBuilder.ast(expression);\n findConstantAndWatchExpressions(ast, self.$filter);\n var assignable;\n var assign;\n if ((assignable = assignableAST(ast))) {\n assign = this.recurse(assignable);\n }\n var toWatch = getInputs(ast.body);\n var inputs;\n if (toWatch) {\n inputs = [];\n forEach(toWatch, function(watch, key) {\n var input = self.recurse(watch);\n watch.input = input;\n inputs.push(input);\n watch.watchId = key;\n });\n }\n var expressions = [];\n forEach(ast.body, function(expression) {\n expressions.push(self.recurse(expression.expression));\n });\n var fn = ast.body.length === 0 ? noop :\n ast.body.length === 1 ? expressions[0] :\n function(scope, locals) {\n var lastValue;\n forEach(expressions, function(exp) {\n lastValue = exp(scope, locals);\n });\n return lastValue;\n };\n if (assign) {\n fn.assign = function(scope, value, locals) {\n return assign(scope, locals, value);\n };\n }\n if (inputs) {\n fn.inputs = inputs;\n }\n fn.literal = isLiteral(ast);\n fn.constant = isConstant(ast);\n return fn;\n },\n\n recurse: function(ast, context, create) {\n var left, right, self = this, args;\n if (ast.input) {\n return this.inputs(ast.input, ast.watchId);\n }\n switch (ast.type) {\n case AST.Literal:\n return this.value(ast.value, context);\n case AST.UnaryExpression:\n right = this.recurse(ast.argument);\n return this['unary' + ast.operator](right, context);\n case AST.BinaryExpression:\n left = this.recurse(ast.left);\n right = this.recurse(ast.right);\n return this['binary' + ast.operator](left, right, context);\n case AST.LogicalExpression:\n left = this.recurse(ast.left);\n right = this.recurse(ast.right);\n return this['binary' + ast.operator](left, right, context);\n case AST.ConditionalExpression:\n return this['ternary?:'](\n this.recurse(ast.test),\n this.recurse(ast.alternate),\n this.recurse(ast.consequent),\n context\n );\n case AST.Identifier:\n return self.identifier(ast.name, context, create);\n case AST.MemberExpression:\n left = this.recurse(ast.object, false, !!create);\n if (!ast.computed) {\n right = ast.property.name;\n }\n if (ast.computed) right = this.recurse(ast.property);\n return ast.computed ?\n this.computedMember(left, right, context, create) :\n this.nonComputedMember(left, right, context, create);\n case AST.CallExpression:\n args = [];\n forEach(ast.arguments, function(expr) {\n args.push(self.recurse(expr));\n });\n if (ast.filter) right = this.$filter(ast.callee.name);\n if (!ast.filter) right = this.recurse(ast.callee, true);\n return ast.filter ?\n function(scope, locals, assign, inputs) {\n var values = [];\n for (var i = 0; i < args.length; ++i) {\n values.push(args[i](scope, locals, assign, inputs));\n }\n var value = right.apply(undefined, values, inputs);\n return context ? {context: undefined, name: undefined, value: value} : value;\n } :\n function(scope, locals, assign, inputs) {\n var rhs = right(scope, locals, assign, inputs);\n var value;\n if (rhs.value != null) {\n var values = [];\n for (var i = 0; i < args.length; ++i) {\n values.push(args[i](scope, locals, assign, inputs));\n }\n value = rhs.value.apply(rhs.context, values);\n }\n return context ? {value: value} : value;\n };\n case AST.AssignmentExpression:\n left = this.recurse(ast.left, true, 1);\n right = this.recurse(ast.right);\n return function(scope, locals, assign, inputs) {\n var lhs = left(scope, locals, assign, inputs);\n var rhs = right(scope, locals, assign, inputs);\n lhs.context[lhs.name] = rhs;\n return context ? {value: rhs} : rhs;\n };\n case AST.ArrayExpression:\n args = [];\n forEach(ast.elements, function(expr) {\n args.push(self.recurse(expr));\n });\n return function(scope, locals, assign, inputs) {\n var value = [];\n for (var i = 0; i < args.length; ++i) {\n value.push(args[i](scope, locals, assign, inputs));\n }\n return context ? {value: value} : value;\n };\n case AST.ObjectExpression:\n args = [];\n forEach(ast.properties, function(property) {\n if (property.computed) {\n args.push({key: self.recurse(property.key),\n computed: true,\n value: self.recurse(property.value)\n });\n } else {\n args.push({key: property.key.type === AST.Identifier ?\n property.key.name :\n ('' + property.key.value),\n computed: false,\n value: self.recurse(property.value)\n });\n }\n });\n return function(scope, locals, assign, inputs) {\n var value = {};\n for (var i = 0; i < args.length; ++i) {\n if (args[i].computed) {\n value[args[i].key(scope, locals, assign, inputs)] = args[i].value(scope, locals, assign, inputs);\n } else {\n value[args[i].key] = args[i].value(scope, locals, assign, inputs);\n }\n }\n return context ? {value: value} : value;\n };\n case AST.ThisExpression:\n return function(scope) {\n return context ? {value: scope} : scope;\n };\n case AST.LocalsExpression:\n return function(scope, locals) {\n return context ? {value: locals} : locals;\n };\n case AST.NGValueParameter:\n return function(scope, locals, assign) {\n return context ? {value: assign} : assign;\n };\n }\n },\n\n 'unary+': function(argument, context) {\n return function(scope, locals, assign, inputs) {\n var arg = argument(scope, locals, assign, inputs);\n if (isDefined(arg)) {\n arg = +arg;\n } else {\n arg = 0;\n }\n return context ? {value: arg} : arg;\n };\n },\n 'unary-': function(argument, context) {\n return function(scope, locals, assign, inputs) {\n var arg = argument(scope, locals, assign, inputs);\n if (isDefined(arg)) {\n arg = -arg;\n } else {\n arg = -0;\n }\n return context ? {value: arg} : arg;\n };\n },\n 'unary!': function(argument, context) {\n return function(scope, locals, assign, inputs) {\n var arg = !argument(scope, locals, assign, inputs);\n return context ? {value: arg} : arg;\n };\n },\n 'binary+': function(left, right, context) {\n return function(scope, locals, assign, inputs) {\n var lhs = left(scope, locals, assign, inputs);\n var rhs = right(scope, locals, assign, inputs);\n var arg = plusFn(lhs, rhs);\n return context ? {value: arg} : arg;\n };\n },\n 'binary-': function(left, right, context) {\n return function(scope, locals, assign, inputs) {\n var lhs = left(scope, locals, assign, inputs);\n var rhs = right(scope, locals, assign, inputs);\n var arg = (isDefined(lhs) ? lhs : 0) - (isDefined(rhs) ? rhs : 0);\n return context ? {value: arg} : arg;\n };\n },\n 'binary*': function(left, right, context) {\n return function(scope, locals, assign, inputs) {\n var arg = left(scope, locals, assign, inputs) * right(scope, locals, assign, inputs);\n return context ? {value: arg} : arg;\n };\n },\n 'binary/': function(left, right, context) {\n return function(scope, locals, assign, inputs) {\n var arg = left(scope, locals, assign, inputs) / right(scope, locals, assign, inputs);\n return context ? {value: arg} : arg;\n };\n },\n 'binary%': function(left, right, context) {\n return function(scope, locals, assign, inputs) {\n var arg = left(scope, locals, assign, inputs) % right(scope, locals, assign, inputs);\n return context ? {value: arg} : arg;\n };\n },\n 'binary===': function(left, right, context) {\n return function(scope, locals, assign, inputs) {\n var arg = left(scope, locals, assign, inputs) === right(scope, locals, assign, inputs);\n return context ? {value: arg} : arg;\n };\n },\n 'binary!==': function(left, right, context) {\n return function(scope, locals, assign, inputs) {\n var arg = left(scope, locals, assign, inputs) !== right(scope, locals, assign, inputs);\n return context ? {value: arg} : arg;\n };\n },\n 'binary==': function(left, right, context) {\n return function(scope, locals, assign, inputs) {\n // eslint-disable-next-line eqeqeq\n var arg = left(scope, locals, assign, inputs) == right(scope, locals, assign, inputs);\n return context ? {value: arg} : arg;\n };\n },\n 'binary!=': function(left, right, context) {\n return function(scope, locals, assign, inputs) {\n // eslint-disable-next-line eqeqeq\n var arg = left(scope, locals, assign, inputs) != right(scope, locals, assign, inputs);\n return context ? {value: arg} : arg;\n };\n },\n 'binary<': function(left, right, context) {\n return function(scope, locals, assign, inputs) {\n var arg = left(scope, locals, assign, inputs) < right(scope, locals, assign, inputs);\n return context ? {value: arg} : arg;\n };\n },\n 'binary>': function(left, right, context) {\n return function(scope, locals, assign, inputs) {\n var arg = left(scope, locals, assign, inputs) > right(scope, locals, assign, inputs);\n return context ? {value: arg} : arg;\n };\n },\n 'binary<=': function(left, right, context) {\n return function(scope, locals, assign, inputs) {\n var arg = left(scope, locals, assign, inputs) <= right(scope, locals, assign, inputs);\n return context ? {value: arg} : arg;\n };\n },\n 'binary>=': function(left, right, context) {\n return function(scope, locals, assign, inputs) {\n var arg = left(scope, locals, assign, inputs) >= right(scope, locals, assign, inputs);\n return context ? {value: arg} : arg;\n };\n },\n 'binary&&': function(left, right, context) {\n return function(scope, locals, assign, inputs) {\n var arg = left(scope, locals, assign, inputs) && right(scope, locals, assign, inputs);\n return context ? {value: arg} : arg;\n };\n },\n 'binary||': function(left, right, context) {\n return function(scope, locals, assign, inputs) {\n var arg = left(scope, locals, assign, inputs) || right(scope, locals, assign, inputs);\n return context ? {value: arg} : arg;\n };\n },\n 'ternary?:': function(test, alternate, consequent, context) {\n return function(scope, locals, assign, inputs) {\n var arg = test(scope, locals, assign, inputs) ? alternate(scope, locals, assign, inputs) : consequent(scope, locals, assign, inputs);\n return context ? {value: arg} : arg;\n };\n },\n value: function(value, context) {\n return function() { return context ? {context: undefined, name: undefined, value: value} : value; };\n },\n identifier: function(name, context, create) {\n return function(scope, locals, assign, inputs) {\n var base = locals && (name in locals) ? locals : scope;\n if (create && create !== 1 && base && base[name] == null) {\n base[name] = {};\n }\n var value = base ? base[name] : undefined;\n if (context) {\n return {context: base, name: name, value: value};\n } else {\n return value;\n }\n };\n },\n computedMember: function(left, right, context, create) {\n return function(scope, locals, assign, inputs) {\n var lhs = left(scope, locals, assign, inputs);\n var rhs;\n var value;\n if (lhs != null) {\n rhs = right(scope, locals, assign, inputs);\n rhs = getStringValue(rhs);\n if (create && create !== 1) {\n if (lhs && !(lhs[rhs])) {\n lhs[rhs] = {};\n }\n }\n value = lhs[rhs];\n }\n if (context) {\n return {context: lhs, name: rhs, value: value};\n } else {\n return value;\n }\n };\n },\n nonComputedMember: function(left, right, context, create) {\n return function(scope, locals, assign, inputs) {\n var lhs = left(scope, locals, assign, inputs);\n if (create && create !== 1) {\n if (lhs && lhs[right] == null) {\n lhs[right] = {};\n }\n }\n var value = lhs != null ? lhs[right] : undefined;\n if (context) {\n return {context: lhs, name: right, value: value};\n } else {\n return value;\n }\n };\n },\n inputs: function(input, watchId) {\n return function(scope, value, locals, inputs) {\n if (inputs) return inputs[watchId];\n return input(scope, value, locals);\n };\n }\n};\n\n/**\n * @constructor\n */\nvar Parser = function Parser(lexer, $filter, options) {\n this.lexer = lexer;\n this.$filter = $filter;\n this.options = options;\n this.ast = new AST(lexer, options);\n this.astCompiler = options.csp ? new ASTInterpreter(this.ast, $filter) :\n new ASTCompiler(this.ast, $filter);\n};\n\nParser.prototype = {\n constructor: Parser,\n\n parse: function(text) {\n return this.astCompiler.compile(text);\n }\n};\n\nfunction getValueOf(value) {\n return isFunction(value.valueOf) ? value.valueOf() : objectValueOf.call(value);\n}\n\n///////////////////////////////////\n\n/**\n * @ngdoc service\n * @name $parse\n * @kind function\n *\n * @description\n *\n * Converts Angular {@link guide/expression expression} into a function.\n *\n * ```js\n * var getter = $parse('user.name');\n * var setter = getter.assign;\n * var context = {user:{name:'angular'}};\n * var locals = {user:{name:'local'}};\n *\n * expect(getter(context)).toEqual('angular');\n * setter(context, 'newValue');\n * expect(context.user.name).toEqual('newValue');\n * expect(getter(context, locals)).toEqual('local');\n * ```\n *\n *\n * @param {string} expression String expression to compile.\n * @returns {function(context, locals)} a function which represents the compiled expression:\n *\n * * `context` – `{object}` – an object against which any expressions embedded in the strings\n * are evaluated against (typically a scope object).\n * * `locals` – `{object=}` – local variables context object, useful for overriding values in\n * `context`.\n *\n * The returned function also has the following properties:\n * * `literal` – `{boolean}` – whether the expression's top-level node is a JavaScript\n * literal.\n * * `constant` – `{boolean}` – whether the expression is made entirely of JavaScript\n * constant literals.\n * * `assign` – `{?function(context, value)}` – if the expression is assignable, this will be\n * set to a function to change its value on the given context.\n *\n */\n\n\n/**\n * @ngdoc provider\n * @name $parseProvider\n * @this\n *\n * @description\n * `$parseProvider` can be used for configuring the default behavior of the {@link ng.$parse $parse}\n * service.\n */\nfunction $ParseProvider() {\n var cache = createMap();\n var literals = {\n 'true': true,\n 'false': false,\n 'null': null,\n 'undefined': undefined\n };\n var identStart, identContinue;\n\n /**\n * @ngdoc method\n * @name $parseProvider#addLiteral\n * @description\n *\n * Configure $parse service to add literal values that will be present as literal at expressions.\n *\n * @param {string} literalName Token for the literal value. The literal name value must be a valid literal name.\n * @param {*} literalValue Value for this literal. All literal values must be primitives or `undefined`.\n *\n **/\n this.addLiteral = function(literalName, literalValue) {\n literals[literalName] = literalValue;\n };\n\n /**\n * @ngdoc method\n * @name $parseProvider#setIdentifierFns\n *\n * @description\n *\n * Allows defining the set of characters that are allowed in Angular expressions. The function\n * `identifierStart` will get called to know if a given character is a valid character to be the\n * first character for an identifier. The function `identifierContinue` will get called to know if\n * a given character is a valid character to be a follow-up identifier character. The functions\n * `identifierStart` and `identifierContinue` will receive as arguments the single character to be\n * identifier and the character code point. These arguments will be `string` and `numeric`. Keep in\n * mind that the `string` parameter can be two characters long depending on the character\n * representation. It is expected for the function to return `true` or `false`, whether that\n * character is allowed or not.\n *\n * Since this function will be called extensively, keep the implementation of these functions fast,\n * as the performance of these functions have a direct impact on the expressions parsing speed.\n *\n * @param {function=} identifierStart The function that will decide whether the given character is\n * a valid identifier start character.\n * @param {function=} identifierContinue The function that will decide whether the given character is\n * a valid identifier continue character.\n */\n this.setIdentifierFns = function(identifierStart, identifierContinue) {\n identStart = identifierStart;\n identContinue = identifierContinue;\n return this;\n };\n\n this.$get = ['$filter', function($filter) {\n var noUnsafeEval = csp().noUnsafeEval;\n var $parseOptions = {\n csp: noUnsafeEval,\n literals: copy(literals),\n isIdentifierStart: isFunction(identStart) && identStart,\n isIdentifierContinue: isFunction(identContinue) && identContinue\n };\n return $parse;\n\n function $parse(exp, interceptorFn) {\n var parsedExpression, oneTime, cacheKey;\n\n switch (typeof exp) {\n case 'string':\n exp = exp.trim();\n cacheKey = exp;\n\n parsedExpression = cache[cacheKey];\n\n if (!parsedExpression) {\n if (exp.charAt(0) === ':' && exp.charAt(1) === ':') {\n oneTime = true;\n exp = exp.substring(2);\n }\n var lexer = new Lexer($parseOptions);\n var parser = new Parser(lexer, $filter, $parseOptions);\n parsedExpression = parser.parse(exp);\n if (parsedExpression.constant) {\n parsedExpression.$$watchDelegate = constantWatchDelegate;\n } else if (oneTime) {\n parsedExpression.$$watchDelegate = parsedExpression.literal ?\n oneTimeLiteralWatchDelegate : oneTimeWatchDelegate;\n } else if (parsedExpression.inputs) {\n parsedExpression.$$watchDelegate = inputsWatchDelegate;\n }\n cache[cacheKey] = parsedExpression;\n }\n return addInterceptor(parsedExpression, interceptorFn);\n\n case 'function':\n return addInterceptor(exp, interceptorFn);\n\n default:\n return addInterceptor(noop, interceptorFn);\n }\n }\n\n function expressionInputDirtyCheck(newValue, oldValueOfValue) {\n\n if (newValue == null || oldValueOfValue == null) { // null/undefined\n return newValue === oldValueOfValue;\n }\n\n if (typeof newValue === 'object') {\n\n // attempt to convert the value to a primitive type\n // TODO(docs): add a note to docs that by implementing valueOf even objects and arrays can\n // be cheaply dirty-checked\n newValue = getValueOf(newValue);\n\n if (typeof newValue === 'object') {\n // objects/arrays are not supported - deep-watching them would be too expensive\n return false;\n }\n\n // fall-through to the primitive equality check\n }\n\n //Primitive or NaN\n // eslint-disable-next-line no-self-compare\n return newValue === oldValueOfValue || (newValue !== newValue && oldValueOfValue !== oldValueOfValue);\n }\n\n function inputsWatchDelegate(scope, listener, objectEquality, parsedExpression, prettyPrintExpression) {\n var inputExpressions = parsedExpression.inputs;\n var lastResult;\n\n if (inputExpressions.length === 1) {\n var oldInputValueOf = expressionInputDirtyCheck; // init to something unique so that equals check fails\n inputExpressions = inputExpressions[0];\n return scope.$watch(function expressionInputWatch(scope) {\n var newInputValue = inputExpressions(scope);\n if (!expressionInputDirtyCheck(newInputValue, oldInputValueOf)) {\n lastResult = parsedExpression(scope, undefined, undefined, [newInputValue]);\n oldInputValueOf = newInputValue && getValueOf(newInputValue);\n }\n return lastResult;\n }, listener, objectEquality, prettyPrintExpression);\n }\n\n var oldInputValueOfValues = [];\n var oldInputValues = [];\n for (var i = 0, ii = inputExpressions.length; i < ii; i++) {\n oldInputValueOfValues[i] = expressionInputDirtyCheck; // init to something unique so that equals check fails\n oldInputValues[i] = null;\n }\n\n return scope.$watch(function expressionInputsWatch(scope) {\n var changed = false;\n\n for (var i = 0, ii = inputExpressions.length; i < ii; i++) {\n var newInputValue = inputExpressions[i](scope);\n if (changed || (changed = !expressionInputDirtyCheck(newInputValue, oldInputValueOfValues[i]))) {\n oldInputValues[i] = newInputValue;\n oldInputValueOfValues[i] = newInputValue && getValueOf(newInputValue);\n }\n }\n\n if (changed) {\n lastResult = parsedExpression(scope, undefined, undefined, oldInputValues);\n }\n\n return lastResult;\n }, listener, objectEquality, prettyPrintExpression);\n }\n\n function oneTimeWatchDelegate(scope, listener, objectEquality, parsedExpression, prettyPrintExpression) {\n var unwatch, lastValue;\n if (parsedExpression.inputs) {\n unwatch = inputsWatchDelegate(scope, oneTimeListener, objectEquality, parsedExpression, prettyPrintExpression);\n } else {\n unwatch = scope.$watch(oneTimeWatch, oneTimeListener, objectEquality);\n }\n return unwatch;\n\n function oneTimeWatch(scope) {\n return parsedExpression(scope);\n }\n function oneTimeListener(value, old, scope) {\n lastValue = value;\n if (isFunction(listener)) {\n listener(value, old, scope);\n }\n if (isDefined(value)) {\n scope.$$postDigest(function() {\n if (isDefined(lastValue)) {\n unwatch();\n }\n });\n }\n }\n }\n\n function oneTimeLiteralWatchDelegate(scope, listener, objectEquality, parsedExpression) {\n var unwatch, lastValue;\n unwatch = scope.$watch(function oneTimeWatch(scope) {\n return parsedExpression(scope);\n }, function oneTimeListener(value, old, scope) {\n lastValue = value;\n if (isFunction(listener)) {\n listener(value, old, scope);\n }\n if (isAllDefined(value)) {\n scope.$$postDigest(function() {\n if (isAllDefined(lastValue)) unwatch();\n });\n }\n }, objectEquality);\n\n return unwatch;\n\n function isAllDefined(value) {\n var allDefined = true;\n forEach(value, function(val) {\n if (!isDefined(val)) allDefined = false;\n });\n return allDefined;\n }\n }\n\n function constantWatchDelegate(scope, listener, objectEquality, parsedExpression) {\n var unwatch = scope.$watch(function constantWatch(scope) {\n unwatch();\n return parsedExpression(scope);\n }, listener, objectEquality);\n return unwatch;\n }\n\n function addInterceptor(parsedExpression, interceptorFn) {\n if (!interceptorFn) return parsedExpression;\n var watchDelegate = parsedExpression.$$watchDelegate;\n var useInputs = false;\n\n var regularWatch =\n watchDelegate !== oneTimeLiteralWatchDelegate &&\n watchDelegate !== oneTimeWatchDelegate;\n\n var fn = regularWatch ? function regularInterceptedExpression(scope, locals, assign, inputs) {\n var value = useInputs && inputs ? inputs[0] : parsedExpression(scope, locals, assign, inputs);\n return interceptorFn(value, scope, locals);\n } : function oneTimeInterceptedExpression(scope, locals, assign, inputs) {\n var value = parsedExpression(scope, locals, assign, inputs);\n var result = interceptorFn(value, scope, locals);\n // we only return the interceptor's result if the\n // initial value is defined (for bind-once)\n return isDefined(value) ? result : value;\n };\n\n // Propagate $$watchDelegates other then inputsWatchDelegate\n useInputs = !parsedExpression.inputs;\n if (parsedExpression.$$watchDelegate &&\n parsedExpression.$$watchDelegate !== inputsWatchDelegate) {\n fn.$$watchDelegate = parsedExpression.$$watchDelegate;\n fn.inputs = parsedExpression.inputs;\n } else if (!interceptorFn.$stateful) {\n // If there is an interceptor, but no watchDelegate then treat the interceptor like\n // we treat filters - it is assumed to be a pure function unless flagged with $stateful\n fn.$$watchDelegate = inputsWatchDelegate;\n fn.inputs = parsedExpression.inputs ? parsedExpression.inputs : [parsedExpression];\n }\n\n return fn;\n }\n }];\n}\n\n/**\n * @ngdoc service\n * @name $q\n * @requires $rootScope\n *\n * @description\n * A service that helps you run functions asynchronously, and use their return values (or exceptions)\n * when they are done processing.\n *\n * This is a [Promises/A+](https://promisesaplus.com/)-compliant implementation of promises/deferred\n * objects inspired by [Kris Kowal's Q](https://github.com/kriskowal/q).\n *\n * $q can be used in two fashions --- one which is more similar to Kris Kowal's Q or jQuery's Deferred\n * implementations, and the other which resembles ES6 (ES2015) promises to some degree.\n *\n * # $q constructor\n *\n * The streamlined ES6 style promise is essentially just using $q as a constructor which takes a `resolver`\n * function as the first argument. This is similar to the native Promise implementation from ES6,\n * see [MDN](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise).\n *\n * While the constructor-style use is supported, not all of the supporting methods from ES6 promises are\n * available yet.\n *\n * It can be used like so:\n *\n * ```js\n * // for the purpose of this example let's assume that variables `$q` and `okToGreet`\n * // are available in the current lexical scope (they could have been injected or passed in).\n *\n * function asyncGreet(name) {\n * // perform some asynchronous operation, resolve or reject the promise when appropriate.\n * return $q(function(resolve, reject) {\n * setTimeout(function() {\n * if (okToGreet(name)) {\n * resolve('Hello, ' + name + '!');\n * } else {\n * reject('Greeting ' + name + ' is not allowed.');\n * }\n * }, 1000);\n * });\n * }\n *\n * var promise = asyncGreet('Robin Hood');\n * promise.then(function(greeting) {\n * alert('Success: ' + greeting);\n * }, function(reason) {\n * alert('Failed: ' + reason);\n * });\n * ```\n *\n * Note: progress/notify callbacks are not currently supported via the ES6-style interface.\n *\n * Note: unlike ES6 behavior, an exception thrown in the constructor function will NOT implicitly reject the promise.\n *\n * However, the more traditional CommonJS-style usage is still available, and documented below.\n *\n * [The CommonJS Promise proposal](http://wiki.commonjs.org/wiki/Promises) describes a promise as an\n * interface for interacting with an object that represents the result of an action that is\n * performed asynchronously, and may or may not be finished at any given point in time.\n *\n * From the perspective of dealing with error handling, deferred and promise APIs are to\n * asynchronous programming what `try`, `catch` and `throw` keywords are to synchronous programming.\n *\n * ```js\n * // for the purpose of this example let's assume that variables `$q` and `okToGreet`\n * // are available in the current lexical scope (they could have been injected or passed in).\n *\n * function asyncGreet(name) {\n * var deferred = $q.defer();\n *\n * setTimeout(function() {\n * deferred.notify('About to greet ' + name + '.');\n *\n * if (okToGreet(name)) {\n * deferred.resolve('Hello, ' + name + '!');\n * } else {\n * deferred.reject('Greeting ' + name + ' is not allowed.');\n * }\n * }, 1000);\n *\n * return deferred.promise;\n * }\n *\n * var promise = asyncGreet('Robin Hood');\n * promise.then(function(greeting) {\n * alert('Success: ' + greeting);\n * }, function(reason) {\n * alert('Failed: ' + reason);\n * }, function(update) {\n * alert('Got notification: ' + update);\n * });\n * ```\n *\n * At first it might not be obvious why this extra complexity is worth the trouble. The payoff\n * comes in the way of guarantees that promise and deferred APIs make, see\n * https://github.com/kriskowal/uncommonjs/blob/master/promises/specification.md.\n *\n * Additionally the promise api allows for composition that is very hard to do with the\n * traditional callback ([CPS](http://en.wikipedia.org/wiki/Continuation-passing_style)) approach.\n * For more on this please see the [Q documentation](https://github.com/kriskowal/q) especially the\n * section on serial or parallel joining of promises.\n *\n * # The Deferred API\n *\n * A new instance of deferred is constructed by calling `$q.defer()`.\n *\n * The purpose of the deferred object is to expose the associated Promise instance as well as APIs\n * that can be used for signaling the successful or unsuccessful completion, as well as the status\n * of the task.\n *\n * **Methods**\n *\n * - `resolve(value)` – resolves the derived promise with the `value`. If the value is a rejection\n * constructed via `$q.reject`, the promise will be rejected instead.\n * - `reject(reason)` – rejects the derived promise with the `reason`. This is equivalent to\n * resolving it with a rejection constructed via `$q.reject`.\n * - `notify(value)` - provides updates on the status of the promise's execution. This may be called\n * multiple times before the promise is either resolved or rejected.\n *\n * **Properties**\n *\n * - promise – `{Promise}` – promise object associated with this deferred.\n *\n *\n * # The Promise API\n *\n * A new promise instance is created when a deferred instance is created and can be retrieved by\n * calling `deferred.promise`.\n *\n * The purpose of the promise object is to allow for interested parties to get access to the result\n * of the deferred task when it completes.\n *\n * **Methods**\n *\n * - `then(successCallback, [errorCallback], [notifyCallback])` – regardless of when the promise was or\n * will be resolved or rejected, `then` calls one of the success or error callbacks asynchronously\n * as soon as the result is available. The callbacks are called with a single argument: the result\n * or rejection reason. Additionally, the notify callback may be called zero or more times to\n * provide a progress indication, before the promise is resolved or rejected.\n *\n * This method *returns a new promise* which is resolved or rejected via the return value of the\n * `successCallback`, `errorCallback` (unless that value is a promise, in which case it is resolved\n * with the value which is resolved in that promise using\n * [promise chaining](http://www.html5rocks.com/en/tutorials/es6/promises/#toc-promises-queues)).\n * It also notifies via the return value of the `notifyCallback` method. The promise cannot be\n * resolved or rejected from the notifyCallback method. The errorCallback and notifyCallback\n * arguments are optional.\n *\n * - `catch(errorCallback)` – shorthand for `promise.then(null, errorCallback)`\n *\n * - `finally(callback, notifyCallback)` – allows you to observe either the fulfillment or rejection of a promise,\n * but to do so without modifying the final value. This is useful to release resources or do some\n * clean-up that needs to be done whether the promise was rejected or resolved. See the [full\n * specification](https://github.com/kriskowal/q/wiki/API-Reference#promisefinallycallback) for\n * more information.\n *\n * # Chaining promises\n *\n * Because calling the `then` method of a promise returns a new derived promise, it is easily\n * possible to create a chain of promises:\n *\n * ```js\n * promiseB = promiseA.then(function(result) {\n * return result + 1;\n * });\n *\n * // promiseB will be resolved immediately after promiseA is resolved and its value\n * // will be the result of promiseA incremented by 1\n * ```\n *\n * It is possible to create chains of any length and since a promise can be resolved with another\n * promise (which will defer its resolution further), it is possible to pause/defer resolution of\n * the promises at any point in the chain. This makes it possible to implement powerful APIs like\n * $http's response interceptors.\n *\n *\n * # Differences between Kris Kowal's Q and $q\n *\n * There are two main differences:\n *\n * - $q is integrated with the {@link ng.$rootScope.Scope} Scope model observation\n * mechanism in angular, which means faster propagation of resolution or rejection into your\n * models and avoiding unnecessary browser repaints, which would result in flickering UI.\n * - Q has many more features than $q, but that comes at a cost of bytes. $q is tiny, but contains\n * all the important functionality needed for common async tasks.\n *\n * # Testing\n *\n * ```js\n * it('should simulate promise', inject(function($q, $rootScope) {\n * var deferred = $q.defer();\n * var promise = deferred.promise;\n * var resolvedValue;\n *\n * promise.then(function(value) { resolvedValue = value; });\n * expect(resolvedValue).toBeUndefined();\n *\n * // Simulate resolving of promise\n * deferred.resolve(123);\n * // Note that the 'then' function does not get called synchronously.\n * // This is because we want the promise API to always be async, whether or not\n * // it got called synchronously or asynchronously.\n * expect(resolvedValue).toBeUndefined();\n *\n * // Propagate promise resolution to 'then' functions using $apply().\n * $rootScope.$apply();\n * expect(resolvedValue).toEqual(123);\n * }));\n * ```\n *\n * @param {function(function, function)} resolver Function which is responsible for resolving or\n * rejecting the newly created promise. The first parameter is a function which resolves the\n * promise, the second parameter is a function which rejects the promise.\n *\n * @returns {Promise} The newly created promise.\n */\n/**\n * @ngdoc provider\n * @name $qProvider\n * @this\n *\n * @description\n */\nfunction $QProvider() {\n var errorOnUnhandledRejections = true;\n this.$get = ['$rootScope', '$exceptionHandler', function($rootScope, $exceptionHandler) {\n return qFactory(function(callback) {\n $rootScope.$evalAsync(callback);\n }, $exceptionHandler, errorOnUnhandledRejections);\n }];\n\n /**\n * @ngdoc method\n * @name $qProvider#errorOnUnhandledRejections\n * @kind function\n *\n * @description\n * Retrieves or overrides whether to generate an error when a rejected promise is not handled.\n *\n * @param {boolean=} value Whether to generate an error when a rejected promise is not handled.\n * @returns {boolean|ng.$qProvider} Current value when called without a new value or self for\n * chaining otherwise.\n */\n this.errorOnUnhandledRejections = function(value) {\n if (isDefined(value)) {\n errorOnUnhandledRejections = value;\n return this;\n } else {\n return errorOnUnhandledRejections;\n }\n };\n}\n\n/** @this */\nfunction $$QProvider() {\n var errorOnUnhandledRejections = true;\n this.$get = ['$browser', '$exceptionHandler', function($browser, $exceptionHandler) {\n return qFactory(function(callback) {\n $browser.defer(callback);\n }, $exceptionHandler, errorOnUnhandledRejections);\n }];\n\n this.errorOnUnhandledRejections = function(value) {\n if (isDefined(value)) {\n errorOnUnhandledRejections = value;\n return this;\n } else {\n return errorOnUnhandledRejections;\n }\n };\n}\n\n/**\n * Constructs a promise manager.\n *\n * @param {function(function)} nextTick Function for executing functions in the next turn.\n * @param {function(...*)} exceptionHandler Function into which unexpected exceptions are passed for\n * debugging purposes.\n @ param {=boolean} errorOnUnhandledRejections Whether an error should be generated on unhandled\n * promises rejections.\n * @returns {object} Promise manager.\n */\nfunction qFactory(nextTick, exceptionHandler, errorOnUnhandledRejections) {\n var $qMinErr = minErr('$q', TypeError);\n var queueSize = 0;\n var checkQueue = [];\n\n /**\n * @ngdoc method\n * @name ng.$q#defer\n * @kind function\n *\n * @description\n * Creates a `Deferred` object which represents a task which will finish in the future.\n *\n * @returns {Deferred} Returns a new instance of deferred.\n */\n function defer() {\n return new Deferred();\n }\n\n function Deferred() {\n var promise = this.promise = new Promise();\n //Non prototype methods necessary to support unbound execution :/\n this.resolve = function(val) { resolvePromise(promise, val); };\n this.reject = function(reason) { rejectPromise(promise, reason); };\n this.notify = function(progress) { notifyPromise(promise, progress); };\n }\n\n\n function Promise() {\n this.$$state = { status: 0 };\n }\n\n extend(Promise.prototype, {\n then: function(onFulfilled, onRejected, progressBack) {\n if (isUndefined(onFulfilled) && isUndefined(onRejected) && isUndefined(progressBack)) {\n return this;\n }\n var result = new Promise();\n\n this.$$state.pending = this.$$state.pending || [];\n this.$$state.pending.push([result, onFulfilled, onRejected, progressBack]);\n if (this.$$state.status > 0) scheduleProcessQueue(this.$$state);\n\n return result;\n },\n\n 'catch': function(callback) {\n return this.then(null, callback);\n },\n\n 'finally': function(callback, progressBack) {\n return this.then(function(value) {\n return handleCallback(value, resolve, callback);\n }, function(error) {\n return handleCallback(error, reject, callback);\n }, progressBack);\n }\n });\n\n function processQueue(state) {\n var fn, promise, pending;\n\n pending = state.pending;\n state.processScheduled = false;\n state.pending = undefined;\n try {\n for (var i = 0, ii = pending.length; i < ii; ++i) {\n state.pur = true;\n promise = pending[i][0];\n fn = pending[i][state.status];\n try {\n if (isFunction(fn)) {\n resolvePromise(promise, fn(state.value));\n } else if (state.status === 1) {\n resolvePromise(promise, state.value);\n } else {\n rejectPromise(promise, state.value);\n }\n } catch (e) {\n rejectPromise(promise, e);\n }\n }\n } finally {\n --queueSize;\n if (errorOnUnhandledRejections && queueSize === 0) {\n nextTick(processChecks);\n }\n }\n }\n\n function processChecks() {\n // eslint-disable-next-line no-unmodified-loop-condition\n while (!queueSize && checkQueue.length) {\n var toCheck = checkQueue.shift();\n if (!toCheck.pur) {\n toCheck.pur = true;\n var errorMessage = 'Possibly unhandled rejection: ' + toDebugString(toCheck.value);\n exceptionHandler(errorMessage);\n }\n }\n }\n\n function scheduleProcessQueue(state) {\n if (errorOnUnhandledRejections && !state.pending && state.status === 2 && !state.pur) {\n if (queueSize === 0 && checkQueue.length === 0) {\n nextTick(processChecks);\n }\n checkQueue.push(state);\n }\n if (state.processScheduled || !state.pending) return;\n state.processScheduled = true;\n ++queueSize;\n nextTick(function() { processQueue(state); });\n }\n\n function resolvePromise(promise, val) {\n if (promise.$$state.status) return;\n if (val === promise) {\n $$reject(promise, $qMinErr(\n 'qcycle',\n 'Expected promise to be resolved with value other than itself \\'{0}\\'',\n val));\n } else {\n $$resolve(promise, val);\n }\n\n }\n\n function $$resolve(promise, val) {\n var then;\n var done = false;\n try {\n if (isObject(val) || isFunction(val)) then = val.then;\n if (isFunction(then)) {\n promise.$$state.status = -1;\n then.call(val, doResolve, doReject, doNotify);\n } else {\n promise.$$state.value = val;\n promise.$$state.status = 1;\n scheduleProcessQueue(promise.$$state);\n }\n } catch (e) {\n doReject(e);\n }\n\n function doResolve(val) {\n if (done) return;\n done = true;\n $$resolve(promise, val);\n }\n function doReject(val) {\n if (done) return;\n done = true;\n $$reject(promise, val);\n }\n function doNotify(progress) {\n notifyPromise(promise, progress);\n }\n }\n\n function rejectPromise(promise, reason) {\n if (promise.$$state.status) return;\n $$reject(promise, reason);\n }\n\n function $$reject(promise, reason) {\n promise.$$state.value = reason;\n promise.$$state.status = 2;\n scheduleProcessQueue(promise.$$state);\n }\n\n function notifyPromise(promise, progress) {\n var callbacks = promise.$$state.pending;\n\n if ((promise.$$state.status <= 0) && callbacks && callbacks.length) {\n nextTick(function() {\n var callback, result;\n for (var i = 0, ii = callbacks.length; i < ii; i++) {\n result = callbacks[i][0];\n callback = callbacks[i][3];\n try {\n notifyPromise(result, isFunction(callback) ? callback(progress) : progress);\n } catch (e) {\n exceptionHandler(e);\n }\n }\n });\n }\n }\n\n /**\n * @ngdoc method\n * @name $q#reject\n * @kind function\n *\n * @description\n * Creates a promise that is resolved as rejected with the specified `reason`. This api should be\n * used to forward rejection in a chain of promises. If you are dealing with the last promise in\n * a promise chain, you don't need to worry about it.\n *\n * When comparing deferreds/promises to the familiar behavior of try/catch/throw, think of\n * `reject` as the `throw` keyword in JavaScript. This also means that if you \"catch\" an error via\n * a promise error callback and you want to forward the error to the promise derived from the\n * current promise, you have to \"rethrow\" the error by returning a rejection constructed via\n * `reject`.\n *\n * ```js\n * promiseB = promiseA.then(function(result) {\n * // success: do something and resolve promiseB\n * // with the old or a new result\n * return result;\n * }, function(reason) {\n * // error: handle the error if possible and\n * // resolve promiseB with newPromiseOrValue,\n * // otherwise forward the rejection to promiseB\n * if (canHandle(reason)) {\n * // handle the error and recover\n * return newPromiseOrValue;\n * }\n * return $q.reject(reason);\n * });\n * ```\n *\n * @param {*} reason Constant, message, exception or an object representing the rejection reason.\n * @returns {Promise} Returns a promise that was already resolved as rejected with the `reason`.\n */\n function reject(reason) {\n var result = new Promise();\n rejectPromise(result, reason);\n return result;\n }\n\n function handleCallback(value, resolver, callback) {\n var callbackOutput = null;\n try {\n if (isFunction(callback)) callbackOutput = callback();\n } catch (e) {\n return reject(e);\n }\n if (isPromiseLike(callbackOutput)) {\n return callbackOutput.then(function() {\n return resolver(value);\n }, reject);\n } else {\n return resolver(value);\n }\n }\n\n /**\n * @ngdoc method\n * @name $q#when\n * @kind function\n *\n * @description\n * Wraps an object that might be a value or a (3rd party) then-able promise into a $q promise.\n * This is useful when you are dealing with an object that might or might not be a promise, or if\n * the promise comes from a source that can't be trusted.\n *\n * @param {*} value Value or a promise\n * @param {Function=} successCallback\n * @param {Function=} errorCallback\n * @param {Function=} progressCallback\n * @returns {Promise} Returns a promise of the passed value or promise\n */\n\n\n function when(value, callback, errback, progressBack) {\n var result = new Promise();\n resolvePromise(result, value);\n return result.then(callback, errback, progressBack);\n }\n\n /**\n * @ngdoc method\n * @name $q#resolve\n * @kind function\n *\n * @description\n * Alias of {@link ng.$q#when when} to maintain naming consistency with ES6.\n *\n * @param {*} value Value or a promise\n * @param {Function=} successCallback\n * @param {Function=} errorCallback\n * @param {Function=} progressCallback\n * @returns {Promise} Returns a promise of the passed value or promise\n */\n var resolve = when;\n\n /**\n * @ngdoc method\n * @name $q#all\n * @kind function\n *\n * @description\n * Combines multiple promises into a single promise that is resolved when all of the input\n * promises are resolved.\n *\n * @param {Array.|Object.} promises An array or hash of promises.\n * @returns {Promise} Returns a single promise that will be resolved with an array/hash of values,\n * each value corresponding to the promise at the same index/key in the `promises` array/hash.\n * If any of the promises is resolved with a rejection, this resulting promise will be rejected\n * with the same rejection value.\n */\n\n function all(promises) {\n var result = new Promise(),\n counter = 0,\n results = isArray(promises) ? [] : {};\n\n forEach(promises, function(promise, key) {\n counter++;\n when(promise).then(function(value) {\n results[key] = value;\n if (!(--counter)) resolvePromise(result, results);\n }, function(reason) {\n rejectPromise(result, reason);\n });\n });\n\n if (counter === 0) {\n resolvePromise(result, results);\n }\n\n return result;\n }\n\n /**\n * @ngdoc method\n * @name $q#race\n * @kind function\n *\n * @description\n * Returns a promise that resolves or rejects as soon as one of those promises\n * resolves or rejects, with the value or reason from that promise.\n *\n * @param {Array.|Object.} promises An array or hash of promises.\n * @returns {Promise} a promise that resolves or rejects as soon as one of the `promises`\n * resolves or rejects, with the value or reason from that promise.\n */\n\n function race(promises) {\n var deferred = defer();\n\n forEach(promises, function(promise) {\n when(promise).then(deferred.resolve, deferred.reject);\n });\n\n return deferred.promise;\n }\n\n function $Q(resolver) {\n if (!isFunction(resolver)) {\n throw $qMinErr('norslvr', 'Expected resolverFn, got \\'{0}\\'', resolver);\n }\n\n var promise = new Promise();\n\n function resolveFn(value) {\n resolvePromise(promise, value);\n }\n\n function rejectFn(reason) {\n rejectPromise(promise, reason);\n }\n\n resolver(resolveFn, rejectFn);\n\n return promise;\n }\n\n // Let's make the instanceof operator work for promises, so that\n // `new $q(fn) instanceof $q` would evaluate to true.\n $Q.prototype = Promise.prototype;\n\n $Q.defer = defer;\n $Q.reject = reject;\n $Q.when = when;\n $Q.resolve = resolve;\n $Q.all = all;\n $Q.race = race;\n\n return $Q;\n}\n\n/** @this */\nfunction $$RAFProvider() { //rAF\n this.$get = ['$window', '$timeout', function($window, $timeout) {\n var requestAnimationFrame = $window.requestAnimationFrame ||\n $window.webkitRequestAnimationFrame;\n\n var cancelAnimationFrame = $window.cancelAnimationFrame ||\n $window.webkitCancelAnimationFrame ||\n $window.webkitCancelRequestAnimationFrame;\n\n var rafSupported = !!requestAnimationFrame;\n var raf = rafSupported\n ? function(fn) {\n var id = requestAnimationFrame(fn);\n return function() {\n cancelAnimationFrame(id);\n };\n }\n : function(fn) {\n var timer = $timeout(fn, 16.66, false); // 1000 / 60 = 16.666\n return function() {\n $timeout.cancel(timer);\n };\n };\n\n raf.supported = rafSupported;\n\n return raf;\n }];\n}\n\n/**\n * DESIGN NOTES\n *\n * The design decisions behind the scope are heavily favored for speed and memory consumption.\n *\n * The typical use of scope is to watch the expressions, which most of the time return the same\n * value as last time so we optimize the operation.\n *\n * Closures construction is expensive in terms of speed as well as memory:\n * - No closures, instead use prototypical inheritance for API\n * - Internal state needs to be stored on scope directly, which means that private state is\n * exposed as $$____ properties\n *\n * Loop operations are optimized by using while(count--) { ... }\n * - This means that in order to keep the same order of execution as addition we have to add\n * items to the array at the beginning (unshift) instead of at the end (push)\n *\n * Child scopes are created and removed often\n * - Using an array would be slow since inserts in the middle are expensive; so we use linked lists\n *\n * There are fewer watches than observers. This is why you don't want the observer to be implemented\n * in the same way as watch. Watch requires return of the initialization function which is expensive\n * to construct.\n */\n\n\n/**\n * @ngdoc provider\n * @name $rootScopeProvider\n * @description\n *\n * Provider for the $rootScope service.\n */\n\n/**\n * @ngdoc method\n * @name $rootScopeProvider#digestTtl\n * @description\n *\n * Sets the number of `$digest` iterations the scope should attempt to execute before giving up and\n * assuming that the model is unstable.\n *\n * The current default is 10 iterations.\n *\n * In complex applications it's possible that the dependencies between `$watch`s will result in\n * several digest iterations. However if an application needs more than the default 10 digest\n * iterations for its model to stabilize then you should investigate what is causing the model to\n * continuously change during the digest.\n *\n * Increasing the TTL could have performance implications, so you should not change it without\n * proper justification.\n *\n * @param {number} limit The number of digest iterations.\n */\n\n\n/**\n * @ngdoc service\n * @name $rootScope\n * @this\n *\n * @description\n *\n * Every application has a single root {@link ng.$rootScope.Scope scope}.\n * All other scopes are descendant scopes of the root scope. Scopes provide separation\n * between the model and the view, via a mechanism for watching the model for changes.\n * They also provide event emission/broadcast and subscription facility. See the\n * {@link guide/scope developer guide on scopes}.\n */\nfunction $RootScopeProvider() {\n var TTL = 10;\n var $rootScopeMinErr = minErr('$rootScope');\n var lastDirtyWatch = null;\n var applyAsyncId = null;\n\n this.digestTtl = function(value) {\n if (arguments.length) {\n TTL = value;\n }\n return TTL;\n };\n\n function createChildScopeClass(parent) {\n function ChildScope() {\n this.$$watchers = this.$$nextSibling =\n this.$$childHead = this.$$childTail = null;\n this.$$listeners = {};\n this.$$listenerCount = {};\n this.$$watchersCount = 0;\n this.$id = nextUid();\n this.$$ChildScope = null;\n }\n ChildScope.prototype = parent;\n return ChildScope;\n }\n\n this.$get = ['$exceptionHandler', '$parse', '$browser',\n function($exceptionHandler, $parse, $browser) {\n\n function destroyChildScope($event) {\n $event.currentScope.$$destroyed = true;\n }\n\n function cleanUpScope($scope) {\n\n // Support: IE 9 only\n if (msie === 9) {\n // There is a memory leak in IE9 if all child scopes are not disconnected\n // completely when a scope is destroyed. So this code will recurse up through\n // all this scopes children\n //\n // See issue https://github.com/angular/angular.js/issues/10706\n if ($scope.$$childHead) {\n cleanUpScope($scope.$$childHead);\n }\n if ($scope.$$nextSibling) {\n cleanUpScope($scope.$$nextSibling);\n }\n }\n\n // The code below works around IE9 and V8's memory leaks\n //\n // See:\n // - https://code.google.com/p/v8/issues/detail?id=2073#c26\n // - https://github.com/angular/angular.js/issues/6794#issuecomment-38648909\n // - https://github.com/angular/angular.js/issues/1313#issuecomment-10378451\n\n $scope.$parent = $scope.$$nextSibling = $scope.$$prevSibling = $scope.$$childHead =\n $scope.$$childTail = $scope.$root = $scope.$$watchers = null;\n }\n\n /**\n * @ngdoc type\n * @name $rootScope.Scope\n *\n * @description\n * A root scope can be retrieved using the {@link ng.$rootScope $rootScope} key from the\n * {@link auto.$injector $injector}. Child scopes are created using the\n * {@link ng.$rootScope.Scope#$new $new()} method. (Most scopes are created automatically when\n * compiled HTML template is executed.) See also the {@link guide/scope Scopes guide} for\n * an in-depth introduction and usage examples.\n *\n *\n * # Inheritance\n * A scope can inherit from a parent scope, as in this example:\n * ```js\n var parent = $rootScope;\n var child = parent.$new();\n\n parent.salutation = \"Hello\";\n expect(child.salutation).toEqual('Hello');\n\n child.salutation = \"Welcome\";\n expect(child.salutation).toEqual('Welcome');\n expect(parent.salutation).toEqual('Hello');\n * ```\n *\n * When interacting with `Scope` in tests, additional helper methods are available on the\n * instances of `Scope` type. See {@link ngMock.$rootScope.Scope ngMock Scope} for additional\n * details.\n *\n *\n * @param {Object.=} providers Map of service factory which need to be\n * provided for the current scope. Defaults to {@link ng}.\n * @param {Object.=} instanceCache Provides pre-instantiated services which should\n * append/override services provided by `providers`. This is handy\n * when unit-testing and having the need to override a default\n * service.\n * @returns {Object} Newly created scope.\n *\n */\n function Scope() {\n this.$id = nextUid();\n this.$$phase = this.$parent = this.$$watchers =\n this.$$nextSibling = this.$$prevSibling =\n this.$$childHead = this.$$childTail = null;\n this.$root = this;\n this.$$destroyed = false;\n this.$$listeners = {};\n this.$$listenerCount = {};\n this.$$watchersCount = 0;\n this.$$isolateBindings = null;\n }\n\n /**\n * @ngdoc property\n * @name $rootScope.Scope#$id\n *\n * @description\n * Unique scope ID (monotonically increasing) useful for debugging.\n */\n\n /**\n * @ngdoc property\n * @name $rootScope.Scope#$parent\n *\n * @description\n * Reference to the parent scope.\n */\n\n /**\n * @ngdoc property\n * @name $rootScope.Scope#$root\n *\n * @description\n * Reference to the root scope.\n */\n\n Scope.prototype = {\n constructor: Scope,\n /**\n * @ngdoc method\n * @name $rootScope.Scope#$new\n * @kind function\n *\n * @description\n * Creates a new child {@link ng.$rootScope.Scope scope}.\n *\n * The parent scope will propagate the {@link ng.$rootScope.Scope#$digest $digest()} event.\n * The scope can be removed from the scope hierarchy using {@link ng.$rootScope.Scope#$destroy $destroy()}.\n *\n * {@link ng.$rootScope.Scope#$destroy $destroy()} must be called on a scope when it is\n * desired for the scope and its child scopes to be permanently detached from the parent and\n * thus stop participating in model change detection and listener notification by invoking.\n *\n * @param {boolean} isolate If true, then the scope does not prototypically inherit from the\n * parent scope. The scope is isolated, as it can not see parent scope properties.\n * When creating widgets, it is useful for the widget to not accidentally read parent\n * state.\n *\n * @param {Scope} [parent=this] The {@link ng.$rootScope.Scope `Scope`} that will be the `$parent`\n * of the newly created scope. Defaults to `this` scope if not provided.\n * This is used when creating a transclude scope to correctly place it\n * in the scope hierarchy while maintaining the correct prototypical\n * inheritance.\n *\n * @returns {Object} The newly created child scope.\n *\n */\n $new: function(isolate, parent) {\n var child;\n\n parent = parent || this;\n\n if (isolate) {\n child = new Scope();\n child.$root = this.$root;\n } else {\n // Only create a child scope class if somebody asks for one,\n // but cache it to allow the VM to optimize lookups.\n if (!this.$$ChildScope) {\n this.$$ChildScope = createChildScopeClass(this);\n }\n child = new this.$$ChildScope();\n }\n child.$parent = parent;\n child.$$prevSibling = parent.$$childTail;\n if (parent.$$childHead) {\n parent.$$childTail.$$nextSibling = child;\n parent.$$childTail = child;\n } else {\n parent.$$childHead = parent.$$childTail = child;\n }\n\n // When the new scope is not isolated or we inherit from `this`, and\n // the parent scope is destroyed, the property `$$destroyed` is inherited\n // prototypically. In all other cases, this property needs to be set\n // when the parent scope is destroyed.\n // The listener needs to be added after the parent is set\n if (isolate || parent !== this) child.$on('$destroy', destroyChildScope);\n\n return child;\n },\n\n /**\n * @ngdoc method\n * @name $rootScope.Scope#$watch\n * @kind function\n *\n * @description\n * Registers a `listener` callback to be executed whenever the `watchExpression` changes.\n *\n * - The `watchExpression` is called on every call to {@link ng.$rootScope.Scope#$digest\n * $digest()} and should return the value that will be watched. (`watchExpression` should not change\n * its value when executed multiple times with the same input because it may be executed multiple\n * times by {@link ng.$rootScope.Scope#$digest $digest()}. That is, `watchExpression` should be\n * [idempotent](http://en.wikipedia.org/wiki/Idempotence).)\n * - The `listener` is called only when the value from the current `watchExpression` and the\n * previous call to `watchExpression` are not equal (with the exception of the initial run,\n * see below). Inequality is determined according to reference inequality,\n * [strict comparison](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Comparison_Operators)\n * via the `!==` Javascript operator, unless `objectEquality == true`\n * (see next point)\n * - When `objectEquality == true`, inequality of the `watchExpression` is determined\n * according to the {@link angular.equals} function. To save the value of the object for\n * later comparison, the {@link angular.copy} function is used. This therefore means that\n * watching complex objects will have adverse memory and performance implications.\n * - This should not be used to watch for changes in objects that are\n * or contain [File](https://developer.mozilla.org/docs/Web/API/File) objects due to limitations with {@link angular.copy `angular.copy`}.\n * - The watch `listener` may change the model, which may trigger other `listener`s to fire.\n * This is achieved by rerunning the watchers until no changes are detected. The rerun\n * iteration limit is 10 to prevent an infinite loop deadlock.\n *\n *\n * If you want to be notified whenever {@link ng.$rootScope.Scope#$digest $digest} is called,\n * you can register a `watchExpression` function with no `listener`. (Be prepared for\n * multiple calls to your `watchExpression` because it will execute multiple times in a\n * single {@link ng.$rootScope.Scope#$digest $digest} cycle if a change is detected.)\n *\n * After a watcher is registered with the scope, the `listener` fn is called asynchronously\n * (via {@link ng.$rootScope.Scope#$evalAsync $evalAsync}) to initialize the\n * watcher. In rare cases, this is undesirable because the listener is called when the result\n * of `watchExpression` didn't change. To detect this scenario within the `listener` fn, you\n * can compare the `newVal` and `oldVal`. If these two values are identical (`===`) then the\n * listener was called due to initialization.\n *\n *\n *\n * # Example\n * ```js\n // let's assume that scope was dependency injected as the $rootScope\n var scope = $rootScope;\n scope.name = 'misko';\n scope.counter = 0;\n\n expect(scope.counter).toEqual(0);\n scope.$watch('name', function(newValue, oldValue) {\n scope.counter = scope.counter + 1;\n });\n expect(scope.counter).toEqual(0);\n\n scope.$digest();\n // the listener is always called during the first $digest loop after it was registered\n expect(scope.counter).toEqual(1);\n\n scope.$digest();\n // but now it will not be called unless the value changes\n expect(scope.counter).toEqual(1);\n\n scope.name = 'adam';\n scope.$digest();\n expect(scope.counter).toEqual(2);\n\n\n\n // Using a function as a watchExpression\n var food;\n scope.foodCounter = 0;\n expect(scope.foodCounter).toEqual(0);\n scope.$watch(\n // This function returns the value being watched. It is called for each turn of the $digest loop\n function() { return food; },\n // This is the change listener, called when the value returned from the above function changes\n function(newValue, oldValue) {\n if ( newValue !== oldValue ) {\n // Only increment the counter if the value changed\n scope.foodCounter = scope.foodCounter + 1;\n }\n }\n );\n // No digest has been run so the counter will be zero\n expect(scope.foodCounter).toEqual(0);\n\n // Run the digest but since food has not changed count will still be zero\n scope.$digest();\n expect(scope.foodCounter).toEqual(0);\n\n // Update food and run digest. Now the counter will increment\n food = 'cheeseburger';\n scope.$digest();\n expect(scope.foodCounter).toEqual(1);\n\n * ```\n *\n *\n *\n * @param {(function()|string)} watchExpression Expression that is evaluated on each\n * {@link ng.$rootScope.Scope#$digest $digest} cycle. A change in the return value triggers\n * a call to the `listener`.\n *\n * - `string`: Evaluated as {@link guide/expression expression}\n * - `function(scope)`: called with current `scope` as a parameter.\n * @param {function(newVal, oldVal, scope)} listener Callback called whenever the value\n * of `watchExpression` changes.\n *\n * - `newVal` contains the current value of the `watchExpression`\n * - `oldVal` contains the previous value of the `watchExpression`\n * - `scope` refers to the current scope\n * @param {boolean=} [objectEquality=false] Compare for object equality using {@link angular.equals} instead of\n * comparing for reference equality.\n * @returns {function()} Returns a deregistration function for this listener.\n */\n $watch: function(watchExp, listener, objectEquality, prettyPrintExpression) {\n var get = $parse(watchExp);\n\n if (get.$$watchDelegate) {\n return get.$$watchDelegate(this, listener, objectEquality, get, watchExp);\n }\n var scope = this,\n array = scope.$$watchers,\n watcher = {\n fn: listener,\n last: initWatchVal,\n get: get,\n exp: prettyPrintExpression || watchExp,\n eq: !!objectEquality\n };\n\n lastDirtyWatch = null;\n\n if (!isFunction(listener)) {\n watcher.fn = noop;\n }\n\n if (!array) {\n array = scope.$$watchers = [];\n }\n // we use unshift since we use a while loop in $digest for speed.\n // the while loop reads in reverse order.\n array.unshift(watcher);\n incrementWatchersCount(this, 1);\n\n return function deregisterWatch() {\n if (arrayRemove(array, watcher) >= 0) {\n incrementWatchersCount(scope, -1);\n }\n lastDirtyWatch = null;\n };\n },\n\n /**\n * @ngdoc method\n * @name $rootScope.Scope#$watchGroup\n * @kind function\n *\n * @description\n * A variant of {@link ng.$rootScope.Scope#$watch $watch()} where it watches an array of `watchExpressions`.\n * If any one expression in the collection changes the `listener` is executed.\n *\n * - The items in the `watchExpressions` array are observed via the standard `$watch` operation. Their return\n * values are examined for changes on every call to `$digest`.\n * - The `listener` is called whenever any expression in the `watchExpressions` array changes.\n *\n * @param {Array.} watchExpressions Array of expressions that will be individually\n * watched using {@link ng.$rootScope.Scope#$watch $watch()}\n *\n * @param {function(newValues, oldValues, scope)} listener Callback called whenever the return value of any\n * expression in `watchExpressions` changes\n * The `newValues` array contains the current values of the `watchExpressions`, with the indexes matching\n * those of `watchExpression`\n * and the `oldValues` array contains the previous values of the `watchExpressions`, with the indexes matching\n * those of `watchExpression`\n * The `scope` refers to the current scope.\n * @returns {function()} Returns a de-registration function for all listeners.\n */\n $watchGroup: function(watchExpressions, listener) {\n var oldValues = new Array(watchExpressions.length);\n var newValues = new Array(watchExpressions.length);\n var deregisterFns = [];\n var self = this;\n var changeReactionScheduled = false;\n var firstRun = true;\n\n if (!watchExpressions.length) {\n // No expressions means we call the listener ASAP\n var shouldCall = true;\n self.$evalAsync(function() {\n if (shouldCall) listener(newValues, newValues, self);\n });\n return function deregisterWatchGroup() {\n shouldCall = false;\n };\n }\n\n if (watchExpressions.length === 1) {\n // Special case size of one\n return this.$watch(watchExpressions[0], function watchGroupAction(value, oldValue, scope) {\n newValues[0] = value;\n oldValues[0] = oldValue;\n listener(newValues, (value === oldValue) ? newValues : oldValues, scope);\n });\n }\n\n forEach(watchExpressions, function(expr, i) {\n var unwatchFn = self.$watch(expr, function watchGroupSubAction(value, oldValue) {\n newValues[i] = value;\n oldValues[i] = oldValue;\n if (!changeReactionScheduled) {\n changeReactionScheduled = true;\n self.$evalAsync(watchGroupAction);\n }\n });\n deregisterFns.push(unwatchFn);\n });\n\n function watchGroupAction() {\n changeReactionScheduled = false;\n\n if (firstRun) {\n firstRun = false;\n listener(newValues, newValues, self);\n } else {\n listener(newValues, oldValues, self);\n }\n }\n\n return function deregisterWatchGroup() {\n while (deregisterFns.length) {\n deregisterFns.shift()();\n }\n };\n },\n\n\n /**\n * @ngdoc method\n * @name $rootScope.Scope#$watchCollection\n * @kind function\n *\n * @description\n * Shallow watches the properties of an object and fires whenever any of the properties change\n * (for arrays, this implies watching the array items; for object maps, this implies watching\n * the properties). If a change is detected, the `listener` callback is fired.\n *\n * - The `obj` collection is observed via standard $watch operation and is examined on every\n * call to $digest() to see if any items have been added, removed, or moved.\n * - The `listener` is called whenever anything within the `obj` has changed. Examples include\n * adding, removing, and moving items belonging to an object or array.\n *\n *\n * # Example\n * ```js\n $scope.names = ['igor', 'matias', 'misko', 'james'];\n $scope.dataCount = 4;\n\n $scope.$watchCollection('names', function(newNames, oldNames) {\n $scope.dataCount = newNames.length;\n });\n\n expect($scope.dataCount).toEqual(4);\n $scope.$digest();\n\n //still at 4 ... no changes\n expect($scope.dataCount).toEqual(4);\n\n $scope.names.pop();\n $scope.$digest();\n\n //now there's been a change\n expect($scope.dataCount).toEqual(3);\n * ```\n *\n *\n * @param {string|function(scope)} obj Evaluated as {@link guide/expression expression}. The\n * expression value should evaluate to an object or an array which is observed on each\n * {@link ng.$rootScope.Scope#$digest $digest} cycle. Any shallow change within the\n * collection will trigger a call to the `listener`.\n *\n * @param {function(newCollection, oldCollection, scope)} listener a callback function called\n * when a change is detected.\n * - The `newCollection` object is the newly modified data obtained from the `obj` expression\n * - The `oldCollection` object is a copy of the former collection data.\n * Due to performance considerations, the`oldCollection` value is computed only if the\n * `listener` function declares two or more arguments.\n * - The `scope` argument refers to the current scope.\n *\n * @returns {function()} Returns a de-registration function for this listener. When the\n * de-registration function is executed, the internal watch operation is terminated.\n */\n $watchCollection: function(obj, listener) {\n $watchCollectionInterceptor.$stateful = true;\n\n var self = this;\n // the current value, updated on each dirty-check run\n var newValue;\n // a shallow copy of the newValue from the last dirty-check run,\n // updated to match newValue during dirty-check run\n var oldValue;\n // a shallow copy of the newValue from when the last change happened\n var veryOldValue;\n // only track veryOldValue if the listener is asking for it\n var trackVeryOldValue = (listener.length > 1);\n var changeDetected = 0;\n var changeDetector = $parse(obj, $watchCollectionInterceptor);\n var internalArray = [];\n var internalObject = {};\n var initRun = true;\n var oldLength = 0;\n\n function $watchCollectionInterceptor(_value) {\n newValue = _value;\n var newLength, key, bothNaN, newItem, oldItem;\n\n // If the new value is undefined, then return undefined as the watch may be a one-time watch\n if (isUndefined(newValue)) return;\n\n if (!isObject(newValue)) { // if primitive\n if (oldValue !== newValue) {\n oldValue = newValue;\n changeDetected++;\n }\n } else if (isArrayLike(newValue)) {\n if (oldValue !== internalArray) {\n // we are transitioning from something which was not an array into array.\n oldValue = internalArray;\n oldLength = oldValue.length = 0;\n changeDetected++;\n }\n\n newLength = newValue.length;\n\n if (oldLength !== newLength) {\n // if lengths do not match we need to trigger change notification\n changeDetected++;\n oldValue.length = oldLength = newLength;\n }\n // copy the items to oldValue and look for changes.\n for (var i = 0; i < newLength; i++) {\n oldItem = oldValue[i];\n newItem = newValue[i];\n\n // eslint-disable-next-line no-self-compare\n bothNaN = (oldItem !== oldItem) && (newItem !== newItem);\n if (!bothNaN && (oldItem !== newItem)) {\n changeDetected++;\n oldValue[i] = newItem;\n }\n }\n } else {\n if (oldValue !== internalObject) {\n // we are transitioning from something which was not an object into object.\n oldValue = internalObject = {};\n oldLength = 0;\n changeDetected++;\n }\n // copy the items to oldValue and look for changes.\n newLength = 0;\n for (key in newValue) {\n if (hasOwnProperty.call(newValue, key)) {\n newLength++;\n newItem = newValue[key];\n oldItem = oldValue[key];\n\n if (key in oldValue) {\n // eslint-disable-next-line no-self-compare\n bothNaN = (oldItem !== oldItem) && (newItem !== newItem);\n if (!bothNaN && (oldItem !== newItem)) {\n changeDetected++;\n oldValue[key] = newItem;\n }\n } else {\n oldLength++;\n oldValue[key] = newItem;\n changeDetected++;\n }\n }\n }\n if (oldLength > newLength) {\n // we used to have more keys, need to find them and destroy them.\n changeDetected++;\n for (key in oldValue) {\n if (!hasOwnProperty.call(newValue, key)) {\n oldLength--;\n delete oldValue[key];\n }\n }\n }\n }\n return changeDetected;\n }\n\n function $watchCollectionAction() {\n if (initRun) {\n initRun = false;\n listener(newValue, newValue, self);\n } else {\n listener(newValue, veryOldValue, self);\n }\n\n // make a copy for the next time a collection is changed\n if (trackVeryOldValue) {\n if (!isObject(newValue)) {\n //primitive\n veryOldValue = newValue;\n } else if (isArrayLike(newValue)) {\n veryOldValue = new Array(newValue.length);\n for (var i = 0; i < newValue.length; i++) {\n veryOldValue[i] = newValue[i];\n }\n } else { // if object\n veryOldValue = {};\n for (var key in newValue) {\n if (hasOwnProperty.call(newValue, key)) {\n veryOldValue[key] = newValue[key];\n }\n }\n }\n }\n }\n\n return this.$watch(changeDetector, $watchCollectionAction);\n },\n\n /**\n * @ngdoc method\n * @name $rootScope.Scope#$digest\n * @kind function\n *\n * @description\n * Processes all of the {@link ng.$rootScope.Scope#$watch watchers} of the current scope and\n * its children. Because a {@link ng.$rootScope.Scope#$watch watcher}'s listener can change\n * the model, the `$digest()` keeps calling the {@link ng.$rootScope.Scope#$watch watchers}\n * until no more listeners are firing. This means that it is possible to get into an infinite\n * loop. This function will throw `'Maximum iteration limit exceeded.'` if the number of\n * iterations exceeds 10.\n *\n * Usually, you don't call `$digest()` directly in\n * {@link ng.directive:ngController controllers} or in\n * {@link ng.$compileProvider#directive directives}.\n * Instead, you should call {@link ng.$rootScope.Scope#$apply $apply()} (typically from within\n * a {@link ng.$compileProvider#directive directive}), which will force a `$digest()`.\n *\n * If you want to be notified whenever `$digest()` is called,\n * you can register a `watchExpression` function with\n * {@link ng.$rootScope.Scope#$watch $watch()} with no `listener`.\n *\n * In unit tests, you may need to call `$digest()` to simulate the scope life cycle.\n *\n * # Example\n * ```js\n var scope = ...;\n scope.name = 'misko';\n scope.counter = 0;\n\n expect(scope.counter).toEqual(0);\n scope.$watch('name', function(newValue, oldValue) {\n scope.counter = scope.counter + 1;\n });\n expect(scope.counter).toEqual(0);\n\n scope.$digest();\n // the listener is always called during the first $digest loop after it was registered\n expect(scope.counter).toEqual(1);\n\n scope.$digest();\n // but now it will not be called unless the value changes\n expect(scope.counter).toEqual(1);\n\n scope.name = 'adam';\n scope.$digest();\n expect(scope.counter).toEqual(2);\n * ```\n *\n */\n $digest: function() {\n var watch, value, last, fn, get,\n watchers,\n length,\n dirty, ttl = TTL,\n next, current, target = this,\n watchLog = [],\n logIdx, asyncTask;\n\n beginPhase('$digest');\n // Check for changes to browser url that happened in sync before the call to $digest\n $browser.$$checkUrlChange();\n\n if (this === $rootScope && applyAsyncId !== null) {\n // If this is the root scope, and $applyAsync has scheduled a deferred $apply(), then\n // cancel the scheduled $apply and flush the queue of expressions to be evaluated.\n $browser.defer.cancel(applyAsyncId);\n flushApplyAsync();\n }\n\n lastDirtyWatch = null;\n\n do { // \"while dirty\" loop\n dirty = false;\n current = target;\n\n // It's safe for asyncQueuePosition to be a local variable here because this loop can't\n // be reentered recursively. Calling $digest from a function passed to $applyAsync would\n // lead to a '$digest already in progress' error.\n for (var asyncQueuePosition = 0; asyncQueuePosition < asyncQueue.length; asyncQueuePosition++) {\n try {\n asyncTask = asyncQueue[asyncQueuePosition];\n asyncTask.scope.$eval(asyncTask.expression, asyncTask.locals);\n } catch (e) {\n $exceptionHandler(e);\n }\n lastDirtyWatch = null;\n }\n asyncQueue.length = 0;\n\n traverseScopesLoop:\n do { // \"traverse the scopes\" loop\n if ((watchers = current.$$watchers)) {\n // process our watches\n length = watchers.length;\n while (length--) {\n try {\n watch = watchers[length];\n // Most common watches are on primitives, in which case we can short\n // circuit it with === operator, only when === fails do we use .equals\n if (watch) {\n get = watch.get;\n if ((value = get(current)) !== (last = watch.last) &&\n !(watch.eq\n ? equals(value, last)\n : (isNumberNaN(value) && isNumberNaN(last)))) {\n dirty = true;\n lastDirtyWatch = watch;\n watch.last = watch.eq ? copy(value, null) : value;\n fn = watch.fn;\n fn(value, ((last === initWatchVal) ? value : last), current);\n if (ttl < 5) {\n logIdx = 4 - ttl;\n if (!watchLog[logIdx]) watchLog[logIdx] = [];\n watchLog[logIdx].push({\n msg: isFunction(watch.exp) ? 'fn: ' + (watch.exp.name || watch.exp.toString()) : watch.exp,\n newVal: value,\n oldVal: last\n });\n }\n } else if (watch === lastDirtyWatch) {\n // If the most recently dirty watcher is now clean, short circuit since the remaining watchers\n // have already been tested.\n dirty = false;\n break traverseScopesLoop;\n }\n }\n } catch (e) {\n $exceptionHandler(e);\n }\n }\n }\n\n // Insanity Warning: scope depth-first traversal\n // yes, this code is a bit crazy, but it works and we have tests to prove it!\n // this piece should be kept in sync with the traversal in $broadcast\n if (!(next = ((current.$$watchersCount && current.$$childHead) ||\n (current !== target && current.$$nextSibling)))) {\n while (current !== target && !(next = current.$$nextSibling)) {\n current = current.$parent;\n }\n }\n } while ((current = next));\n\n // `break traverseScopesLoop;` takes us to here\n\n if ((dirty || asyncQueue.length) && !(ttl--)) {\n clearPhase();\n throw $rootScopeMinErr('infdig',\n '{0} $digest() iterations reached. Aborting!\\n' +\n 'Watchers fired in the last 5 iterations: {1}',\n TTL, watchLog);\n }\n\n } while (dirty || asyncQueue.length);\n\n clearPhase();\n\n // postDigestQueuePosition isn't local here because this loop can be reentered recursively.\n while (postDigestQueuePosition < postDigestQueue.length) {\n try {\n postDigestQueue[postDigestQueuePosition++]();\n } catch (e) {\n $exceptionHandler(e);\n }\n }\n postDigestQueue.length = postDigestQueuePosition = 0;\n },\n\n\n /**\n * @ngdoc event\n * @name $rootScope.Scope#$destroy\n * @eventType broadcast on scope being destroyed\n *\n * @description\n * Broadcasted when a scope and its children are being destroyed.\n *\n * Note that, in AngularJS, there is also a `$destroy` jQuery event, which can be used to\n * clean up DOM bindings before an element is removed from the DOM.\n */\n\n /**\n * @ngdoc method\n * @name $rootScope.Scope#$destroy\n * @kind function\n *\n * @description\n * Removes the current scope (and all of its children) from the parent scope. Removal implies\n * that calls to {@link ng.$rootScope.Scope#$digest $digest()} will no longer\n * propagate to the current scope and its children. Removal also implies that the current\n * scope is eligible for garbage collection.\n *\n * The `$destroy()` is usually used by directives such as\n * {@link ng.directive:ngRepeat ngRepeat} for managing the\n * unrolling of the loop.\n *\n * Just before a scope is destroyed, a `$destroy` event is broadcasted on this scope.\n * Application code can register a `$destroy` event handler that will give it a chance to\n * perform any necessary cleanup.\n *\n * Note that, in AngularJS, there is also a `$destroy` jQuery event, which can be used to\n * clean up DOM bindings before an element is removed from the DOM.\n */\n $destroy: function() {\n // We can't destroy a scope that has been already destroyed.\n if (this.$$destroyed) return;\n var parent = this.$parent;\n\n this.$broadcast('$destroy');\n this.$$destroyed = true;\n\n if (this === $rootScope) {\n //Remove handlers attached to window when $rootScope is removed\n $browser.$$applicationDestroyed();\n }\n\n incrementWatchersCount(this, -this.$$watchersCount);\n for (var eventName in this.$$listenerCount) {\n decrementListenerCount(this, this.$$listenerCount[eventName], eventName);\n }\n\n // sever all the references to parent scopes (after this cleanup, the current scope should\n // not be retained by any of our references and should be eligible for garbage collection)\n if (parent && parent.$$childHead === this) parent.$$childHead = this.$$nextSibling;\n if (parent && parent.$$childTail === this) parent.$$childTail = this.$$prevSibling;\n if (this.$$prevSibling) this.$$prevSibling.$$nextSibling = this.$$nextSibling;\n if (this.$$nextSibling) this.$$nextSibling.$$prevSibling = this.$$prevSibling;\n\n // Disable listeners, watchers and apply/digest methods\n this.$destroy = this.$digest = this.$apply = this.$evalAsync = this.$applyAsync = noop;\n this.$on = this.$watch = this.$watchGroup = function() { return noop; };\n this.$$listeners = {};\n\n // Disconnect the next sibling to prevent `cleanUpScope` destroying those too\n this.$$nextSibling = null;\n cleanUpScope(this);\n },\n\n /**\n * @ngdoc method\n * @name $rootScope.Scope#$eval\n * @kind function\n *\n * @description\n * Executes the `expression` on the current scope and returns the result. Any exceptions in\n * the expression are propagated (uncaught). This is useful when evaluating Angular\n * expressions.\n *\n * # Example\n * ```js\n var scope = ng.$rootScope.Scope();\n scope.a = 1;\n scope.b = 2;\n\n expect(scope.$eval('a+b')).toEqual(3);\n expect(scope.$eval(function(scope){ return scope.a + scope.b; })).toEqual(3);\n * ```\n *\n * @param {(string|function())=} expression An angular expression to be executed.\n *\n * - `string`: execute using the rules as defined in {@link guide/expression expression}.\n * - `function(scope)`: execute the function with the current `scope` parameter.\n *\n * @param {(object)=} locals Local variables object, useful for overriding values in scope.\n * @returns {*} The result of evaluating the expression.\n */\n $eval: function(expr, locals) {\n return $parse(expr)(this, locals);\n },\n\n /**\n * @ngdoc method\n * @name $rootScope.Scope#$evalAsync\n * @kind function\n *\n * @description\n * Executes the expression on the current scope at a later point in time.\n *\n * The `$evalAsync` makes no guarantees as to when the `expression` will be executed, only\n * that:\n *\n * - it will execute after the function that scheduled the evaluation (preferably before DOM\n * rendering).\n * - at least one {@link ng.$rootScope.Scope#$digest $digest cycle} will be performed after\n * `expression` execution.\n *\n * Any exceptions from the execution of the expression are forwarded to the\n * {@link ng.$exceptionHandler $exceptionHandler} service.\n *\n * __Note:__ if this function is called outside of a `$digest` cycle, a new `$digest` cycle\n * will be scheduled. However, it is encouraged to always call code that changes the model\n * from within an `$apply` call. That includes code evaluated via `$evalAsync`.\n *\n * @param {(string|function())=} expression An angular expression to be executed.\n *\n * - `string`: execute using the rules as defined in {@link guide/expression expression}.\n * - `function(scope)`: execute the function with the current `scope` parameter.\n *\n * @param {(object)=} locals Local variables object, useful for overriding values in scope.\n */\n $evalAsync: function(expr, locals) {\n // if we are outside of an $digest loop and this is the first time we are scheduling async\n // task also schedule async auto-flush\n if (!$rootScope.$$phase && !asyncQueue.length) {\n $browser.defer(function() {\n if (asyncQueue.length) {\n $rootScope.$digest();\n }\n });\n }\n\n asyncQueue.push({scope: this, expression: $parse(expr), locals: locals});\n },\n\n $$postDigest: function(fn) {\n postDigestQueue.push(fn);\n },\n\n /**\n * @ngdoc method\n * @name $rootScope.Scope#$apply\n * @kind function\n *\n * @description\n * `$apply()` is used to execute an expression in angular from outside of the angular\n * framework. (For example from browser DOM events, setTimeout, XHR or third party libraries).\n * Because we are calling into the angular framework we need to perform proper scope life\n * cycle of {@link ng.$exceptionHandler exception handling},\n * {@link ng.$rootScope.Scope#$digest executing watches}.\n *\n * ## Life cycle\n *\n * # Pseudo-Code of `$apply()`\n * ```js\n function $apply(expr) {\n try {\n return $eval(expr);\n } catch (e) {\n $exceptionHandler(e);\n } finally {\n $root.$digest();\n }\n }\n * ```\n *\n *\n * Scope's `$apply()` method transitions through the following stages:\n *\n * 1. The {@link guide/expression expression} is executed using the\n * {@link ng.$rootScope.Scope#$eval $eval()} method.\n * 2. Any exceptions from the execution of the expression are forwarded to the\n * {@link ng.$exceptionHandler $exceptionHandler} service.\n * 3. The {@link ng.$rootScope.Scope#$watch watch} listeners are fired immediately after the\n * expression was executed using the {@link ng.$rootScope.Scope#$digest $digest()} method.\n *\n *\n * @param {(string|function())=} exp An angular expression to be executed.\n *\n * - `string`: execute using the rules as defined in {@link guide/expression expression}.\n * - `function(scope)`: execute the function with current `scope` parameter.\n *\n * @returns {*} The result of evaluating the expression.\n */\n $apply: function(expr) {\n try {\n beginPhase('$apply');\n try {\n return this.$eval(expr);\n } finally {\n clearPhase();\n }\n } catch (e) {\n $exceptionHandler(e);\n } finally {\n try {\n $rootScope.$digest();\n } catch (e) {\n $exceptionHandler(e);\n // eslint-disable-next-line no-unsafe-finally\n throw e;\n }\n }\n },\n\n /**\n * @ngdoc method\n * @name $rootScope.Scope#$applyAsync\n * @kind function\n *\n * @description\n * Schedule the invocation of $apply to occur at a later time. The actual time difference\n * varies across browsers, but is typically around ~10 milliseconds.\n *\n * This can be used to queue up multiple expressions which need to be evaluated in the same\n * digest.\n *\n * @param {(string|function())=} exp An angular expression to be executed.\n *\n * - `string`: execute using the rules as defined in {@link guide/expression expression}.\n * - `function(scope)`: execute the function with current `scope` parameter.\n */\n $applyAsync: function(expr) {\n var scope = this;\n if (expr) {\n applyAsyncQueue.push($applyAsyncExpression);\n }\n expr = $parse(expr);\n scheduleApplyAsync();\n\n function $applyAsyncExpression() {\n scope.$eval(expr);\n }\n },\n\n /**\n * @ngdoc method\n * @name $rootScope.Scope#$on\n * @kind function\n *\n * @description\n * Listens on events of a given type. See {@link ng.$rootScope.Scope#$emit $emit} for\n * discussion of event life cycle.\n *\n * The event listener function format is: `function(event, args...)`. The `event` object\n * passed into the listener has the following attributes:\n *\n * - `targetScope` - `{Scope}`: the scope on which the event was `$emit`-ed or\n * `$broadcast`-ed.\n * - `currentScope` - `{Scope}`: the scope that is currently handling the event. Once the\n * event propagates through the scope hierarchy, this property is set to null.\n * - `name` - `{string}`: name of the event.\n * - `stopPropagation` - `{function=}`: calling `stopPropagation` function will cancel\n * further event propagation (available only for events that were `$emit`-ed).\n * - `preventDefault` - `{function}`: calling `preventDefault` sets `defaultPrevented` flag\n * to true.\n * - `defaultPrevented` - `{boolean}`: true if `preventDefault` was called.\n *\n * @param {string} name Event name to listen on.\n * @param {function(event, ...args)} listener Function to call when the event is emitted.\n * @returns {function()} Returns a deregistration function for this listener.\n */\n $on: function(name, listener) {\n var namedListeners = this.$$listeners[name];\n if (!namedListeners) {\n this.$$listeners[name] = namedListeners = [];\n }\n namedListeners.push(listener);\n\n var current = this;\n do {\n if (!current.$$listenerCount[name]) {\n current.$$listenerCount[name] = 0;\n }\n current.$$listenerCount[name]++;\n } while ((current = current.$parent));\n\n var self = this;\n return function() {\n var indexOfListener = namedListeners.indexOf(listener);\n if (indexOfListener !== -1) {\n namedListeners[indexOfListener] = null;\n decrementListenerCount(self, 1, name);\n }\n };\n },\n\n\n /**\n * @ngdoc method\n * @name $rootScope.Scope#$emit\n * @kind function\n *\n * @description\n * Dispatches an event `name` upwards through the scope hierarchy notifying the\n * registered {@link ng.$rootScope.Scope#$on} listeners.\n *\n * The event life cycle starts at the scope on which `$emit` was called. All\n * {@link ng.$rootScope.Scope#$on listeners} listening for `name` event on this scope get\n * notified. Afterwards, the event traverses upwards toward the root scope and calls all\n * registered listeners along the way. The event will stop propagating if one of the listeners\n * cancels it.\n *\n * Any exception emitted from the {@link ng.$rootScope.Scope#$on listeners} will be passed\n * onto the {@link ng.$exceptionHandler $exceptionHandler} service.\n *\n * @param {string} name Event name to emit.\n * @param {...*} args Optional one or more arguments which will be passed onto the event listeners.\n * @return {Object} Event object (see {@link ng.$rootScope.Scope#$on}).\n */\n $emit: function(name, args) {\n var empty = [],\n namedListeners,\n scope = this,\n stopPropagation = false,\n event = {\n name: name,\n targetScope: scope,\n stopPropagation: function() {stopPropagation = true;},\n preventDefault: function() {\n event.defaultPrevented = true;\n },\n defaultPrevented: false\n },\n listenerArgs = concat([event], arguments, 1),\n i, length;\n\n do {\n namedListeners = scope.$$listeners[name] || empty;\n event.currentScope = scope;\n for (i = 0, length = namedListeners.length; i < length; i++) {\n\n // if listeners were deregistered, defragment the array\n if (!namedListeners[i]) {\n namedListeners.splice(i, 1);\n i--;\n length--;\n continue;\n }\n try {\n //allow all listeners attached to the current scope to run\n namedListeners[i].apply(null, listenerArgs);\n } catch (e) {\n $exceptionHandler(e);\n }\n }\n //if any listener on the current scope stops propagation, prevent bubbling\n if (stopPropagation) {\n event.currentScope = null;\n return event;\n }\n //traverse upwards\n scope = scope.$parent;\n } while (scope);\n\n event.currentScope = null;\n\n return event;\n },\n\n\n /**\n * @ngdoc method\n * @name $rootScope.Scope#$broadcast\n * @kind function\n *\n * @description\n * Dispatches an event `name` downwards to all child scopes (and their children) notifying the\n * registered {@link ng.$rootScope.Scope#$on} listeners.\n *\n * The event life cycle starts at the scope on which `$broadcast` was called. All\n * {@link ng.$rootScope.Scope#$on listeners} listening for `name` event on this scope get\n * notified. Afterwards, the event propagates to all direct and indirect scopes of the current\n * scope and calls all registered listeners along the way. The event cannot be canceled.\n *\n * Any exception emitted from the {@link ng.$rootScope.Scope#$on listeners} will be passed\n * onto the {@link ng.$exceptionHandler $exceptionHandler} service.\n *\n * @param {string} name Event name to broadcast.\n * @param {...*} args Optional one or more arguments which will be passed onto the event listeners.\n * @return {Object} Event object, see {@link ng.$rootScope.Scope#$on}\n */\n $broadcast: function(name, args) {\n var target = this,\n current = target,\n next = target,\n event = {\n name: name,\n targetScope: target,\n preventDefault: function() {\n event.defaultPrevented = true;\n },\n defaultPrevented: false\n };\n\n if (!target.$$listenerCount[name]) return event;\n\n var listenerArgs = concat([event], arguments, 1),\n listeners, i, length;\n\n //down while you can, then up and next sibling or up and next sibling until back at root\n while ((current = next)) {\n event.currentScope = current;\n listeners = current.$$listeners[name] || [];\n for (i = 0, length = listeners.length; i < length; i++) {\n // if listeners were deregistered, defragment the array\n if (!listeners[i]) {\n listeners.splice(i, 1);\n i--;\n length--;\n continue;\n }\n\n try {\n listeners[i].apply(null, listenerArgs);\n } catch (e) {\n $exceptionHandler(e);\n }\n }\n\n // Insanity Warning: scope depth-first traversal\n // yes, this code is a bit crazy, but it works and we have tests to prove it!\n // this piece should be kept in sync with the traversal in $digest\n // (though it differs due to having the extra check for $$listenerCount)\n if (!(next = ((current.$$listenerCount[name] && current.$$childHead) ||\n (current !== target && current.$$nextSibling)))) {\n while (current !== target && !(next = current.$$nextSibling)) {\n current = current.$parent;\n }\n }\n }\n\n event.currentScope = null;\n return event;\n }\n };\n\n var $rootScope = new Scope();\n\n //The internal queues. Expose them on the $rootScope for debugging/testing purposes.\n var asyncQueue = $rootScope.$$asyncQueue = [];\n var postDigestQueue = $rootScope.$$postDigestQueue = [];\n var applyAsyncQueue = $rootScope.$$applyAsyncQueue = [];\n\n var postDigestQueuePosition = 0;\n\n return $rootScope;\n\n\n function beginPhase(phase) {\n if ($rootScope.$$phase) {\n throw $rootScopeMinErr('inprog', '{0} already in progress', $rootScope.$$phase);\n }\n\n $rootScope.$$phase = phase;\n }\n\n function clearPhase() {\n $rootScope.$$phase = null;\n }\n\n function incrementWatchersCount(current, count) {\n do {\n current.$$watchersCount += count;\n } while ((current = current.$parent));\n }\n\n function decrementListenerCount(current, count, name) {\n do {\n current.$$listenerCount[name] -= count;\n\n if (current.$$listenerCount[name] === 0) {\n delete current.$$listenerCount[name];\n }\n } while ((current = current.$parent));\n }\n\n /**\n * function used as an initial value for watchers.\n * because it's unique we can easily tell it apart from other values\n */\n function initWatchVal() {}\n\n function flushApplyAsync() {\n while (applyAsyncQueue.length) {\n try {\n applyAsyncQueue.shift()();\n } catch (e) {\n $exceptionHandler(e);\n }\n }\n applyAsyncId = null;\n }\n\n function scheduleApplyAsync() {\n if (applyAsyncId === null) {\n applyAsyncId = $browser.defer(function() {\n $rootScope.$apply(flushApplyAsync);\n });\n }\n }\n }];\n}\n\n/**\n * @ngdoc service\n * @name $rootElement\n *\n * @description\n * The root element of Angular application. This is either the element where {@link\n * ng.directive:ngApp ngApp} was declared or the element passed into\n * {@link angular.bootstrap}. The element represents the root element of application. It is also the\n * location where the application's {@link auto.$injector $injector} service gets\n * published, and can be retrieved using `$rootElement.injector()`.\n */\n\n\n// the implementation is in angular.bootstrap\n\n/**\n * @this\n * @description\n * Private service to sanitize uris for links and images. Used by $compile and $sanitize.\n */\nfunction $$SanitizeUriProvider() {\n var aHrefSanitizationWhitelist = /^\\s*(https?|ftp|mailto|tel|file):/,\n imgSrcSanitizationWhitelist = /^\\s*((https?|ftp|file|blob):|data:image\\/)/;\n\n /**\n * @description\n * Retrieves or overrides the default regular expression that is used for whitelisting of safe\n * urls during a[href] sanitization.\n *\n * The sanitization is a security measure aimed at prevent XSS attacks via html links.\n *\n * Any url about to be assigned to a[href] via data-binding is first normalized and turned into\n * an absolute url. Afterwards, the url is matched against the `aHrefSanitizationWhitelist`\n * regular expression. If a match is found, the original url is written into the dom. Otherwise,\n * the absolute url is prefixed with `'unsafe:'` string and only then is it written into the DOM.\n *\n * @param {RegExp=} regexp New regexp to whitelist urls with.\n * @returns {RegExp|ng.$compileProvider} Current RegExp if called without value or self for\n * chaining otherwise.\n */\n this.aHrefSanitizationWhitelist = function(regexp) {\n if (isDefined(regexp)) {\n aHrefSanitizationWhitelist = regexp;\n return this;\n }\n return aHrefSanitizationWhitelist;\n };\n\n\n /**\n * @description\n * Retrieves or overrides the default regular expression that is used for whitelisting of safe\n * urls during img[src] sanitization.\n *\n * The sanitization is a security measure aimed at prevent XSS attacks via html links.\n *\n * Any url about to be assigned to img[src] via data-binding is first normalized and turned into\n * an absolute url. Afterwards, the url is matched against the `imgSrcSanitizationWhitelist`\n * regular expression. If a match is found, the original url is written into the dom. Otherwise,\n * the absolute url is prefixed with `'unsafe:'` string and only then is it written into the DOM.\n *\n * @param {RegExp=} regexp New regexp to whitelist urls with.\n * @returns {RegExp|ng.$compileProvider} Current RegExp if called without value or self for\n * chaining otherwise.\n */\n this.imgSrcSanitizationWhitelist = function(regexp) {\n if (isDefined(regexp)) {\n imgSrcSanitizationWhitelist = regexp;\n return this;\n }\n return imgSrcSanitizationWhitelist;\n };\n\n this.$get = function() {\n return function sanitizeUri(uri, isImage) {\n var regex = isImage ? imgSrcSanitizationWhitelist : aHrefSanitizationWhitelist;\n var normalizedVal;\n normalizedVal = urlResolve(uri).href;\n if (normalizedVal !== '' && !normalizedVal.match(regex)) {\n return 'unsafe:' + normalizedVal;\n }\n return uri;\n };\n };\n}\n\n/* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *\n * Any commits to this file should be reviewed with security in mind. *\n * Changes to this file can potentially create security vulnerabilities. *\n * An approval from 2 Core members with history of modifying *\n * this file is required. *\n * *\n * Does the change somehow allow for arbitrary javascript to be executed? *\n * Or allows for someone to change the prototype of built-in objects? *\n * Or gives undesired access to variables likes document or window? *\n * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */\n\n/* exported $SceProvider, $SceDelegateProvider */\n\nvar $sceMinErr = minErr('$sce');\n\nvar SCE_CONTEXTS = {\n HTML: 'html',\n CSS: 'css',\n URL: 'url',\n // RESOURCE_URL is a subtype of URL used in contexts where a privileged resource is sourced from a\n // url. (e.g. ng-include, script src, templateUrl)\n RESOURCE_URL: 'resourceUrl',\n JS: 'js'\n};\n\n// Helper functions follow.\n\nvar UNDERSCORE_LOWERCASE_REGEXP = /_([a-z])/g;\n\nfunction snakeToCamel(name) {\n return name\n .replace(UNDERSCORE_LOWERCASE_REGEXP, fnCamelCaseReplace);\n}\n\nfunction adjustMatcher(matcher) {\n if (matcher === 'self') {\n return matcher;\n } else if (isString(matcher)) {\n // Strings match exactly except for 2 wildcards - '*' and '**'.\n // '*' matches any character except those from the set ':/.?&'.\n // '**' matches any character (like .* in a RegExp).\n // More than 2 *'s raises an error as it's ill defined.\n if (matcher.indexOf('***') > -1) {\n throw $sceMinErr('iwcard',\n 'Illegal sequence *** in string matcher. String: {0}', matcher);\n }\n matcher = escapeForRegexp(matcher).\n replace(/\\\\\\*\\\\\\*/g, '.*').\n replace(/\\\\\\*/g, '[^:/.?&;]*');\n return new RegExp('^' + matcher + '$');\n } else if (isRegExp(matcher)) {\n // The only other type of matcher allowed is a Regexp.\n // Match entire URL / disallow partial matches.\n // Flags are reset (i.e. no global, ignoreCase or multiline)\n return new RegExp('^' + matcher.source + '$');\n } else {\n throw $sceMinErr('imatcher',\n 'Matchers may only be \"self\", string patterns or RegExp objects');\n }\n}\n\n\nfunction adjustMatchers(matchers) {\n var adjustedMatchers = [];\n if (isDefined(matchers)) {\n forEach(matchers, function(matcher) {\n adjustedMatchers.push(adjustMatcher(matcher));\n });\n }\n return adjustedMatchers;\n}\n\n\n/**\n * @ngdoc service\n * @name $sceDelegate\n * @kind function\n *\n * @description\n *\n * `$sceDelegate` is a service that is used by the `$sce` service to provide {@link ng.$sce Strict\n * Contextual Escaping (SCE)} services to AngularJS.\n *\n * Typically, you would configure or override the {@link ng.$sceDelegate $sceDelegate} instead of\n * the `$sce` service to customize the way Strict Contextual Escaping works in AngularJS. This is\n * because, while the `$sce` provides numerous shorthand methods, etc., you really only need to\n * override 3 core functions (`trustAs`, `getTrusted` and `valueOf`) to replace the way things\n * work because `$sce` delegates to `$sceDelegate` for these operations.\n *\n * Refer {@link ng.$sceDelegateProvider $sceDelegateProvider} to configure this service.\n *\n * The default instance of `$sceDelegate` should work out of the box with little pain. While you\n * can override it completely to change the behavior of `$sce`, the common case would\n * involve configuring the {@link ng.$sceDelegateProvider $sceDelegateProvider} instead by setting\n * your own whitelists and blacklists for trusting URLs used for loading AngularJS resources such as\n * templates. Refer {@link ng.$sceDelegateProvider#resourceUrlWhitelist\n * $sceDelegateProvider.resourceUrlWhitelist} and {@link\n * ng.$sceDelegateProvider#resourceUrlBlacklist $sceDelegateProvider.resourceUrlBlacklist}\n */\n\n/**\n * @ngdoc provider\n * @name $sceDelegateProvider\n * @this\n *\n * @description\n *\n * The `$sceDelegateProvider` provider allows developers to configure the {@link ng.$sceDelegate\n * $sceDelegate} service. This allows one to get/set the whitelists and blacklists used to ensure\n * that the URLs used for sourcing Angular templates are safe. Refer {@link\n * ng.$sceDelegateProvider#resourceUrlWhitelist $sceDelegateProvider.resourceUrlWhitelist} and\n * {@link ng.$sceDelegateProvider#resourceUrlBlacklist $sceDelegateProvider.resourceUrlBlacklist}\n *\n * For the general details about this service in Angular, read the main page for {@link ng.$sce\n * Strict Contextual Escaping (SCE)}.\n *\n * **Example**: Consider the following case.
\n *\n * - your app is hosted at url `http://myapp.example.com/`\n * - but some of your templates are hosted on other domains you control such as\n * `http://srv01.assets.example.com/`, `http://srv02.assets.example.com/`, etc.\n * - and you have an open redirect at `http://myapp.example.com/clickThru?...`.\n *\n * Here is what a secure configuration for this scenario might look like:\n *\n * ```\n * angular.module('myApp', []).config(function($sceDelegateProvider) {\n * $sceDelegateProvider.resourceUrlWhitelist([\n * // Allow same origin resource loads.\n * 'self',\n * // Allow loading from our assets domain. Notice the difference between * and **.\n * 'http://srv*.assets.example.com/**'\n * ]);\n *\n * // The blacklist overrides the whitelist so the open redirect here is blocked.\n * $sceDelegateProvider.resourceUrlBlacklist([\n * 'http://myapp.example.com/clickThru**'\n * ]);\n * });\n * ```\n */\n\nfunction $SceDelegateProvider() {\n this.SCE_CONTEXTS = SCE_CONTEXTS;\n\n // Resource URLs can also be trusted by policy.\n var resourceUrlWhitelist = ['self'],\n resourceUrlBlacklist = [];\n\n /**\n * @ngdoc method\n * @name $sceDelegateProvider#resourceUrlWhitelist\n * @kind function\n *\n * @param {Array=} whitelist When provided, replaces the resourceUrlWhitelist with the value\n * provided. This must be an array or null. A snapshot of this array is used so further\n * changes to the array are ignored.\n *\n * Follow {@link ng.$sce#resourceUrlPatternItem this link} for a description of the items\n * allowed in this array.\n *\n *
\n * **Note:** an empty whitelist array will block all URLs!\n *
\n *\n * @return {Array} the currently set whitelist array.\n *\n * The **default value** when no whitelist has been explicitly set is `['self']` allowing only\n * same origin resource requests.\n *\n * @description\n * Sets/Gets the whitelist of trusted resource URLs.\n */\n this.resourceUrlWhitelist = function(value) {\n if (arguments.length) {\n resourceUrlWhitelist = adjustMatchers(value);\n }\n return resourceUrlWhitelist;\n };\n\n /**\n * @ngdoc method\n * @name $sceDelegateProvider#resourceUrlBlacklist\n * @kind function\n *\n * @param {Array=} blacklist When provided, replaces the resourceUrlBlacklist with the value\n * provided. This must be an array or null. A snapshot of this array is used so further\n * changes to the array are ignored.\n *\n * Follow {@link ng.$sce#resourceUrlPatternItem this link} for a description of the items\n * allowed in this array.\n *\n * The typical usage for the blacklist is to **block\n * [open redirects](http://cwe.mitre.org/data/definitions/601.html)** served by your domain as\n * these would otherwise be trusted but actually return content from the redirected domain.\n *\n * Finally, **the blacklist overrides the whitelist** and has the final say.\n *\n * @return {Array} the currently set blacklist array.\n *\n * The **default value** when no whitelist has been explicitly set is the empty array (i.e. there\n * is no blacklist.)\n *\n * @description\n * Sets/Gets the blacklist of trusted resource URLs.\n */\n\n this.resourceUrlBlacklist = function(value) {\n if (arguments.length) {\n resourceUrlBlacklist = adjustMatchers(value);\n }\n return resourceUrlBlacklist;\n };\n\n this.$get = ['$injector', function($injector) {\n\n var htmlSanitizer = function htmlSanitizer(html) {\n throw $sceMinErr('unsafe', 'Attempting to use an unsafe value in a safe context.');\n };\n\n if ($injector.has('$sanitize')) {\n htmlSanitizer = $injector.get('$sanitize');\n }\n\n\n function matchUrl(matcher, parsedUrl) {\n if (matcher === 'self') {\n return urlIsSameOrigin(parsedUrl);\n } else {\n // definitely a regex. See adjustMatchers()\n return !!matcher.exec(parsedUrl.href);\n }\n }\n\n function isResourceUrlAllowedByPolicy(url) {\n var parsedUrl = urlResolve(url.toString());\n var i, n, allowed = false;\n // Ensure that at least one item from the whitelist allows this url.\n for (i = 0, n = resourceUrlWhitelist.length; i < n; i++) {\n if (matchUrl(resourceUrlWhitelist[i], parsedUrl)) {\n allowed = true;\n break;\n }\n }\n if (allowed) {\n // Ensure that no item from the blacklist blocked this url.\n for (i = 0, n = resourceUrlBlacklist.length; i < n; i++) {\n if (matchUrl(resourceUrlBlacklist[i], parsedUrl)) {\n allowed = false;\n break;\n }\n }\n }\n return allowed;\n }\n\n function generateHolderType(Base) {\n var holderType = function TrustedValueHolderType(trustedValue) {\n this.$$unwrapTrustedValue = function() {\n return trustedValue;\n };\n };\n if (Base) {\n holderType.prototype = new Base();\n }\n holderType.prototype.valueOf = function sceValueOf() {\n return this.$$unwrapTrustedValue();\n };\n holderType.prototype.toString = function sceToString() {\n return this.$$unwrapTrustedValue().toString();\n };\n return holderType;\n }\n\n var trustedValueHolderBase = generateHolderType(),\n byType = {};\n\n byType[SCE_CONTEXTS.HTML] = generateHolderType(trustedValueHolderBase);\n byType[SCE_CONTEXTS.CSS] = generateHolderType(trustedValueHolderBase);\n byType[SCE_CONTEXTS.URL] = generateHolderType(trustedValueHolderBase);\n byType[SCE_CONTEXTS.JS] = generateHolderType(trustedValueHolderBase);\n byType[SCE_CONTEXTS.RESOURCE_URL] = generateHolderType(byType[SCE_CONTEXTS.URL]);\n\n /**\n * @ngdoc method\n * @name $sceDelegate#trustAs\n *\n * @description\n * Returns an object that is trusted by angular for use in specified strict\n * contextual escaping contexts (such as ng-bind-html, ng-include, any src\n * attribute interpolation, any dom event binding attribute interpolation\n * such as for onclick, etc.) that uses the provided value.\n * See {@link ng.$sce $sce} for enabling strict contextual escaping.\n *\n * @param {string} type The kind of context in which this value is safe for use. e.g. url,\n * resourceUrl, html, js and css.\n * @param {*} value The value that that should be considered trusted/safe.\n * @returns {*} A value that can be used to stand in for the provided `value` in places\n * where Angular expects a $sce.trustAs() return value.\n */\n function trustAs(type, trustedValue) {\n var Constructor = (byType.hasOwnProperty(type) ? byType[type] : null);\n if (!Constructor) {\n throw $sceMinErr('icontext',\n 'Attempted to trust a value in invalid context. Context: {0}; Value: {1}',\n type, trustedValue);\n }\n if (trustedValue === null || isUndefined(trustedValue) || trustedValue === '') {\n return trustedValue;\n }\n // All the current contexts in SCE_CONTEXTS happen to be strings. In order to avoid trusting\n // mutable objects, we ensure here that the value passed in is actually a string.\n if (typeof trustedValue !== 'string') {\n throw $sceMinErr('itype',\n 'Attempted to trust a non-string value in a content requiring a string: Context: {0}',\n type);\n }\n return new Constructor(trustedValue);\n }\n\n /**\n * @ngdoc method\n * @name $sceDelegate#valueOf\n *\n * @description\n * If the passed parameter had been returned by a prior call to {@link ng.$sceDelegate#trustAs\n * `$sceDelegate.trustAs`}, returns the value that had been passed to {@link\n * ng.$sceDelegate#trustAs `$sceDelegate.trustAs`}.\n *\n * If the passed parameter is not a value that had been returned by {@link\n * ng.$sceDelegate#trustAs `$sceDelegate.trustAs`}, returns it as-is.\n *\n * @param {*} value The result of a prior {@link ng.$sceDelegate#trustAs `$sceDelegate.trustAs`}\n * call or anything else.\n * @returns {*} The `value` that was originally provided to {@link ng.$sceDelegate#trustAs\n * `$sceDelegate.trustAs`} if `value` is the result of such a call. Otherwise, returns\n * `value` unchanged.\n */\n function valueOf(maybeTrusted) {\n if (maybeTrusted instanceof trustedValueHolderBase) {\n return maybeTrusted.$$unwrapTrustedValue();\n } else {\n return maybeTrusted;\n }\n }\n\n /**\n * @ngdoc method\n * @name $sceDelegate#getTrusted\n *\n * @description\n * Takes the result of a {@link ng.$sceDelegate#trustAs `$sceDelegate.trustAs`} call and\n * returns the originally supplied value if the queried context type is a supertype of the\n * created type. If this condition isn't satisfied, throws an exception.\n *\n *
\n * Disabling auto-escaping is extremely dangerous, it usually creates a Cross Site Scripting\n * (XSS) vulnerability in your application.\n *
\n *\n * @param {string} type The kind of context in which this value is to be used.\n * @param {*} maybeTrusted The result of a prior {@link ng.$sceDelegate#trustAs\n * `$sceDelegate.trustAs`} call.\n * @returns {*} The value the was originally provided to {@link ng.$sceDelegate#trustAs\n * `$sceDelegate.trustAs`} if valid in this context. Otherwise, throws an exception.\n */\n function getTrusted(type, maybeTrusted) {\n if (maybeTrusted === null || isUndefined(maybeTrusted) || maybeTrusted === '') {\n return maybeTrusted;\n }\n var constructor = (byType.hasOwnProperty(type) ? byType[type] : null);\n if (constructor && maybeTrusted instanceof constructor) {\n return maybeTrusted.$$unwrapTrustedValue();\n }\n // If we get here, then we may only take one of two actions.\n // 1. sanitize the value for the requested type, or\n // 2. throw an exception.\n if (type === SCE_CONTEXTS.RESOURCE_URL) {\n if (isResourceUrlAllowedByPolicy(maybeTrusted)) {\n return maybeTrusted;\n } else {\n throw $sceMinErr('insecurl',\n 'Blocked loading resource from url not allowed by $sceDelegate policy. URL: {0}',\n maybeTrusted.toString());\n }\n } else if (type === SCE_CONTEXTS.HTML) {\n return htmlSanitizer(maybeTrusted);\n }\n throw $sceMinErr('unsafe', 'Attempting to use an unsafe value in a safe context.');\n }\n\n return { trustAs: trustAs,\n getTrusted: getTrusted,\n valueOf: valueOf };\n }];\n}\n\n\n/**\n * @ngdoc provider\n * @name $sceProvider\n * @this\n *\n * @description\n *\n * The $sceProvider provider allows developers to configure the {@link ng.$sce $sce} service.\n * - enable/disable Strict Contextual Escaping (SCE) in a module\n * - override the default implementation with a custom delegate\n *\n * Read more about {@link ng.$sce Strict Contextual Escaping (SCE)}.\n */\n\n/**\n * @ngdoc service\n * @name $sce\n * @kind function\n *\n * @description\n *\n * `$sce` is a service that provides Strict Contextual Escaping services to AngularJS.\n *\n * # Strict Contextual Escaping\n *\n * Strict Contextual Escaping (SCE) is a mode in which AngularJS requires bindings in certain\n * contexts to result in a value that is marked as safe to use for that context. One example of\n * such a context is binding arbitrary html controlled by the user via `ng-bind-html`. We refer\n * to these contexts as privileged or SCE contexts.\n *\n * As of version 1.2, Angular ships with SCE enabled by default.\n *\n * Note: When enabled (the default), IE<11 in quirks mode is not supported. In this mode, IE<11 allow\n * one to execute arbitrary javascript by the use of the expression() syntax. Refer\n * to learn more about them.\n * You can ensure your document is in standards mode and not quirks mode by adding ``\n * to the top of your HTML document.\n *\n * SCE assists in writing code in a way that (a) is secure by default and (b) makes auditing for\n * security vulnerabilities such as XSS, clickjacking, etc. a lot easier.\n *\n * Here's an example of a binding in a privileged context:\n *\n * ```\n * \n *
\n * ```\n *\n * Notice that `ng-bind-html` is bound to `userHtml` controlled by the user. With SCE\n * disabled, this application allows the user to render arbitrary HTML into the DIV.\n * In a more realistic example, one may be rendering user comments, blog articles, etc. via\n * bindings. (HTML is just one example of a context where rendering user controlled input creates\n * security vulnerabilities.)\n *\n * For the case of HTML, you might use a library, either on the client side, or on the server side,\n * to sanitize unsafe HTML before binding to the value and rendering it in the document.\n *\n * How would you ensure that every place that used these types of bindings was bound to a value that\n * was sanitized by your library (or returned as safe for rendering by your server?) How can you\n * ensure that you didn't accidentally delete the line that sanitized the value, or renamed some\n * properties/fields and forgot to update the binding to the sanitized value?\n *\n * To be secure by default, you want to ensure that any such bindings are disallowed unless you can\n * determine that something explicitly says it's safe to use a value for binding in that\n * context. You can then audit your code (a simple grep would do) to ensure that this is only done\n * for those values that you can easily tell are safe - because they were received from your server,\n * sanitized by your library, etc. You can organize your codebase to help with this - perhaps\n * allowing only the files in a specific directory to do this. Ensuring that the internal API\n * exposed by that code doesn't markup arbitrary values as safe then becomes a more manageable task.\n *\n * In the case of AngularJS' SCE service, one uses {@link ng.$sce#trustAs $sce.trustAs}\n * (and shorthand methods such as {@link ng.$sce#trustAsHtml $sce.trustAsHtml}, etc.) to\n * obtain values that will be accepted by SCE / privileged contexts.\n *\n *\n * ## How does it work?\n *\n * In privileged contexts, directives and code will bind to the result of {@link ng.$sce#getTrusted\n * $sce.getTrusted(context, value)} rather than to the value directly. Directives use {@link\n * ng.$sce#parseAs $sce.parseAs} rather than `$parse` to watch attribute bindings, which performs the\n * {@link ng.$sce#getTrusted $sce.getTrusted} behind the scenes on non-constant literals.\n *\n * As an example, {@link ng.directive:ngBindHtml ngBindHtml} uses {@link\n * ng.$sce#parseAsHtml $sce.parseAsHtml(binding expression)}. Here's the actual code (slightly\n * simplified):\n *\n * ```\n * var ngBindHtmlDirective = ['$sce', function($sce) {\n * return function(scope, element, attr) {\n * scope.$watch($sce.parseAsHtml(attr.ngBindHtml), function(value) {\n * element.html(value || '');\n * });\n * };\n * }];\n * ```\n *\n * ## Impact on loading templates\n *\n * This applies both to the {@link ng.directive:ngInclude `ng-include`} directive as well as\n * `templateUrl`'s specified by {@link guide/directive directives}.\n *\n * By default, Angular only loads templates from the same domain and protocol as the application\n * document. This is done by calling {@link ng.$sce#getTrustedResourceUrl\n * $sce.getTrustedResourceUrl} on the template URL. To load templates from other domains and/or\n * protocols, you may either {@link ng.$sceDelegateProvider#resourceUrlWhitelist whitelist\n * them} or {@link ng.$sce#trustAsResourceUrl wrap it} into a trusted value.\n *\n * *Please note*:\n * The browser's\n * [Same Origin Policy](https://code.google.com/p/browsersec/wiki/Part2#Same-origin_policy_for_XMLHttpRequest)\n * and [Cross-Origin Resource Sharing (CORS)](http://www.w3.org/TR/cors/)\n * policy apply in addition to this and may further restrict whether the template is successfully\n * loaded. This means that without the right CORS policy, loading templates from a different domain\n * won't work on all browsers. Also, loading templates from `file://` URL does not work on some\n * browsers.\n *\n * ## This feels like too much overhead\n *\n * It's important to remember that SCE only applies to interpolation expressions.\n *\n * If your expressions are constant literals, they're automatically trusted and you don't need to\n * call `$sce.trustAs` on them (remember to include the `ngSanitize` module) (e.g.\n * `
implicitly trusted'\">
`) just works.\n *\n * Additionally, `a[href]` and `img[src]` automatically sanitize their URLs and do not pass them\n * through {@link ng.$sce#getTrusted $sce.getTrusted}. SCE doesn't play a role here.\n *\n * The included {@link ng.$sceDelegate $sceDelegate} comes with sane defaults to allow you to load\n * templates in `ng-include` from your application's domain without having to even know about SCE.\n * It blocks loading templates from other domains or loading templates over http from an https\n * served document. You can change these by setting your own custom {@link\n * ng.$sceDelegateProvider#resourceUrlWhitelist whitelists} and {@link\n * ng.$sceDelegateProvider#resourceUrlBlacklist blacklists} for matching such URLs.\n *\n * This significantly reduces the overhead. It is far easier to pay the small overhead and have an\n * application that's secure and can be audited to verify that with much more ease than bolting\n * security onto an application later.\n *\n * \n * ## What trusted context types are supported?\n *\n * | Context | Notes |\n * |---------------------|----------------|\n * | `$sce.HTML` | For HTML that's safe to source into the application. The {@link ng.directive:ngBindHtml ngBindHtml} directive uses this context for bindings. If an unsafe value is encountered and the {@link ngSanitize $sanitize} module is present this will sanitize the value instead of throwing an error. |\n * | `$sce.CSS` | For CSS that's safe to source into the application. Currently unused. Feel free to use it in your own directives. |\n * | `$sce.URL` | For URLs that are safe to follow as links. Currently unused (`
Note that `$sce.RESOURCE_URL` makes a stronger statement about the URL than `$sce.URL` does and therefore contexts requiring values trusted for `$sce.RESOURCE_URL` can be used anywhere that values trusted for `$sce.URL` are required. |\n * | `$sce.JS` | For JavaScript that is safe to execute in your application's context. Currently unused. Feel free to use it in your own directives. |\n *\n * ## Format of items in {@link ng.$sceDelegateProvider#resourceUrlWhitelist resourceUrlWhitelist}/{@link ng.$sceDelegateProvider#resourceUrlBlacklist Blacklist}
\n *\n * Each element in these arrays must be one of the following:\n *\n * - **'self'**\n * - The special **string**, `'self'`, can be used to match against all URLs of the **same\n * domain** as the application document using the **same protocol**.\n * - **String** (except the special value `'self'`)\n * - The string is matched against the full *normalized / absolute URL* of the resource\n * being tested (substring matches are not good enough.)\n * - There are exactly **two wildcard sequences** - `*` and `**`. All other characters\n * match themselves.\n * - `*`: matches zero or more occurrences of any character other than one of the following 6\n * characters: '`:`', '`/`', '`.`', '`?`', '`&`' and '`;`'. It's a useful wildcard for use\n * in a whitelist.\n * - `**`: matches zero or more occurrences of *any* character. As such, it's not\n * appropriate for use in a scheme, domain, etc. as it would match too much. (e.g.\n * http://**.example.com/ would match http://evil.com/?ignore=.example.com/ and that might\n * not have been the intention.) Its usage at the very end of the path is ok. (e.g.\n * http://foo.example.com/templates/**).\n * - **RegExp** (*see caveat below*)\n * - *Caveat*: While regular expressions are powerful and offer great flexibility, their syntax\n * (and all the inevitable escaping) makes them *harder to maintain*. It's easy to\n * accidentally introduce a bug when one updates a complex expression (imho, all regexes should\n * have good test coverage). For instance, the use of `.` in the regex is correct only in a\n * small number of cases. A `.` character in the regex used when matching the scheme or a\n * subdomain could be matched against a `:` or literal `.` that was likely not intended. It\n * is highly recommended to use the string patterns and only fall back to regular expressions\n * as a last resort.\n * - The regular expression must be an instance of RegExp (i.e. not a string.) It is\n * matched against the **entire** *normalized / absolute URL* of the resource being tested\n * (even when the RegExp did not have the `^` and `$` codes.) In addition, any flags\n * present on the RegExp (such as multiline, global, ignoreCase) are ignored.\n * - If you are generating your JavaScript from some other templating engine (not\n * recommended, e.g. in issue [#4006](https://github.com/angular/angular.js/issues/4006)),\n * remember to escape your regular expression (and be aware that you might need more than\n * one level of escaping depending on your templating engine and the way you interpolated\n * the value.) Do make use of your platform's escaping mechanism as it might be good\n * enough before coding your own. E.g. Ruby has\n * [Regexp.escape(str)](http://www.ruby-doc.org/core-2.0.0/Regexp.html#method-c-escape)\n * and Python has [re.escape](http://docs.python.org/library/re.html#re.escape).\n * Javascript lacks a similar built in function for escaping. Take a look at Google\n * Closure library's [goog.string.regExpEscape(s)](\n * http://docs.closure-library.googlecode.com/git/closure_goog_string_string.js.source.html#line962).\n *\n * Refer {@link ng.$sceDelegateProvider $sceDelegateProvider} for an example.\n *\n * ## Show me an example using SCE.\n *\n * \n * \n *
\n *

\n * User comments
\n * By default, HTML that isn't explicitly trusted (e.g. Alice's comment) is sanitized when\n * $sanitize is available. If $sanitize isn't available, this results in an error instead of an\n * exploit.\n *
\n *
\n * {{userComment.name}}:\n * \n *
\n *
\n *
\n *
\n *
\n *\n * \n * angular.module('mySceApp', ['ngSanitize'])\n * .controller('AppController', ['$http', '$templateCache', '$sce',\n * function AppController($http, $templateCache, $sce) {\n * var self = this;\n * $http.get('test_data.json', {cache: $templateCache}).then(function(response) {\n * self.userComments = response.data;\n * });\n * self.explicitlyTrustedHtml = $sce.trustAsHtml(\n * 'Hover over this text.');\n * }]);\n * \n *\n * \n * [\n * { \"name\": \"Alice\",\n * \"htmlComment\":\n * \"Is anyone reading this?\"\n * },\n * { \"name\": \"Bob\",\n * \"htmlComment\": \"Yes! Am I the only other one?\"\n * }\n * ]\n * \n *\n * \n * describe('SCE doc demo', function() {\n * it('should sanitize untrusted values', function() {\n * expect(element.all(by.css('.htmlComment')).first().getAttribute('innerHTML'))\n * .toBe('Is anyone reading this?');\n * });\n *\n * it('should NOT sanitize explicitly trusted values', function() {\n * expect(element(by.id('explicitlyTrustedHtml')).getAttribute('innerHTML')).toBe(\n * 'Hover over this text.');\n * });\n * });\n * \n *
\n *\n *\n *\n * ## Can I disable SCE completely?\n *\n * Yes, you can. However, this is strongly discouraged. SCE gives you a lot of security benefits\n * for little coding overhead. It will be much harder to take an SCE disabled application and\n * either secure it on your own or enable SCE at a later stage. It might make sense to disable SCE\n * for cases where you have a lot of existing code that was written before SCE was introduced and\n * you're migrating them a module at a time.\n *\n * That said, here's how you can completely disable SCE:\n *\n * ```\n * angular.module('myAppWithSceDisabledmyApp', []).config(function($sceProvider) {\n * // Completely disable SCE. For demonstration purposes only!\n * // Do not use in new projects.\n * $sceProvider.enabled(false);\n * });\n * ```\n *\n */\n\nfunction $SceProvider() {\n var enabled = true;\n\n /**\n * @ngdoc method\n * @name $sceProvider#enabled\n * @kind function\n *\n * @param {boolean=} value If provided, then enables/disables SCE.\n * @return {boolean} true if SCE is enabled, false otherwise.\n *\n * @description\n * Enables/disables SCE and returns the current value.\n */\n this.enabled = function(value) {\n if (arguments.length) {\n enabled = !!value;\n }\n return enabled;\n };\n\n\n /* Design notes on the default implementation for SCE.\n *\n * The API contract for the SCE delegate\n * -------------------------------------\n * The SCE delegate object must provide the following 3 methods:\n *\n * - trustAs(contextEnum, value)\n * This method is used to tell the SCE service that the provided value is OK to use in the\n * contexts specified by contextEnum. It must return an object that will be accepted by\n * getTrusted() for a compatible contextEnum and return this value.\n *\n * - valueOf(value)\n * For values that were not produced by trustAs(), return them as is. For values that were\n * produced by trustAs(), return the corresponding input value to trustAs. Basically, if\n * trustAs is wrapping the given values into some type, this operation unwraps it when given\n * such a value.\n *\n * - getTrusted(contextEnum, value)\n * This function should return the a value that is safe to use in the context specified by\n * contextEnum or throw and exception otherwise.\n *\n * NOTE: This contract deliberately does NOT state that values returned by trustAs() must be\n * opaque or wrapped in some holder object. That happens to be an implementation detail. For\n * instance, an implementation could maintain a registry of all trusted objects by context. In\n * such a case, trustAs() would return the same object that was passed in. getTrusted() would\n * return the same object passed in if it was found in the registry under a compatible context or\n * throw an exception otherwise. An implementation might only wrap values some of the time based\n * on some criteria. getTrusted() might return a value and not throw an exception for special\n * constants or objects even if not wrapped. All such implementations fulfill this contract.\n *\n *\n * A note on the inheritance model for SCE contexts\n * ------------------------------------------------\n * I've used inheritance and made RESOURCE_URL wrapped types a subtype of URL wrapped types. This\n * is purely an implementation details.\n *\n * The contract is simply this:\n *\n * getTrusted($sce.RESOURCE_URL, value) succeeding implies that getTrusted($sce.URL, value)\n * will also succeed.\n *\n * Inheritance happens to capture this in a natural way. In some future, we\n * may not use inheritance anymore. That is OK because no code outside of\n * sce.js and sceSpecs.js would need to be aware of this detail.\n */\n\n this.$get = ['$parse', '$sceDelegate', function(\n $parse, $sceDelegate) {\n // Support: IE 9-11 only\n // Prereq: Ensure that we're not running in IE<11 quirks mode. In that mode, IE < 11 allow\n // the \"expression(javascript expression)\" syntax which is insecure.\n if (enabled && msie < 8) {\n throw $sceMinErr('iequirks',\n 'Strict Contextual Escaping does not support Internet Explorer version < 11 in quirks ' +\n 'mode. You can fix this by adding the text to the top of your HTML ' +\n 'document. See http://docs.angularjs.org/api/ng.$sce for more information.');\n }\n\n var sce = shallowCopy(SCE_CONTEXTS);\n\n /**\n * @ngdoc method\n * @name $sce#isEnabled\n * @kind function\n *\n * @return {Boolean} true if SCE is enabled, false otherwise. If you want to set the value, you\n * have to do it at module config time on {@link ng.$sceProvider $sceProvider}.\n *\n * @description\n * Returns a boolean indicating if SCE is enabled.\n */\n sce.isEnabled = function() {\n return enabled;\n };\n sce.trustAs = $sceDelegate.trustAs;\n sce.getTrusted = $sceDelegate.getTrusted;\n sce.valueOf = $sceDelegate.valueOf;\n\n if (!enabled) {\n sce.trustAs = sce.getTrusted = function(type, value) { return value; };\n sce.valueOf = identity;\n }\n\n /**\n * @ngdoc method\n * @name $sce#parseAs\n *\n * @description\n * Converts Angular {@link guide/expression expression} into a function. This is like {@link\n * ng.$parse $parse} and is identical when the expression is a literal constant. Otherwise, it\n * wraps the expression in a call to {@link ng.$sce#getTrusted $sce.getTrusted(*type*,\n * *result*)}\n *\n * @param {string} type The kind of SCE context in which this result will be used.\n * @param {string} expression String expression to compile.\n * @returns {function(context, locals)} a function which represents the compiled expression:\n *\n * * `context` – `{object}` – an object against which any expressions embedded in the strings\n * are evaluated against (typically a scope object).\n * * `locals` – `{object=}` – local variables context object, useful for overriding values in\n * `context`.\n */\n sce.parseAs = function sceParseAs(type, expr) {\n var parsed = $parse(expr);\n if (parsed.literal && parsed.constant) {\n return parsed;\n } else {\n return $parse(expr, function(value) {\n return sce.getTrusted(type, value);\n });\n }\n };\n\n /**\n * @ngdoc method\n * @name $sce#trustAs\n *\n * @description\n * Delegates to {@link ng.$sceDelegate#trustAs `$sceDelegate.trustAs`}. As such,\n * returns an object that is trusted by angular for use in specified strict contextual\n * escaping contexts (such as ng-bind-html, ng-include, any src attribute\n * interpolation, any dom event binding attribute interpolation such as for onclick, etc.)\n * that uses the provided value. See * {@link ng.$sce $sce} for enabling strict contextual\n * escaping.\n *\n * @param {string} type The kind of context in which this value is safe for use. e.g. url,\n * resourceUrl, html, js and css.\n * @param {*} value The value that that should be considered trusted/safe.\n * @returns {*} A value that can be used to stand in for the provided `value` in places\n * where Angular expects a $sce.trustAs() return value.\n */\n\n /**\n * @ngdoc method\n * @name $sce#trustAsHtml\n *\n * @description\n * Shorthand method. `$sce.trustAsHtml(value)` →\n * {@link ng.$sceDelegate#trustAs `$sceDelegate.trustAs($sce.HTML, value)`}\n *\n * @param {*} value The value to trustAs.\n * @returns {*} An object that can be passed to {@link ng.$sce#getTrustedHtml\n * $sce.getTrustedHtml(value)} to obtain the original value. (privileged directives\n * only accept expressions that are either literal constants or are the\n * return value of {@link ng.$sce#trustAs $sce.trustAs}.)\n */\n\n /**\n * @ngdoc method\n * @name $sce#trustAsUrl\n *\n * @description\n * Shorthand method. `$sce.trustAsUrl(value)` →\n * {@link ng.$sceDelegate#trustAs `$sceDelegate.trustAs($sce.URL, value)`}\n *\n * @param {*} value The value to trustAs.\n * @returns {*} An object that can be passed to {@link ng.$sce#getTrustedUrl\n * $sce.getTrustedUrl(value)} to obtain the original value. (privileged directives\n * only accept expressions that are either literal constants or are the\n * return value of {@link ng.$sce#trustAs $sce.trustAs}.)\n */\n\n /**\n * @ngdoc method\n * @name $sce#trustAsResourceUrl\n *\n * @description\n * Shorthand method. `$sce.trustAsResourceUrl(value)` →\n * {@link ng.$sceDelegate#trustAs `$sceDelegate.trustAs($sce.RESOURCE_URL, value)`}\n *\n * @param {*} value The value to trustAs.\n * @returns {*} An object that can be passed to {@link ng.$sce#getTrustedResourceUrl\n * $sce.getTrustedResourceUrl(value)} to obtain the original value. (privileged directives\n * only accept expressions that are either literal constants or are the return\n * value of {@link ng.$sce#trustAs $sce.trustAs}.)\n */\n\n /**\n * @ngdoc method\n * @name $sce#trustAsJs\n *\n * @description\n * Shorthand method. `$sce.trustAsJs(value)` →\n * {@link ng.$sceDelegate#trustAs `$sceDelegate.trustAs($sce.JS, value)`}\n *\n * @param {*} value The value to trustAs.\n * @returns {*} An object that can be passed to {@link ng.$sce#getTrustedJs\n * $sce.getTrustedJs(value)} to obtain the original value. (privileged directives\n * only accept expressions that are either literal constants or are the\n * return value of {@link ng.$sce#trustAs $sce.trustAs}.)\n */\n\n /**\n * @ngdoc method\n * @name $sce#getTrusted\n *\n * @description\n * Delegates to {@link ng.$sceDelegate#getTrusted `$sceDelegate.getTrusted`}. As such,\n * takes the result of a {@link ng.$sce#trustAs `$sce.trustAs`}() call and returns the\n * originally supplied value if the queried context type is a supertype of the created type.\n * If this condition isn't satisfied, throws an exception.\n *\n * @param {string} type The kind of context in which this value is to be used.\n * @param {*} maybeTrusted The result of a prior {@link ng.$sce#trustAs `$sce.trustAs`}\n * call.\n * @returns {*} The value the was originally provided to\n * {@link ng.$sce#trustAs `$sce.trustAs`} if valid in this context.\n * Otherwise, throws an exception.\n */\n\n /**\n * @ngdoc method\n * @name $sce#getTrustedHtml\n *\n * @description\n * Shorthand method. `$sce.getTrustedHtml(value)` →\n * {@link ng.$sceDelegate#getTrusted `$sceDelegate.getTrusted($sce.HTML, value)`}\n *\n * @param {*} value The value to pass to `$sce.getTrusted`.\n * @returns {*} The return value of `$sce.getTrusted($sce.HTML, value)`\n */\n\n /**\n * @ngdoc method\n * @name $sce#getTrustedCss\n *\n * @description\n * Shorthand method. `$sce.getTrustedCss(value)` →\n * {@link ng.$sceDelegate#getTrusted `$sceDelegate.getTrusted($sce.CSS, value)`}\n *\n * @param {*} value The value to pass to `$sce.getTrusted`.\n * @returns {*} The return value of `$sce.getTrusted($sce.CSS, value)`\n */\n\n /**\n * @ngdoc method\n * @name $sce#getTrustedUrl\n *\n * @description\n * Shorthand method. `$sce.getTrustedUrl(value)` →\n * {@link ng.$sceDelegate#getTrusted `$sceDelegate.getTrusted($sce.URL, value)`}\n *\n * @param {*} value The value to pass to `$sce.getTrusted`.\n * @returns {*} The return value of `$sce.getTrusted($sce.URL, value)`\n */\n\n /**\n * @ngdoc method\n * @name $sce#getTrustedResourceUrl\n *\n * @description\n * Shorthand method. `$sce.getTrustedResourceUrl(value)` →\n * {@link ng.$sceDelegate#getTrusted `$sceDelegate.getTrusted($sce.RESOURCE_URL, value)`}\n *\n * @param {*} value The value to pass to `$sceDelegate.getTrusted`.\n * @returns {*} The return value of `$sce.getTrusted($sce.RESOURCE_URL, value)`\n */\n\n /**\n * @ngdoc method\n * @name $sce#getTrustedJs\n *\n * @description\n * Shorthand method. `$sce.getTrustedJs(value)` →\n * {@link ng.$sceDelegate#getTrusted `$sceDelegate.getTrusted($sce.JS, value)`}\n *\n * @param {*} value The value to pass to `$sce.getTrusted`.\n * @returns {*} The return value of `$sce.getTrusted($sce.JS, value)`\n */\n\n /**\n * @ngdoc method\n * @name $sce#parseAsHtml\n *\n * @description\n * Shorthand method. `$sce.parseAsHtml(expression string)` →\n * {@link ng.$sce#parseAs `$sce.parseAs($sce.HTML, value)`}\n *\n * @param {string} expression String expression to compile.\n * @returns {function(context, locals)} a function which represents the compiled expression:\n *\n * * `context` – `{object}` – an object against which any expressions embedded in the strings\n * are evaluated against (typically a scope object).\n * * `locals` – `{object=}` – local variables context object, useful for overriding values in\n * `context`.\n */\n\n /**\n * @ngdoc method\n * @name $sce#parseAsCss\n *\n * @description\n * Shorthand method. `$sce.parseAsCss(value)` →\n * {@link ng.$sce#parseAs `$sce.parseAs($sce.CSS, value)`}\n *\n * @param {string} expression String expression to compile.\n * @returns {function(context, locals)} a function which represents the compiled expression:\n *\n * * `context` – `{object}` – an object against which any expressions embedded in the strings\n * are evaluated against (typically a scope object).\n * * `locals` – `{object=}` – local variables context object, useful for overriding values in\n * `context`.\n */\n\n /**\n * @ngdoc method\n * @name $sce#parseAsUrl\n *\n * @description\n * Shorthand method. `$sce.parseAsUrl(value)` →\n * {@link ng.$sce#parseAs `$sce.parseAs($sce.URL, value)`}\n *\n * @param {string} expression String expression to compile.\n * @returns {function(context, locals)} a function which represents the compiled expression:\n *\n * * `context` – `{object}` – an object against which any expressions embedded in the strings\n * are evaluated against (typically a scope object).\n * * `locals` – `{object=}` – local variables context object, useful for overriding values in\n * `context`.\n */\n\n /**\n * @ngdoc method\n * @name $sce#parseAsResourceUrl\n *\n * @description\n * Shorthand method. `$sce.parseAsResourceUrl(value)` →\n * {@link ng.$sce#parseAs `$sce.parseAs($sce.RESOURCE_URL, value)`}\n *\n * @param {string} expression String expression to compile.\n * @returns {function(context, locals)} a function which represents the compiled expression:\n *\n * * `context` – `{object}` – an object against which any expressions embedded in the strings\n * are evaluated against (typically a scope object).\n * * `locals` – `{object=}` – local variables context object, useful for overriding values in\n * `context`.\n */\n\n /**\n * @ngdoc method\n * @name $sce#parseAsJs\n *\n * @description\n * Shorthand method. `$sce.parseAsJs(value)` →\n * {@link ng.$sce#parseAs `$sce.parseAs($sce.JS, value)`}\n *\n * @param {string} expression String expression to compile.\n * @returns {function(context, locals)} a function which represents the compiled expression:\n *\n * * `context` – `{object}` – an object against which any expressions embedded in the strings\n * are evaluated against (typically a scope object).\n * * `locals` – `{object=}` – local variables context object, useful for overriding values in\n * `context`.\n */\n\n // Shorthand delegations.\n var parse = sce.parseAs,\n getTrusted = sce.getTrusted,\n trustAs = sce.trustAs;\n\n forEach(SCE_CONTEXTS, function(enumValue, name) {\n var lName = lowercase(name);\n sce[snakeToCamel('parse_as_' + lName)] = function(expr) {\n return parse(enumValue, expr);\n };\n sce[snakeToCamel('get_trusted_' + lName)] = function(value) {\n return getTrusted(enumValue, value);\n };\n sce[snakeToCamel('trust_as_' + lName)] = function(value) {\n return trustAs(enumValue, value);\n };\n });\n\n return sce;\n }];\n}\n\n/* exported $SnifferProvider */\n\n/**\n * !!! This is an undocumented \"private\" service !!!\n *\n * @name $sniffer\n * @requires $window\n * @requires $document\n * @this\n *\n * @property {boolean} history Does the browser support html5 history api ?\n * @property {boolean} transitions Does the browser support CSS transition events ?\n * @property {boolean} animations Does the browser support CSS animation events ?\n *\n * @description\n * This is very simple implementation of testing browser's features.\n */\nfunction $SnifferProvider() {\n this.$get = ['$window', '$document', function($window, $document) {\n var eventSupport = {},\n // Chrome Packaged Apps are not allowed to access `history.pushState`.\n // If not sandboxed, they can be detected by the presence of `chrome.app.runtime`\n // (see https://developer.chrome.com/apps/api_index). If sandboxed, they can be detected by\n // the presence of an extension runtime ID and the absence of other Chrome runtime APIs\n // (see https://developer.chrome.com/apps/manifest/sandbox).\n isChromePackagedApp =\n $window.chrome &&\n ($window.chrome.app && $window.chrome.app.runtime ||\n !$window.chrome.app && $window.chrome.runtime && $window.chrome.runtime.id),\n hasHistoryPushState = !isChromePackagedApp && $window.history && $window.history.pushState,\n android =\n toInt((/android (\\d+)/.exec(lowercase(($window.navigator || {}).userAgent)) || [])[1]),\n boxee = /Boxee/i.test(($window.navigator || {}).userAgent),\n document = $document[0] || {},\n bodyStyle = document.body && document.body.style,\n transitions = false,\n animations = false;\n\n if (bodyStyle) {\n // Support: Android <5, Blackberry Browser 10, default Chrome in Android 4.4.x\n // Mentioned browsers need a -webkit- prefix for transitions & animations.\n transitions = !!('transition' in bodyStyle || 'webkitTransition' in bodyStyle);\n animations = !!('animation' in bodyStyle || 'webkitAnimation' in bodyStyle);\n }\n\n\n return {\n // Android has history.pushState, but it does not update location correctly\n // so let's not use the history API at all.\n // http://code.google.com/p/android/issues/detail?id=17471\n // https://github.com/angular/angular.js/issues/904\n\n // older webkit browser (533.9) on Boxee box has exactly the same problem as Android has\n // so let's not use the history API also\n // We are purposefully using `!(android < 4)` to cover the case when `android` is undefined\n history: !!(hasHistoryPushState && !(android < 4) && !boxee),\n hasEvent: function(event) {\n // Support: IE 9-11 only\n // IE9 implements 'input' event it's so fubared that we rather pretend that it doesn't have\n // it. In particular the event is not fired when backspace or delete key are pressed or\n // when cut operation is performed.\n // IE10+ implements 'input' event but it erroneously fires under various situations,\n // e.g. when placeholder changes, or a form is focused.\n if (event === 'input' && msie) return false;\n\n if (isUndefined(eventSupport[event])) {\n var divElm = document.createElement('div');\n eventSupport[event] = 'on' + event in divElm;\n }\n\n return eventSupport[event];\n },\n csp: csp(),\n transitions: transitions,\n animations: animations,\n android: android\n };\n }];\n}\n\nvar $templateRequestMinErr = minErr('$compile');\n\n/**\n * @ngdoc provider\n * @name $templateRequestProvider\n * @this\n *\n * @description\n * Used to configure the options passed to the {@link $http} service when making a template request.\n *\n * For example, it can be used for specifying the \"Accept\" header that is sent to the server, when\n * requesting a template.\n */\nfunction $TemplateRequestProvider() {\n\n var httpOptions;\n\n /**\n * @ngdoc method\n * @name $templateRequestProvider#httpOptions\n * @description\n * The options to be passed to the {@link $http} service when making the request.\n * You can use this to override options such as the \"Accept\" header for template requests.\n *\n * The {@link $templateRequest} will set the `cache` and the `transformResponse` properties of the\n * options if not overridden here.\n *\n * @param {string=} value new value for the {@link $http} options.\n * @returns {string|self} Returns the {@link $http} options when used as getter and self if used as setter.\n */\n this.httpOptions = function(val) {\n if (val) {\n httpOptions = val;\n return this;\n }\n return httpOptions;\n };\n\n /**\n * @ngdoc service\n * @name $templateRequest\n *\n * @description\n * The `$templateRequest` service runs security checks then downloads the provided template using\n * `$http` and, upon success, stores the contents inside of `$templateCache`. If the HTTP request\n * fails or the response data of the HTTP request is empty, a `$compile` error will be thrown (the\n * exception can be thwarted by setting the 2nd parameter of the function to true). Note that the\n * contents of `$templateCache` are trusted, so the call to `$sce.getTrustedUrl(tpl)` is omitted\n * when `tpl` is of type string and `$templateCache` has the matching entry.\n *\n * If you want to pass custom options to the `$http` service, such as setting the Accept header you\n * can configure this via {@link $templateRequestProvider#httpOptions}.\n *\n * @param {string|TrustedResourceUrl} tpl The HTTP request template URL\n * @param {boolean=} ignoreRequestError Whether or not to ignore the exception when the request fails or the template is empty\n *\n * @return {Promise} a promise for the HTTP response data of the given URL.\n *\n * @property {number} totalPendingRequests total amount of pending template requests being downloaded.\n */\n this.$get = ['$exceptionHandler', '$templateCache', '$http', '$q', '$sce',\n function($exceptionHandler, $templateCache, $http, $q, $sce) {\n\n function handleRequestFn(tpl, ignoreRequestError) {\n handleRequestFn.totalPendingRequests++;\n\n // We consider the template cache holds only trusted templates, so\n // there's no need to go through whitelisting again for keys that already\n // are included in there. This also makes Angular accept any script\n // directive, no matter its name. However, we still need to unwrap trusted\n // types.\n if (!isString(tpl) || isUndefined($templateCache.get(tpl))) {\n tpl = $sce.getTrustedResourceUrl(tpl);\n }\n\n var transformResponse = $http.defaults && $http.defaults.transformResponse;\n\n if (isArray(transformResponse)) {\n transformResponse = transformResponse.filter(function(transformer) {\n return transformer !== defaultHttpResponseTransform;\n });\n } else if (transformResponse === defaultHttpResponseTransform) {\n transformResponse = null;\n }\n\n return $http.get(tpl, extend({\n cache: $templateCache,\n transformResponse: transformResponse\n }, httpOptions))\n .finally(function() {\n handleRequestFn.totalPendingRequests--;\n })\n .then(function(response) {\n $templateCache.put(tpl, response.data);\n return response.data;\n }, handleError);\n\n function handleError(resp) {\n if (!ignoreRequestError) {\n resp = $templateRequestMinErr('tpload',\n 'Failed to load template: {0} (HTTP status: {1} {2})',\n tpl, resp.status, resp.statusText);\n\n $exceptionHandler(resp);\n }\n\n return $q.reject(resp);\n }\n }\n\n handleRequestFn.totalPendingRequests = 0;\n\n return handleRequestFn;\n }\n ];\n}\n\n/** @this */\nfunction $$TestabilityProvider() {\n this.$get = ['$rootScope', '$browser', '$location',\n function($rootScope, $browser, $location) {\n\n /**\n * @name $testability\n *\n * @description\n * The private $$testability service provides a collection of methods for use when debugging\n * or by automated test and debugging tools.\n */\n var testability = {};\n\n /**\n * @name $$testability#findBindings\n *\n * @description\n * Returns an array of elements that are bound (via ng-bind or {{}})\n * to expressions matching the input.\n *\n * @param {Element} element The element root to search from.\n * @param {string} expression The binding expression to match.\n * @param {boolean} opt_exactMatch If true, only returns exact matches\n * for the expression. Filters and whitespace are ignored.\n */\n testability.findBindings = function(element, expression, opt_exactMatch) {\n var bindings = element.getElementsByClassName('ng-binding');\n var matches = [];\n forEach(bindings, function(binding) {\n var dataBinding = angular.element(binding).data('$binding');\n if (dataBinding) {\n forEach(dataBinding, function(bindingName) {\n if (opt_exactMatch) {\n var matcher = new RegExp('(^|\\\\s)' + escapeForRegexp(expression) + '(\\\\s|\\\\||$)');\n if (matcher.test(bindingName)) {\n matches.push(binding);\n }\n } else {\n if (bindingName.indexOf(expression) !== -1) {\n matches.push(binding);\n }\n }\n });\n }\n });\n return matches;\n };\n\n /**\n * @name $$testability#findModels\n *\n * @description\n * Returns an array of elements that are two-way found via ng-model to\n * expressions matching the input.\n *\n * @param {Element} element The element root to search from.\n * @param {string} expression The model expression to match.\n * @param {boolean} opt_exactMatch If true, only returns exact matches\n * for the expression.\n */\n testability.findModels = function(element, expression, opt_exactMatch) {\n var prefixes = ['ng-', 'data-ng-', 'ng\\\\:'];\n for (var p = 0; p < prefixes.length; ++p) {\n var attributeEquals = opt_exactMatch ? '=' : '*=';\n var selector = '[' + prefixes[p] + 'model' + attributeEquals + '\"' + expression + '\"]';\n var elements = element.querySelectorAll(selector);\n if (elements.length) {\n return elements;\n }\n }\n };\n\n /**\n * @name $$testability#getLocation\n *\n * @description\n * Shortcut for getting the location in a browser agnostic way. Returns\n * the path, search, and hash. (e.g. /path?a=b#hash)\n */\n testability.getLocation = function() {\n return $location.url();\n };\n\n /**\n * @name $$testability#setLocation\n *\n * @description\n * Shortcut for navigating to a location without doing a full page reload.\n *\n * @param {string} url The location url (path, search and hash,\n * e.g. /path?a=b#hash) to go to.\n */\n testability.setLocation = function(url) {\n if (url !== $location.url()) {\n $location.url(url);\n $rootScope.$digest();\n }\n };\n\n /**\n * @name $$testability#whenStable\n *\n * @description\n * Calls the callback when $timeout and $http requests are completed.\n *\n * @param {function} callback\n */\n testability.whenStable = function(callback) {\n $browser.notifyWhenNoOutstandingRequests(callback);\n };\n\n return testability;\n }];\n}\n\n/** @this */\nfunction $TimeoutProvider() {\n this.$get = ['$rootScope', '$browser', '$q', '$$q', '$exceptionHandler',\n function($rootScope, $browser, $q, $$q, $exceptionHandler) {\n\n var deferreds = {};\n\n\n /**\n * @ngdoc service\n * @name $timeout\n *\n * @description\n * Angular's wrapper for `window.setTimeout`. The `fn` function is wrapped into a try/catch\n * block and delegates any exceptions to\n * {@link ng.$exceptionHandler $exceptionHandler} service.\n *\n * The return value of calling `$timeout` is a promise, which will be resolved when\n * the delay has passed and the timeout function, if provided, is executed.\n *\n * To cancel a timeout request, call `$timeout.cancel(promise)`.\n *\n * In tests you can use {@link ngMock.$timeout `$timeout.flush()`} to\n * synchronously flush the queue of deferred functions.\n *\n * If you only want a promise that will be resolved after some specified delay\n * then you can call `$timeout` without the `fn` function.\n *\n * @param {function()=} fn A function, whose execution should be delayed.\n * @param {number=} [delay=0] Delay in milliseconds.\n * @param {boolean=} [invokeApply=true] If set to `false` skips model dirty checking, otherwise\n * will invoke `fn` within the {@link ng.$rootScope.Scope#$apply $apply} block.\n * @param {...*=} Pass additional parameters to the executed function.\n * @returns {Promise} Promise that will be resolved when the timeout is reached. The promise\n * will be resolved with the return value of the `fn` function.\n *\n */\n function timeout(fn, delay, invokeApply) {\n if (!isFunction(fn)) {\n invokeApply = delay;\n delay = fn;\n fn = noop;\n }\n\n var args = sliceArgs(arguments, 3),\n skipApply = (isDefined(invokeApply) && !invokeApply),\n deferred = (skipApply ? $$q : $q).defer(),\n promise = deferred.promise,\n timeoutId;\n\n timeoutId = $browser.defer(function() {\n try {\n deferred.resolve(fn.apply(null, args));\n } catch (e) {\n deferred.reject(e);\n $exceptionHandler(e);\n } finally {\n delete deferreds[promise.$$timeoutId];\n }\n\n if (!skipApply) $rootScope.$apply();\n }, delay);\n\n promise.$$timeoutId = timeoutId;\n deferreds[timeoutId] = deferred;\n\n return promise;\n }\n\n\n /**\n * @ngdoc method\n * @name $timeout#cancel\n *\n * @description\n * Cancels a task associated with the `promise`. As a result of this, the promise will be\n * resolved with a rejection.\n *\n * @param {Promise=} promise Promise returned by the `$timeout` function.\n * @returns {boolean} Returns `true` if the task hasn't executed yet and was successfully\n * canceled.\n */\n timeout.cancel = function(promise) {\n if (promise && promise.$$timeoutId in deferreds) {\n // Timeout cancels should not report an unhandled promise.\n deferreds[promise.$$timeoutId].promise.catch(noop);\n deferreds[promise.$$timeoutId].reject('canceled');\n delete deferreds[promise.$$timeoutId];\n return $browser.defer.cancel(promise.$$timeoutId);\n }\n return false;\n };\n\n return timeout;\n }];\n}\n\n// NOTE: The usage of window and document instead of $window and $document here is\n// deliberate. This service depends on the specific behavior of anchor nodes created by the\n// browser (resolving and parsing URLs) that is unlikely to be provided by mock objects and\n// cause us to break tests. In addition, when the browser resolves a URL for XHR, it\n// doesn't know about mocked locations and resolves URLs to the real document - which is\n// exactly the behavior needed here. There is little value is mocking these out for this\n// service.\nvar urlParsingNode = window.document.createElement('a');\nvar originUrl = urlResolve(window.location.href);\n\n\n/**\n *\n * Implementation Notes for non-IE browsers\n * ----------------------------------------\n * Assigning a URL to the href property of an anchor DOM node, even one attached to the DOM,\n * results both in the normalizing and parsing of the URL. Normalizing means that a relative\n * URL will be resolved into an absolute URL in the context of the application document.\n * Parsing means that the anchor node's host, hostname, protocol, port, pathname and related\n * properties are all populated to reflect the normalized URL. This approach has wide\n * compatibility - Safari 1+, Mozilla 1+, Opera 7+,e etc. See\n * http://www.aptana.com/reference/html/api/HTMLAnchorElement.html\n *\n * Implementation Notes for IE\n * ---------------------------\n * IE <= 10 normalizes the URL when assigned to the anchor node similar to the other\n * browsers. However, the parsed components will not be set if the URL assigned did not specify\n * them. (e.g. if you assign a.href = \"foo\", then a.protocol, a.host, etc. will be empty.) We\n * work around that by performing the parsing in a 2nd step by taking a previously normalized\n * URL (e.g. by assigning to a.href) and assigning it a.href again. This correctly populates the\n * properties such as protocol, hostname, port, etc.\n *\n * References:\n * http://developer.mozilla.org/en-US/docs/Web/API/HTMLAnchorElement\n * http://www.aptana.com/reference/html/api/HTMLAnchorElement.html\n * http://url.spec.whatwg.org/#urlutils\n * https://github.com/angular/angular.js/pull/2902\n * http://james.padolsey.com/javascript/parsing-urls-with-the-dom/\n *\n * @kind function\n * @param {string} url The URL to be parsed.\n * @description Normalizes and parses a URL.\n * @returns {object} Returns the normalized URL as a dictionary.\n *\n * | member name | Description |\n * |---------------|----------------|\n * | href | A normalized version of the provided URL if it was not an absolute URL |\n * | protocol | The protocol including the trailing colon |\n * | host | The host and port (if the port is non-default) of the normalizedUrl |\n * | search | The search params, minus the question mark |\n * | hash | The hash string, minus the hash symbol\n * | hostname | The hostname\n * | port | The port, without \":\"\n * | pathname | The pathname, beginning with \"/\"\n *\n */\nfunction urlResolve(url) {\n var href = url;\n\n // Support: IE 9-11 only\n if (msie) {\n // Normalize before parse. Refer Implementation Notes on why this is\n // done in two steps on IE.\n urlParsingNode.setAttribute('href', href);\n href = urlParsingNode.href;\n }\n\n urlParsingNode.setAttribute('href', href);\n\n // urlParsingNode provides the UrlUtils interface - http://url.spec.whatwg.org/#urlutils\n return {\n href: urlParsingNode.href,\n protocol: urlParsingNode.protocol ? urlParsingNode.protocol.replace(/:$/, '') : '',\n host: urlParsingNode.host,\n search: urlParsingNode.search ? urlParsingNode.search.replace(/^\\?/, '') : '',\n hash: urlParsingNode.hash ? urlParsingNode.hash.replace(/^#/, '') : '',\n hostname: urlParsingNode.hostname,\n port: urlParsingNode.port,\n pathname: (urlParsingNode.pathname.charAt(0) === '/')\n ? urlParsingNode.pathname\n : '/' + urlParsingNode.pathname\n };\n}\n\n/**\n * Parse a request URL and determine whether this is a same-origin request as the application document.\n *\n * @param {string|object} requestUrl The url of the request as a string that will be resolved\n * or a parsed URL object.\n * @returns {boolean} Whether the request is for the same origin as the application document.\n */\nfunction urlIsSameOrigin(requestUrl) {\n var parsed = (isString(requestUrl)) ? urlResolve(requestUrl) : requestUrl;\n return (parsed.protocol === originUrl.protocol &&\n parsed.host === originUrl.host);\n}\n\n/**\n * @ngdoc service\n * @name $window\n * @this\n *\n * @description\n * A reference to the browser's `window` object. While `window`\n * is globally available in JavaScript, it causes testability problems, because\n * it is a global variable. In angular we always refer to it through the\n * `$window` service, so it may be overridden, removed or mocked for testing.\n *\n * Expressions, like the one defined for the `ngClick` directive in the example\n * below, are evaluated with respect to the current scope. Therefore, there is\n * no risk of inadvertently coding in a dependency on a global value in such an\n * expression.\n *\n * @example\n \n \n \n
\n \n \n
\n
\n \n it('should display the greeting in the input box', function() {\n element(by.model('greeting')).sendKeys('Hello, E2E Tests');\n // If we click the button it will block the test runner\n // element(':button').click();\n });\n \n
\n */\nfunction $WindowProvider() {\n this.$get = valueFn(window);\n}\n\n/**\n * @name $$cookieReader\n * @requires $document\n *\n * @description\n * This is a private service for reading cookies used by $http and ngCookies\n *\n * @return {Object} a key/value map of the current cookies\n */\nfunction $$CookieReader($document) {\n var rawDocument = $document[0] || {};\n var lastCookies = {};\n var lastCookieString = '';\n\n function safeDecodeURIComponent(str) {\n try {\n return decodeURIComponent(str);\n } catch (e) {\n return str;\n }\n }\n\n return function() {\n var cookieArray, cookie, i, index, name;\n var currentCookieString = rawDocument.cookie || '';\n\n if (currentCookieString !== lastCookieString) {\n lastCookieString = currentCookieString;\n cookieArray = lastCookieString.split('; ');\n lastCookies = {};\n\n for (i = 0; i < cookieArray.length; i++) {\n cookie = cookieArray[i];\n index = cookie.indexOf('=');\n if (index > 0) { //ignore nameless cookies\n name = safeDecodeURIComponent(cookie.substring(0, index));\n // the first value that is seen for a cookie is the most\n // specific one. values for the same cookie name that\n // follow are for less specific paths.\n if (isUndefined(lastCookies[name])) {\n lastCookies[name] = safeDecodeURIComponent(cookie.substring(index + 1));\n }\n }\n }\n }\n return lastCookies;\n };\n}\n\n$$CookieReader.$inject = ['$document'];\n\n/** @this */\nfunction $$CookieReaderProvider() {\n this.$get = $$CookieReader;\n}\n\n/* global currencyFilter: true,\n dateFilter: true,\n filterFilter: true,\n jsonFilter: true,\n limitToFilter: true,\n lowercaseFilter: true,\n numberFilter: true,\n orderByFilter: true,\n uppercaseFilter: true,\n */\n\n/**\n * @ngdoc provider\n * @name $filterProvider\n * @description\n *\n * Filters are just functions which transform input to an output. However filters need to be\n * Dependency Injected. To achieve this a filter definition consists of a factory function which is\n * annotated with dependencies and is responsible for creating a filter function.\n *\n *
\n * **Note:** Filter names must be valid angular {@link expression} identifiers, such as `uppercase` or `orderBy`.\n * Names with special characters, such as hyphens and dots, are not allowed. If you wish to namespace\n * your filters, then you can use capitalization (`myappSubsectionFilterx`) or underscores\n * (`myapp_subsection_filterx`).\n *
\n *\n * ```js\n * // Filter registration\n * function MyModule($provide, $filterProvider) {\n * // create a service to demonstrate injection (not always needed)\n * $provide.value('greet', function(name){\n * return 'Hello ' + name + '!';\n * });\n *\n * // register a filter factory which uses the\n * // greet service to demonstrate DI.\n * $filterProvider.register('greet', function(greet){\n * // return the filter function which uses the greet service\n * // to generate salutation\n * return function(text) {\n * // filters need to be forgiving so check input validity\n * return text && greet(text) || text;\n * };\n * });\n * }\n * ```\n *\n * The filter function is registered with the `$injector` under the filter name suffix with\n * `Filter`.\n *\n * ```js\n * it('should be the same instance', inject(\n * function($filterProvider) {\n * $filterProvider.register('reverse', function(){\n * return ...;\n * });\n * },\n * function($filter, reverseFilter) {\n * expect($filter('reverse')).toBe(reverseFilter);\n * });\n * ```\n *\n *\n * For more information about how angular filters work, and how to create your own filters, see\n * {@link guide/filter Filters} in the Angular Developer Guide.\n */\n\n/**\n * @ngdoc service\n * @name $filter\n * @kind function\n * @description\n * Filters are used for formatting data displayed to the user.\n *\n * They can be used in view templates, controllers or services.Angular comes\n * with a collection of [built-in filters](api/ng/filter), but it is easy to\n * define your own as well.\n *\n * The general syntax in templates is as follows:\n *\n * ```html\n * {{ expression [| filter_name[:parameter_value] ... ] }}\n * ```\n *\n * @param {String} name Name of the filter function to retrieve\n * @return {Function} the filter function\n * @example\n \n \n
\n

{{ originalText }}

\n

{{ filteredText }}

\n
\n
\n\n \n angular.module('filterExample', [])\n .controller('MainCtrl', function($scope, $filter) {\n $scope.originalText = 'hello';\n $scope.filteredText = $filter('uppercase')($scope.originalText);\n });\n \n
\n */\n$FilterProvider.$inject = ['$provide'];\n/** @this */\nfunction $FilterProvider($provide) {\n var suffix = 'Filter';\n\n /**\n * @ngdoc method\n * @name $filterProvider#register\n * @param {string|Object} name Name of the filter function, or an object map of filters where\n * the keys are the filter names and the values are the filter factories.\n *\n *
\n * **Note:** Filter names must be valid angular {@link expression} identifiers, such as `uppercase` or `orderBy`.\n * Names with special characters, such as hyphens and dots, are not allowed. If you wish to namespace\n * your filters, then you can use capitalization (`myappSubsectionFilterx`) or underscores\n * (`myapp_subsection_filterx`).\n *
\n * @param {Function} factory If the first argument was a string, a factory function for the filter to be registered.\n * @returns {Object} Registered filter instance, or if a map of filters was provided then a map\n * of the registered filter instances.\n */\n function register(name, factory) {\n if (isObject(name)) {\n var filters = {};\n forEach(name, function(filter, key) {\n filters[key] = register(key, filter);\n });\n return filters;\n } else {\n return $provide.factory(name + suffix, factory);\n }\n }\n this.register = register;\n\n this.$get = ['$injector', function($injector) {\n return function(name) {\n return $injector.get(name + suffix);\n };\n }];\n\n ////////////////////////////////////////\n\n /* global\n currencyFilter: false,\n dateFilter: false,\n filterFilter: false,\n jsonFilter: false,\n limitToFilter: false,\n lowercaseFilter: false,\n numberFilter: false,\n orderByFilter: false,\n uppercaseFilter: false\n */\n\n register('currency', currencyFilter);\n register('date', dateFilter);\n register('filter', filterFilter);\n register('json', jsonFilter);\n register('limitTo', limitToFilter);\n register('lowercase', lowercaseFilter);\n register('number', numberFilter);\n register('orderBy', orderByFilter);\n register('uppercase', uppercaseFilter);\n}\n\n/**\n * @ngdoc filter\n * @name filter\n * @kind function\n *\n * @description\n * Selects a subset of items from `array` and returns it as a new array.\n *\n * @param {Array} array The source array.\n * @param {string|Object|function()} expression The predicate to be used for selecting items from\n * `array`.\n *\n * Can be one of:\n *\n * - `string`: The string is used for matching against the contents of the `array`. All strings or\n * objects with string properties in `array` that match this string will be returned. This also\n * applies to nested object properties.\n * The predicate can be negated by prefixing the string with `!`.\n *\n * - `Object`: A pattern object can be used to filter specific properties on objects contained\n * by `array`. For example `{name:\"M\", phone:\"1\"}` predicate will return an array of items\n * which have property `name` containing \"M\" and property `phone` containing \"1\". A special\n * property name (`$` by default) can be used (e.g. as in `{$: \"text\"}`) to accept a match\n * against any property of the object or its nested object properties. That's equivalent to the\n * simple substring match with a `string` as described above. The special property name can be\n * overwritten, using the `anyPropertyKey` parameter.\n * The predicate can be negated by prefixing the string with `!`.\n * For example `{name: \"!M\"}` predicate will return an array of items which have property `name`\n * not containing \"M\".\n *\n * Note that a named property will match properties on the same level only, while the special\n * `$` property will match properties on the same level or deeper. E.g. an array item like\n * `{name: {first: 'John', last: 'Doe'}}` will **not** be matched by `{name: 'John'}`, but\n * **will** be matched by `{$: 'John'}`.\n *\n * - `function(value, index, array)`: A predicate function can be used to write arbitrary filters.\n * The function is called for each element of the array, with the element, its index, and\n * the entire array itself as arguments.\n *\n * The final result is an array of those elements that the predicate returned true for.\n *\n * @param {function(actual, expected)|true|false} [comparator] Comparator which is used in\n * determining if the expected value (from the filter expression) and actual value (from\n * the object in the array) should be considered a match.\n *\n * Can be one of:\n *\n * - `function(actual, expected)`:\n * The function will be given the object value and the predicate value to compare and\n * should return true if both values should be considered equal.\n *\n * - `true`: A shorthand for `function(actual, expected) { return angular.equals(actual, expected)}`.\n * This is essentially strict comparison of expected and actual.\n *\n * - `false`: A short hand for a function which will look for a substring match in a case\n * insensitive way. Primitive values are converted to strings. Objects are not compared against\n * primitives, unless they have a custom `toString` method (e.g. `Date` objects).\n *\n *\n * Defaults to `false`.\n *\n * @param {string} [anyPropertyKey] The special property name that matches against any property.\n * By default `$`.\n *\n * @example\n \n \n
\n\n \n \n \n \n \n \n \n
NamePhone
{{friend.name}}{{friend.phone}}
\n
\n
\n
\n
\n
\n \n \n \n \n \n \n
NamePhone
{{friendObj.name}}{{friendObj.phone}}
\n
\n \n var expectFriendNames = function(expectedNames, key) {\n element.all(by.repeater(key + ' in friends').column(key + '.name')).then(function(arr) {\n arr.forEach(function(wd, i) {\n expect(wd.getText()).toMatch(expectedNames[i]);\n });\n });\n };\n\n it('should search across all fields when filtering with a string', function() {\n var searchText = element(by.model('searchText'));\n searchText.clear();\n searchText.sendKeys('m');\n expectFriendNames(['Mary', 'Mike', 'Adam'], 'friend');\n\n searchText.clear();\n searchText.sendKeys('76');\n expectFriendNames(['John', 'Julie'], 'friend');\n });\n\n it('should search in specific fields when filtering with a predicate object', function() {\n var searchAny = element(by.model('search.$'));\n searchAny.clear();\n searchAny.sendKeys('i');\n expectFriendNames(['Mary', 'Mike', 'Julie', 'Juliette'], 'friendObj');\n });\n it('should use a equal comparison when comparator is true', function() {\n var searchName = element(by.model('search.name'));\n var strict = element(by.model('strict'));\n searchName.clear();\n searchName.sendKeys('Julie');\n strict.click();\n expectFriendNames(['Julie'], 'friendObj');\n });\n \n
\n */\n\nfunction filterFilter() {\n return function(array, expression, comparator, anyPropertyKey) {\n if (!isArrayLike(array)) {\n if (array == null) {\n return array;\n } else {\n throw minErr('filter')('notarray', 'Expected array but received: {0}', array);\n }\n }\n\n anyPropertyKey = anyPropertyKey || '$';\n var expressionType = getTypeForFilter(expression);\n var predicateFn;\n var matchAgainstAnyProp;\n\n switch (expressionType) {\n case 'function':\n predicateFn = expression;\n break;\n case 'boolean':\n case 'null':\n case 'number':\n case 'string':\n matchAgainstAnyProp = true;\n // falls through\n case 'object':\n predicateFn = createPredicateFn(expression, comparator, anyPropertyKey, matchAgainstAnyProp);\n break;\n default:\n return array;\n }\n\n return Array.prototype.filter.call(array, predicateFn);\n };\n}\n\n// Helper functions for `filterFilter`\nfunction createPredicateFn(expression, comparator, anyPropertyKey, matchAgainstAnyProp) {\n var shouldMatchPrimitives = isObject(expression) && (anyPropertyKey in expression);\n var predicateFn;\n\n if (comparator === true) {\n comparator = equals;\n } else if (!isFunction(comparator)) {\n comparator = function(actual, expected) {\n if (isUndefined(actual)) {\n // No substring matching against `undefined`\n return false;\n }\n if ((actual === null) || (expected === null)) {\n // No substring matching against `null`; only match against `null`\n return actual === expected;\n }\n if (isObject(expected) || (isObject(actual) && !hasCustomToString(actual))) {\n // Should not compare primitives against objects, unless they have custom `toString` method\n return false;\n }\n\n actual = lowercase('' + actual);\n expected = lowercase('' + expected);\n return actual.indexOf(expected) !== -1;\n };\n }\n\n predicateFn = function(item) {\n if (shouldMatchPrimitives && !isObject(item)) {\n return deepCompare(item, expression[anyPropertyKey], comparator, anyPropertyKey, false);\n }\n return deepCompare(item, expression, comparator, anyPropertyKey, matchAgainstAnyProp);\n };\n\n return predicateFn;\n}\n\nfunction deepCompare(actual, expected, comparator, anyPropertyKey, matchAgainstAnyProp, dontMatchWholeObject) {\n var actualType = getTypeForFilter(actual);\n var expectedType = getTypeForFilter(expected);\n\n if ((expectedType === 'string') && (expected.charAt(0) === '!')) {\n return !deepCompare(actual, expected.substring(1), comparator, anyPropertyKey, matchAgainstAnyProp);\n } else if (isArray(actual)) {\n // In case `actual` is an array, consider it a match\n // if ANY of it's items matches `expected`\n return actual.some(function(item) {\n return deepCompare(item, expected, comparator, anyPropertyKey, matchAgainstAnyProp);\n });\n }\n\n switch (actualType) {\n case 'object':\n var key;\n if (matchAgainstAnyProp) {\n for (key in actual) {\n if ((key.charAt(0) !== '$') && deepCompare(actual[key], expected, comparator, anyPropertyKey, true)) {\n return true;\n }\n }\n return dontMatchWholeObject ? false : deepCompare(actual, expected, comparator, anyPropertyKey, false);\n } else if (expectedType === 'object') {\n for (key in expected) {\n var expectedVal = expected[key];\n if (isFunction(expectedVal) || isUndefined(expectedVal)) {\n continue;\n }\n\n var matchAnyProperty = key === anyPropertyKey;\n var actualVal = matchAnyProperty ? actual : actual[key];\n if (!deepCompare(actualVal, expectedVal, comparator, anyPropertyKey, matchAnyProperty, matchAnyProperty)) {\n return false;\n }\n }\n return true;\n } else {\n return comparator(actual, expected);\n }\n case 'function':\n return false;\n default:\n return comparator(actual, expected);\n }\n}\n\n// Used for easily differentiating between `null` and actual `object`\nfunction getTypeForFilter(val) {\n return (val === null) ? 'null' : typeof val;\n}\n\nvar MAX_DIGITS = 22;\nvar DECIMAL_SEP = '.';\nvar ZERO_CHAR = '0';\n\n/**\n * @ngdoc filter\n * @name currency\n * @kind function\n *\n * @description\n * Formats a number as a currency (ie $1,234.56). When no currency symbol is provided, default\n * symbol for current locale is used.\n *\n * @param {number} amount Input to filter.\n * @param {string=} symbol Currency symbol or identifier to be displayed.\n * @param {number=} fractionSize Number of decimal places to round the amount to, defaults to default max fraction size for current locale\n * @returns {string} Formatted number.\n *\n *\n * @example\n \n \n \n
\n
\n default currency symbol ($): {{amount | currency}}
\n custom currency identifier (USD$): {{amount | currency:\"USD$\"}}
\n no fractions (0): {{amount | currency:\"USD$\":0}}\n
\n
\n \n it('should init with 1234.56', function() {\n expect(element(by.id('currency-default')).getText()).toBe('$1,234.56');\n expect(element(by.id('currency-custom')).getText()).toBe('USD$1,234.56');\n expect(element(by.id('currency-no-fractions')).getText()).toBe('USD$1,235');\n });\n it('should update', function() {\n if (browser.params.browser === 'safari') {\n // Safari does not understand the minus key. See\n // https://github.com/angular/protractor/issues/481\n return;\n }\n element(by.model('amount')).clear();\n element(by.model('amount')).sendKeys('-1234');\n expect(element(by.id('currency-default')).getText()).toBe('-$1,234.00');\n expect(element(by.id('currency-custom')).getText()).toBe('-USD$1,234.00');\n expect(element(by.id('currency-no-fractions')).getText()).toBe('-USD$1,234');\n });\n \n
\n */\ncurrencyFilter.$inject = ['$locale'];\nfunction currencyFilter($locale) {\n var formats = $locale.NUMBER_FORMATS;\n return function(amount, currencySymbol, fractionSize) {\n if (isUndefined(currencySymbol)) {\n currencySymbol = formats.CURRENCY_SYM;\n }\n\n if (isUndefined(fractionSize)) {\n fractionSize = formats.PATTERNS[1].maxFrac;\n }\n\n // if null or undefined pass it through\n return (amount == null)\n ? amount\n : formatNumber(amount, formats.PATTERNS[1], formats.GROUP_SEP, formats.DECIMAL_SEP, fractionSize).\n replace(/\\u00A4/g, currencySymbol);\n };\n}\n\n/**\n * @ngdoc filter\n * @name number\n * @kind function\n *\n * @description\n * Formats a number as text.\n *\n * If the input is null or undefined, it will just be returned.\n * If the input is infinite (Infinity or -Infinity), the Infinity symbol '∞' or '-∞' is returned, respectively.\n * If the input is not a number an empty string is returned.\n *\n *\n * @param {number|string} number Number to format.\n * @param {(number|string)=} fractionSize Number of decimal places to round the number to.\n * If this is not provided then the fraction size is computed from the current locale's number\n * formatting pattern. In the case of the default locale, it will be 3.\n * @returns {string} Number rounded to `fractionSize` appropriately formatted based on the current\n * locale (e.g., in the en_US locale it will have \".\" as the decimal separator and\n * include \",\" group separators after each third digit).\n *\n * @example\n \n \n \n
\n
\n Default formatting: {{val | number}}
\n No fractions: {{val | number:0}}
\n Negative number: {{-val | number:4}}\n
\n
\n \n it('should format numbers', function() {\n expect(element(by.id('number-default')).getText()).toBe('1,234.568');\n expect(element(by.binding('val | number:0')).getText()).toBe('1,235');\n expect(element(by.binding('-val | number:4')).getText()).toBe('-1,234.5679');\n });\n\n it('should update', function() {\n element(by.model('val')).clear();\n element(by.model('val')).sendKeys('3374.333');\n expect(element(by.id('number-default')).getText()).toBe('3,374.333');\n expect(element(by.binding('val | number:0')).getText()).toBe('3,374');\n expect(element(by.binding('-val | number:4')).getText()).toBe('-3,374.3330');\n });\n \n
\n */\nnumberFilter.$inject = ['$locale'];\nfunction numberFilter($locale) {\n var formats = $locale.NUMBER_FORMATS;\n return function(number, fractionSize) {\n\n // if null or undefined pass it through\n return (number == null)\n ? number\n : formatNumber(number, formats.PATTERNS[0], formats.GROUP_SEP, formats.DECIMAL_SEP,\n fractionSize);\n };\n}\n\n/**\n * Parse a number (as a string) into three components that can be used\n * for formatting the number.\n *\n * (Significant bits of this parse algorithm came from https://github.com/MikeMcl/big.js/)\n *\n * @param {string} numStr The number to parse\n * @return {object} An object describing this number, containing the following keys:\n * - d : an array of digits containing leading zeros as necessary\n * - i : the number of the digits in `d` that are to the left of the decimal point\n * - e : the exponent for numbers that would need more than `MAX_DIGITS` digits in `d`\n *\n */\nfunction parse(numStr) {\n var exponent = 0, digits, numberOfIntegerDigits;\n var i, j, zeros;\n\n // Decimal point?\n if ((numberOfIntegerDigits = numStr.indexOf(DECIMAL_SEP)) > -1) {\n numStr = numStr.replace(DECIMAL_SEP, '');\n }\n\n // Exponential form?\n if ((i = numStr.search(/e/i)) > 0) {\n // Work out the exponent.\n if (numberOfIntegerDigits < 0) numberOfIntegerDigits = i;\n numberOfIntegerDigits += +numStr.slice(i + 1);\n numStr = numStr.substring(0, i);\n } else if (numberOfIntegerDigits < 0) {\n // There was no decimal point or exponent so it is an integer.\n numberOfIntegerDigits = numStr.length;\n }\n\n // Count the number of leading zeros.\n for (i = 0; numStr.charAt(i) === ZERO_CHAR; i++) { /* empty */ }\n\n if (i === (zeros = numStr.length)) {\n // The digits are all zero.\n digits = [0];\n numberOfIntegerDigits = 1;\n } else {\n // Count the number of trailing zeros\n zeros--;\n while (numStr.charAt(zeros) === ZERO_CHAR) zeros--;\n\n // Trailing zeros are insignificant so ignore them\n numberOfIntegerDigits -= i;\n digits = [];\n // Convert string to array of digits without leading/trailing zeros.\n for (j = 0; i <= zeros; i++, j++) {\n digits[j] = +numStr.charAt(i);\n }\n }\n\n // If the number overflows the maximum allowed digits then use an exponent.\n if (numberOfIntegerDigits > MAX_DIGITS) {\n digits = digits.splice(0, MAX_DIGITS - 1);\n exponent = numberOfIntegerDigits - 1;\n numberOfIntegerDigits = 1;\n }\n\n return { d: digits, e: exponent, i: numberOfIntegerDigits };\n}\n\n/**\n * Round the parsed number to the specified number of decimal places\n * This function changed the parsedNumber in-place\n */\nfunction roundNumber(parsedNumber, fractionSize, minFrac, maxFrac) {\n var digits = parsedNumber.d;\n var fractionLen = digits.length - parsedNumber.i;\n\n // determine fractionSize if it is not specified; `+fractionSize` converts it to a number\n fractionSize = (isUndefined(fractionSize)) ? Math.min(Math.max(minFrac, fractionLen), maxFrac) : +fractionSize;\n\n // The index of the digit to where rounding is to occur\n var roundAt = fractionSize + parsedNumber.i;\n var digit = digits[roundAt];\n\n if (roundAt > 0) {\n // Drop fractional digits beyond `roundAt`\n digits.splice(Math.max(parsedNumber.i, roundAt));\n\n // Set non-fractional digits beyond `roundAt` to 0\n for (var j = roundAt; j < digits.length; j++) {\n digits[j] = 0;\n }\n } else {\n // We rounded to zero so reset the parsedNumber\n fractionLen = Math.max(0, fractionLen);\n parsedNumber.i = 1;\n digits.length = Math.max(1, roundAt = fractionSize + 1);\n digits[0] = 0;\n for (var i = 1; i < roundAt; i++) digits[i] = 0;\n }\n\n if (digit >= 5) {\n if (roundAt - 1 < 0) {\n for (var k = 0; k > roundAt; k--) {\n digits.unshift(0);\n parsedNumber.i++;\n }\n digits.unshift(1);\n parsedNumber.i++;\n } else {\n digits[roundAt - 1]++;\n }\n }\n\n // Pad out with zeros to get the required fraction length\n for (; fractionLen < Math.max(0, fractionSize); fractionLen++) digits.push(0);\n\n\n // Do any carrying, e.g. a digit was rounded up to 10\n var carry = digits.reduceRight(function(carry, d, i, digits) {\n d = d + carry;\n digits[i] = d % 10;\n return Math.floor(d / 10);\n }, 0);\n if (carry) {\n digits.unshift(carry);\n parsedNumber.i++;\n }\n}\n\n/**\n * Format a number into a string\n * @param {number} number The number to format\n * @param {{\n * minFrac, // the minimum number of digits required in the fraction part of the number\n * maxFrac, // the maximum number of digits required in the fraction part of the number\n * gSize, // number of digits in each group of separated digits\n * lgSize, // number of digits in the last group of digits before the decimal separator\n * negPre, // the string to go in front of a negative number (e.g. `-` or `(`))\n * posPre, // the string to go in front of a positive number\n * negSuf, // the string to go after a negative number (e.g. `)`)\n * posSuf // the string to go after a positive number\n * }} pattern\n * @param {string} groupSep The string to separate groups of number (e.g. `,`)\n * @param {string} decimalSep The string to act as the decimal separator (e.g. `.`)\n * @param {[type]} fractionSize The size of the fractional part of the number\n * @return {string} The number formatted as a string\n */\nfunction formatNumber(number, pattern, groupSep, decimalSep, fractionSize) {\n\n if (!(isString(number) || isNumber(number)) || isNaN(number)) return '';\n\n var isInfinity = !isFinite(number);\n var isZero = false;\n var numStr = Math.abs(number) + '',\n formattedText = '',\n parsedNumber;\n\n if (isInfinity) {\n formattedText = '\\u221e';\n } else {\n parsedNumber = parse(numStr);\n\n roundNumber(parsedNumber, fractionSize, pattern.minFrac, pattern.maxFrac);\n\n var digits = parsedNumber.d;\n var integerLen = parsedNumber.i;\n var exponent = parsedNumber.e;\n var decimals = [];\n isZero = digits.reduce(function(isZero, d) { return isZero && !d; }, true);\n\n // pad zeros for small numbers\n while (integerLen < 0) {\n digits.unshift(0);\n integerLen++;\n }\n\n // extract decimals digits\n if (integerLen > 0) {\n decimals = digits.splice(integerLen, digits.length);\n } else {\n decimals = digits;\n digits = [0];\n }\n\n // format the integer digits with grouping separators\n var groups = [];\n if (digits.length >= pattern.lgSize) {\n groups.unshift(digits.splice(-pattern.lgSize, digits.length).join(''));\n }\n while (digits.length > pattern.gSize) {\n groups.unshift(digits.splice(-pattern.gSize, digits.length).join(''));\n }\n if (digits.length) {\n groups.unshift(digits.join(''));\n }\n formattedText = groups.join(groupSep);\n\n // append the decimal digits\n if (decimals.length) {\n formattedText += decimalSep + decimals.join('');\n }\n\n if (exponent) {\n formattedText += 'e+' + exponent;\n }\n }\n if (number < 0 && !isZero) {\n return pattern.negPre + formattedText + pattern.negSuf;\n } else {\n return pattern.posPre + formattedText + pattern.posSuf;\n }\n}\n\nfunction padNumber(num, digits, trim, negWrap) {\n var neg = '';\n if (num < 0 || (negWrap && num <= 0)) {\n if (negWrap) {\n num = -num + 1;\n } else {\n num = -num;\n neg = '-';\n }\n }\n num = '' + num;\n while (num.length < digits) num = ZERO_CHAR + num;\n if (trim) {\n num = num.substr(num.length - digits);\n }\n return neg + num;\n}\n\n\nfunction dateGetter(name, size, offset, trim, negWrap) {\n offset = offset || 0;\n return function(date) {\n var value = date['get' + name]();\n if (offset > 0 || value > -offset) {\n value += offset;\n }\n if (value === 0 && offset === -12) value = 12;\n return padNumber(value, size, trim, negWrap);\n };\n}\n\nfunction dateStrGetter(name, shortForm, standAlone) {\n return function(date, formats) {\n var value = date['get' + name]();\n var propPrefix = (standAlone ? 'STANDALONE' : '') + (shortForm ? 'SHORT' : '');\n var get = uppercase(propPrefix + name);\n\n return formats[get][value];\n };\n}\n\nfunction timeZoneGetter(date, formats, offset) {\n var zone = -1 * offset;\n var paddedZone = (zone >= 0) ? '+' : '';\n\n paddedZone += padNumber(Math[zone > 0 ? 'floor' : 'ceil'](zone / 60), 2) +\n padNumber(Math.abs(zone % 60), 2);\n\n return paddedZone;\n}\n\nfunction getFirstThursdayOfYear(year) {\n // 0 = index of January\n var dayOfWeekOnFirst = (new Date(year, 0, 1)).getDay();\n // 4 = index of Thursday (+1 to account for 1st = 5)\n // 11 = index of *next* Thursday (+1 account for 1st = 12)\n return new Date(year, 0, ((dayOfWeekOnFirst <= 4) ? 5 : 12) - dayOfWeekOnFirst);\n}\n\nfunction getThursdayThisWeek(datetime) {\n return new Date(datetime.getFullYear(), datetime.getMonth(),\n // 4 = index of Thursday\n datetime.getDate() + (4 - datetime.getDay()));\n}\n\nfunction weekGetter(size) {\n return function(date) {\n var firstThurs = getFirstThursdayOfYear(date.getFullYear()),\n thisThurs = getThursdayThisWeek(date);\n\n var diff = +thisThurs - +firstThurs,\n result = 1 + Math.round(diff / 6.048e8); // 6.048e8 ms per week\n\n return padNumber(result, size);\n };\n}\n\nfunction ampmGetter(date, formats) {\n return date.getHours() < 12 ? formats.AMPMS[0] : formats.AMPMS[1];\n}\n\nfunction eraGetter(date, formats) {\n return date.getFullYear() <= 0 ? formats.ERAS[0] : formats.ERAS[1];\n}\n\nfunction longEraGetter(date, formats) {\n return date.getFullYear() <= 0 ? formats.ERANAMES[0] : formats.ERANAMES[1];\n}\n\nvar DATE_FORMATS = {\n yyyy: dateGetter('FullYear', 4, 0, false, true),\n yy: dateGetter('FullYear', 2, 0, true, true),\n y: dateGetter('FullYear', 1, 0, false, true),\n MMMM: dateStrGetter('Month'),\n MMM: dateStrGetter('Month', true),\n MM: dateGetter('Month', 2, 1),\n M: dateGetter('Month', 1, 1),\n LLLL: dateStrGetter('Month', false, true),\n dd: dateGetter('Date', 2),\n d: dateGetter('Date', 1),\n HH: dateGetter('Hours', 2),\n H: dateGetter('Hours', 1),\n hh: dateGetter('Hours', 2, -12),\n h: dateGetter('Hours', 1, -12),\n mm: dateGetter('Minutes', 2),\n m: dateGetter('Minutes', 1),\n ss: dateGetter('Seconds', 2),\n s: dateGetter('Seconds', 1),\n // while ISO 8601 requires fractions to be prefixed with `.` or `,`\n // we can be just safely rely on using `sss` since we currently don't support single or two digit fractions\n sss: dateGetter('Milliseconds', 3),\n EEEE: dateStrGetter('Day'),\n EEE: dateStrGetter('Day', true),\n a: ampmGetter,\n Z: timeZoneGetter,\n ww: weekGetter(2),\n w: weekGetter(1),\n G: eraGetter,\n GG: eraGetter,\n GGG: eraGetter,\n GGGG: longEraGetter\n};\n\nvar DATE_FORMATS_SPLIT = /((?:[^yMLdHhmsaZEwG']+)|(?:'(?:[^']|'')*')|(?:E+|y+|M+|L+|d+|H+|h+|m+|s+|a|Z|G+|w+))(.*)/,\n NUMBER_STRING = /^-?\\d+$/;\n\n/**\n * @ngdoc filter\n * @name date\n * @kind function\n *\n * @description\n * Formats `date` to a string based on the requested `format`.\n *\n * `format` string can be composed of the following elements:\n *\n * * `'yyyy'`: 4 digit representation of year (e.g. AD 1 => 0001, AD 2010 => 2010)\n * * `'yy'`: 2 digit representation of year, padded (00-99). (e.g. AD 2001 => 01, AD 2010 => 10)\n * * `'y'`: 1 digit representation of year, e.g. (AD 1 => 1, AD 199 => 199)\n * * `'MMMM'`: Month in year (January-December)\n * * `'MMM'`: Month in year (Jan-Dec)\n * * `'MM'`: Month in year, padded (01-12)\n * * `'M'`: Month in year (1-12)\n * * `'LLLL'`: Stand-alone month in year (January-December)\n * * `'dd'`: Day in month, padded (01-31)\n * * `'d'`: Day in month (1-31)\n * * `'EEEE'`: Day in Week,(Sunday-Saturday)\n * * `'EEE'`: Day in Week, (Sun-Sat)\n * * `'HH'`: Hour in day, padded (00-23)\n * * `'H'`: Hour in day (0-23)\n * * `'hh'`: Hour in AM/PM, padded (01-12)\n * * `'h'`: Hour in AM/PM, (1-12)\n * * `'mm'`: Minute in hour, padded (00-59)\n * * `'m'`: Minute in hour (0-59)\n * * `'ss'`: Second in minute, padded (00-59)\n * * `'s'`: Second in minute (0-59)\n * * `'sss'`: Millisecond in second, padded (000-999)\n * * `'a'`: AM/PM marker\n * * `'Z'`: 4 digit (+sign) representation of the timezone offset (-1200-+1200)\n * * `'ww'`: Week of year, padded (00-53). Week 01 is the week with the first Thursday of the year\n * * `'w'`: Week of year (0-53). Week 1 is the week with the first Thursday of the year\n * * `'G'`, `'GG'`, `'GGG'`: The abbreviated form of the era string (e.g. 'AD')\n * * `'GGGG'`: The long form of the era string (e.g. 'Anno Domini')\n *\n * `format` string can also be one of the following predefined\n * {@link guide/i18n localizable formats}:\n *\n * * `'medium'`: equivalent to `'MMM d, y h:mm:ss a'` for en_US locale\n * (e.g. Sep 3, 2010 12:05:08 PM)\n * * `'short'`: equivalent to `'M/d/yy h:mm a'` for en_US locale (e.g. 9/3/10 12:05 PM)\n * * `'fullDate'`: equivalent to `'EEEE, MMMM d, y'` for en_US locale\n * (e.g. Friday, September 3, 2010)\n * * `'longDate'`: equivalent to `'MMMM d, y'` for en_US locale (e.g. September 3, 2010)\n * * `'mediumDate'`: equivalent to `'MMM d, y'` for en_US locale (e.g. Sep 3, 2010)\n * * `'shortDate'`: equivalent to `'M/d/yy'` for en_US locale (e.g. 9/3/10)\n * * `'mediumTime'`: equivalent to `'h:mm:ss a'` for en_US locale (e.g. 12:05:08 PM)\n * * `'shortTime'`: equivalent to `'h:mm a'` for en_US locale (e.g. 12:05 PM)\n *\n * `format` string can contain literal values. These need to be escaped by surrounding with single quotes (e.g.\n * `\"h 'in the morning'\"`). In order to output a single quote, escape it - i.e., two single quotes in a sequence\n * (e.g. `\"h 'o''clock'\"`).\n *\n * @param {(Date|number|string)} date Date to format either as Date object, milliseconds (string or\n * number) or various ISO 8601 datetime string formats (e.g. yyyy-MM-ddTHH:mm:ss.sssZ and its\n * shorter versions like yyyy-MM-ddTHH:mmZ, yyyy-MM-dd or yyyyMMddTHHmmssZ). If no timezone is\n * specified in the string input, the time is considered to be in the local timezone.\n * @param {string=} format Formatting rules (see Description). If not specified,\n * `mediumDate` is used.\n * @param {string=} timezone Timezone to be used for formatting. It understands UTC/GMT and the\n * continental US time zone abbreviations, but for general use, use a time zone offset, for\n * example, `'+0430'` (4 hours, 30 minutes east of the Greenwich meridian)\n * If not specified, the timezone of the browser will be used.\n * @returns {string} Formatted string or the input if input is not recognized as date/millis.\n *\n * @example\n \n \n {{1288323623006 | date:'medium'}}:\n {{1288323623006 | date:'medium'}}
\n {{1288323623006 | date:'yyyy-MM-dd HH:mm:ss Z'}}:\n {{1288323623006 | date:'yyyy-MM-dd HH:mm:ss Z'}}
\n {{1288323623006 | date:'MM/dd/yyyy @ h:mma'}}:\n {{'1288323623006' | date:'MM/dd/yyyy @ h:mma'}}
\n {{1288323623006 | date:\"MM/dd/yyyy 'at' h:mma\"}}:\n {{'1288323623006' | date:\"MM/dd/yyyy 'at' h:mma\"}}
\n
\n \n it('should format date', function() {\n expect(element(by.binding(\"1288323623006 | date:'medium'\")).getText()).\n toMatch(/Oct 2\\d, 2010 \\d{1,2}:\\d{2}:\\d{2} (AM|PM)/);\n expect(element(by.binding(\"1288323623006 | date:'yyyy-MM-dd HH:mm:ss Z'\")).getText()).\n toMatch(/2010-10-2\\d \\d{2}:\\d{2}:\\d{2} (-|\\+)?\\d{4}/);\n expect(element(by.binding(\"'1288323623006' | date:'MM/dd/yyyy @ h:mma'\")).getText()).\n toMatch(/10\\/2\\d\\/2010 @ \\d{1,2}:\\d{2}(AM|PM)/);\n expect(element(by.binding(\"'1288323623006' | date:\\\"MM/dd/yyyy 'at' h:mma\\\"\")).getText()).\n toMatch(/10\\/2\\d\\/2010 at \\d{1,2}:\\d{2}(AM|PM)/);\n });\n \n
\n */\ndateFilter.$inject = ['$locale'];\nfunction dateFilter($locale) {\n\n\n var R_ISO8601_STR = /^(\\d{4})-?(\\d\\d)-?(\\d\\d)(?:T(\\d\\d)(?::?(\\d\\d)(?::?(\\d\\d)(?:\\.(\\d+))?)?)?(Z|([+-])(\\d\\d):?(\\d\\d))?)?$/;\n // 1 2 3 4 5 6 7 8 9 10 11\n function jsonStringToDate(string) {\n var match;\n if ((match = string.match(R_ISO8601_STR))) {\n var date = new Date(0),\n tzHour = 0,\n tzMin = 0,\n dateSetter = match[8] ? date.setUTCFullYear : date.setFullYear,\n timeSetter = match[8] ? date.setUTCHours : date.setHours;\n\n if (match[9]) {\n tzHour = toInt(match[9] + match[10]);\n tzMin = toInt(match[9] + match[11]);\n }\n dateSetter.call(date, toInt(match[1]), toInt(match[2]) - 1, toInt(match[3]));\n var h = toInt(match[4] || 0) - tzHour;\n var m = toInt(match[5] || 0) - tzMin;\n var s = toInt(match[6] || 0);\n var ms = Math.round(parseFloat('0.' + (match[7] || 0)) * 1000);\n timeSetter.call(date, h, m, s, ms);\n return date;\n }\n return string;\n }\n\n\n return function(date, format, timezone) {\n var text = '',\n parts = [],\n fn, match;\n\n format = format || 'mediumDate';\n format = $locale.DATETIME_FORMATS[format] || format;\n if (isString(date)) {\n date = NUMBER_STRING.test(date) ? toInt(date) : jsonStringToDate(date);\n }\n\n if (isNumber(date)) {\n date = new Date(date);\n }\n\n if (!isDate(date) || !isFinite(date.getTime())) {\n return date;\n }\n\n while (format) {\n match = DATE_FORMATS_SPLIT.exec(format);\n if (match) {\n parts = concat(parts, match, 1);\n format = parts.pop();\n } else {\n parts.push(format);\n format = null;\n }\n }\n\n var dateTimezoneOffset = date.getTimezoneOffset();\n if (timezone) {\n dateTimezoneOffset = timezoneToOffset(timezone, dateTimezoneOffset);\n date = convertTimezoneToLocal(date, timezone, true);\n }\n forEach(parts, function(value) {\n fn = DATE_FORMATS[value];\n text += fn ? fn(date, $locale.DATETIME_FORMATS, dateTimezoneOffset)\n : value === '\\'\\'' ? '\\'' : value.replace(/(^'|'$)/g, '').replace(/''/g, '\\'');\n });\n\n return text;\n };\n}\n\n\n/**\n * @ngdoc filter\n * @name json\n * @kind function\n *\n * @description\n * Allows you to convert a JavaScript object into JSON string.\n *\n * This filter is mostly useful for debugging. When using the double curly {{value}} notation\n * the binding is automatically converted to JSON.\n *\n * @param {*} object Any JavaScript object (including arrays and primitive types) to filter.\n * @param {number=} spacing The number of spaces to use per indentation, defaults to 2.\n * @returns {string} JSON string.\n *\n *\n * @example\n \n \n
{{ {'name':'value'} | json }}
\n
{{ {'name':'value'} | json:4 }}
\n
\n \n it('should jsonify filtered objects', function() {\n expect(element(by.id('default-spacing')).getText()).toMatch(/\\{\\n {2}\"name\": ?\"value\"\\n}/);\n expect(element(by.id('custom-spacing')).getText()).toMatch(/\\{\\n {4}\"name\": ?\"value\"\\n}/);\n });\n \n
\n *\n */\nfunction jsonFilter() {\n return function(object, spacing) {\n if (isUndefined(spacing)) {\n spacing = 2;\n }\n return toJson(object, spacing);\n };\n}\n\n\n/**\n * @ngdoc filter\n * @name lowercase\n * @kind function\n * @description\n * Converts string to lowercase.\n * @see angular.lowercase\n */\nvar lowercaseFilter = valueFn(lowercase);\n\n\n/**\n * @ngdoc filter\n * @name uppercase\n * @kind function\n * @description\n * Converts string to uppercase.\n * @see angular.uppercase\n */\nvar uppercaseFilter = valueFn(uppercase);\n\n/**\n * @ngdoc filter\n * @name limitTo\n * @kind function\n *\n * @description\n * Creates a new array or string containing only a specified number of elements. The elements are\n * taken from either the beginning or the end of the source array, string or number, as specified by\n * the value and sign (positive or negative) of `limit`. Other array-like objects are also supported\n * (e.g. array subclasses, NodeLists, jqLite/jQuery collections etc). If a number is used as input,\n * it is converted to a string.\n *\n * @param {Array|ArrayLike|string|number} input - Array/array-like, string or number to be limited.\n * @param {string|number} limit - The length of the returned array or string. If the `limit` number\n * is positive, `limit` number of items from the beginning of the source array/string are copied.\n * If the number is negative, `limit` number of items from the end of the source array/string\n * are copied. The `limit` will be trimmed if it exceeds `array.length`. If `limit` is undefined,\n * the input will be returned unchanged.\n * @param {(string|number)=} begin - Index at which to begin limitation. As a negative index,\n * `begin` indicates an offset from the end of `input`. Defaults to `0`.\n * @returns {Array|string} A new sub-array or substring of length `limit` or less if the input had\n * less than `limit` elements.\n *\n * @example\n \n \n \n
\n \n

Output numbers: {{ numbers | limitTo:numLimit }}

\n \n

Output letters: {{ letters | limitTo:letterLimit }}

\n \n

Output long number: {{ longNumber | limitTo:longNumberLimit }}

\n
\n
\n \n var numLimitInput = element(by.model('numLimit'));\n var letterLimitInput = element(by.model('letterLimit'));\n var longNumberLimitInput = element(by.model('longNumberLimit'));\n var limitedNumbers = element(by.binding('numbers | limitTo:numLimit'));\n var limitedLetters = element(by.binding('letters | limitTo:letterLimit'));\n var limitedLongNumber = element(by.binding('longNumber | limitTo:longNumberLimit'));\n\n it('should limit the number array to first three items', function() {\n expect(numLimitInput.getAttribute('value')).toBe('3');\n expect(letterLimitInput.getAttribute('value')).toBe('3');\n expect(longNumberLimitInput.getAttribute('value')).toBe('3');\n expect(limitedNumbers.getText()).toEqual('Output numbers: [1,2,3]');\n expect(limitedLetters.getText()).toEqual('Output letters: abc');\n expect(limitedLongNumber.getText()).toEqual('Output long number: 234');\n });\n\n // There is a bug in safari and protractor that doesn't like the minus key\n // it('should update the output when -3 is entered', function() {\n // numLimitInput.clear();\n // numLimitInput.sendKeys('-3');\n // letterLimitInput.clear();\n // letterLimitInput.sendKeys('-3');\n // longNumberLimitInput.clear();\n // longNumberLimitInput.sendKeys('-3');\n // expect(limitedNumbers.getText()).toEqual('Output numbers: [7,8,9]');\n // expect(limitedLetters.getText()).toEqual('Output letters: ghi');\n // expect(limitedLongNumber.getText()).toEqual('Output long number: 342');\n // });\n\n it('should not exceed the maximum size of input array', function() {\n numLimitInput.clear();\n numLimitInput.sendKeys('100');\n letterLimitInput.clear();\n letterLimitInput.sendKeys('100');\n longNumberLimitInput.clear();\n longNumberLimitInput.sendKeys('100');\n expect(limitedNumbers.getText()).toEqual('Output numbers: [1,2,3,4,5,6,7,8,9]');\n expect(limitedLetters.getText()).toEqual('Output letters: abcdefghi');\n expect(limitedLongNumber.getText()).toEqual('Output long number: 2345432342');\n });\n \n
\n*/\nfunction limitToFilter() {\n return function(input, limit, begin) {\n if (Math.abs(Number(limit)) === Infinity) {\n limit = Number(limit);\n } else {\n limit = toInt(limit);\n }\n if (isNumberNaN(limit)) return input;\n\n if (isNumber(input)) input = input.toString();\n if (!isArrayLike(input)) return input;\n\n begin = (!begin || isNaN(begin)) ? 0 : toInt(begin);\n begin = (begin < 0) ? Math.max(0, input.length + begin) : begin;\n\n if (limit >= 0) {\n return sliceFn(input, begin, begin + limit);\n } else {\n if (begin === 0) {\n return sliceFn(input, limit, input.length);\n } else {\n return sliceFn(input, Math.max(0, begin + limit), begin);\n }\n }\n };\n}\n\nfunction sliceFn(input, begin, end) {\n if (isString(input)) return input.slice(begin, end);\n\n return slice.call(input, begin, end);\n}\n\n/**\n * @ngdoc filter\n * @name orderBy\n * @kind function\n *\n * @description\n * Returns an array containing the items from the specified `collection`, ordered by a `comparator`\n * function based on the values computed using the `expression` predicate.\n *\n * For example, `[{id: 'foo'}, {id: 'bar'}] | orderBy:'id'` would result in\n * `[{id: 'bar'}, {id: 'foo'}]`.\n *\n * The `collection` can be an Array or array-like object (e.g. NodeList, jQuery object, TypedArray,\n * String, etc).\n *\n * The `expression` can be a single predicate, or a list of predicates each serving as a tie-breaker\n * for the preceding one. The `expression` is evaluated against each item and the output is used\n * for comparing with other items.\n *\n * You can change the sorting order by setting `reverse` to `true`. By default, items are sorted in\n * ascending order.\n *\n * The comparison is done using the `comparator` function. If none is specified, a default, built-in\n * comparator is used (see below for details - in a nutshell, it compares numbers numerically and\n * strings alphabetically).\n *\n * ### Under the hood\n *\n * Ordering the specified `collection` happens in two phases:\n *\n * 1. All items are passed through the predicate (or predicates), and the returned values are saved\n * along with their type (`string`, `number` etc). For example, an item `{label: 'foo'}`, passed\n * through a predicate that extracts the value of the `label` property, would be transformed to:\n * ```\n * {\n * value: 'foo',\n * type: 'string',\n * index: ...\n * }\n * ```\n * 2. The comparator function is used to sort the items, based on the derived values, types and\n * indices.\n *\n * If you use a custom comparator, it will be called with pairs of objects of the form\n * `{value: ..., type: '...', index: ...}` and is expected to return `0` if the objects are equal\n * (as far as the comparator is concerned), `-1` if the 1st one should be ranked higher than the\n * second, or `1` otherwise.\n *\n * In order to ensure that the sorting will be deterministic across platforms, if none of the\n * specified predicates can distinguish between two items, `orderBy` will automatically introduce a\n * dummy predicate that returns the item's index as `value`.\n * (If you are using a custom comparator, make sure it can handle this predicate as well.)\n *\n * Finally, in an attempt to simplify things, if a predicate returns an object as the extracted\n * value for an item, `orderBy` will try to convert that object to a primitive value, before passing\n * it to the comparator. The following rules govern the conversion:\n *\n * 1. If the object has a `valueOf()` method that returns a primitive, its return value will be\n * used instead.
\n * (If the object has a `valueOf()` method that returns another object, then the returned object\n * will be used in subsequent steps.)\n * 2. If the object has a custom `toString()` method (i.e. not the one inherited from `Object`) that\n * returns a primitive, its return value will be used instead.
\n * (If the object has a `toString()` method that returns another object, then the returned object\n * will be used in subsequent steps.)\n * 3. No conversion; the object itself is used.\n *\n * ### The default comparator\n *\n * The default, built-in comparator should be sufficient for most usecases. In short, it compares\n * numbers numerically, strings alphabetically (and case-insensitively), for objects falls back to\n * using their index in the original collection, and sorts values of different types by type.\n *\n * More specifically, it follows these steps to determine the relative order of items:\n *\n * 1. If the compared values are of different types, compare the types themselves alphabetically.\n * 2. If both values are of type `string`, compare them alphabetically in a case- and\n * locale-insensitive way.\n * 3. If both values are objects, compare their indices instead.\n * 4. Otherwise, return:\n * - `0`, if the values are equal (by strict equality comparison, i.e. using `===`).\n * - `-1`, if the 1st value is \"less than\" the 2nd value (compared using the `<` operator).\n * - `1`, otherwise.\n *\n * **Note:** If you notice numbers not being sorted as expected, make sure they are actually being\n * saved as numbers and not strings.\n * **Note:** For the purpose of sorting, `null` values are treated as the string `'null'` (i.e.\n * `type: 'string'`, `value: 'null'`). This may cause unexpected sort order relative to\n * other values.\n *\n * @param {Array|ArrayLike} collection - The collection (array or array-like object) to sort.\n * @param {(Function|string|Array.)=} expression - A predicate (or list of\n * predicates) to be used by the comparator to determine the order of elements.\n *\n * Can be one of:\n *\n * - `Function`: A getter function. This function will be called with each item as argument and\n * the return value will be used for sorting.\n * - `string`: An Angular expression. This expression will be evaluated against each item and the\n * result will be used for sorting. For example, use `'label'` to sort by a property called\n * `label` or `'label.substring(0, 3)'` to sort by the first 3 characters of the `label`\n * property.
\n * (The result of a constant expression is interpreted as a property name to be used for\n * comparison. For example, use `'\"special name\"'` (note the extra pair of quotes) to sort by a\n * property called `special name`.)
\n * An expression can be optionally prefixed with `+` or `-` to control the sorting direction,\n * ascending or descending. For example, `'+label'` or `'-label'`. If no property is provided,\n * (e.g. `'+'` or `'-'`), the collection element itself is used in comparisons.\n * - `Array`: An array of function and/or string predicates. If a predicate cannot determine the\n * relative order of two items, the next predicate is used as a tie-breaker.\n *\n * **Note:** If the predicate is missing or empty then it defaults to `'+'`.\n *\n * @param {boolean=} reverse - If `true`, reverse the sorting order.\n * @param {(Function)=} comparator - The comparator function used to determine the relative order of\n * value pairs. If omitted, the built-in comparator will be used.\n *\n * @returns {Array} - The sorted array.\n *\n *\n * @example\n * ### Ordering a table with `ngRepeat`\n *\n * The example below demonstrates a simple {@link ngRepeat ngRepeat}, where the data is sorted by\n * age in descending order (expression is set to `'-age'`). The `comparator` is not set, which means\n * it defaults to the built-in comparator.\n *\n \n \n
\n \n \n \n \n \n \n \n \n \n \n \n
NamePhone NumberAge
{{friend.name}}{{friend.phone}}{{friend.age}}
\n
\n
\n \n angular.module('orderByExample1', [])\n .controller('ExampleController', ['$scope', function($scope) {\n $scope.friends = [\n {name: 'John', phone: '555-1212', age: 10},\n {name: 'Mary', phone: '555-9876', age: 19},\n {name: 'Mike', phone: '555-4321', age: 21},\n {name: 'Adam', phone: '555-5678', age: 35},\n {name: 'Julie', phone: '555-8765', age: 29}\n ];\n }]);\n \n \n .friends {\n border-collapse: collapse;\n }\n\n .friends th {\n border-bottom: 1px solid;\n }\n .friends td, .friends th {\n border-left: 1px solid;\n padding: 5px 10px;\n }\n .friends td:first-child, .friends th:first-child {\n border-left: none;\n }\n \n \n // Element locators\n var names = element.all(by.repeater('friends').column('friend.name'));\n\n it('should sort friends by age in reverse order', function() {\n expect(names.get(0).getText()).toBe('Adam');\n expect(names.get(1).getText()).toBe('Julie');\n expect(names.get(2).getText()).toBe('Mike');\n expect(names.get(3).getText()).toBe('Mary');\n expect(names.get(4).getText()).toBe('John');\n });\n \n
\n *
\n *\n * @example\n * ### Changing parameters dynamically\n *\n * All parameters can be changed dynamically. The next example shows how you can make the columns of\n * a table sortable, by binding the `expression` and `reverse` parameters to scope properties.\n *\n \n \n
\n
Sort by = {{propertyName}}; reverse = {{reverse}}
\n
\n \n
\n \n \n \n \n \n \n \n \n \n \n \n
\n \n \n \n \n \n \n \n \n
{{friend.name}}{{friend.phone}}{{friend.age}}
\n
\n
\n \n angular.module('orderByExample2', [])\n .controller('ExampleController', ['$scope', function($scope) {\n var friends = [\n {name: 'John', phone: '555-1212', age: 10},\n {name: 'Mary', phone: '555-9876', age: 19},\n {name: 'Mike', phone: '555-4321', age: 21},\n {name: 'Adam', phone: '555-5678', age: 35},\n {name: 'Julie', phone: '555-8765', age: 29}\n ];\n\n $scope.propertyName = 'age';\n $scope.reverse = true;\n $scope.friends = friends;\n\n $scope.sortBy = function(propertyName) {\n $scope.reverse = ($scope.propertyName === propertyName) ? !$scope.reverse : false;\n $scope.propertyName = propertyName;\n };\n }]);\n \n \n .friends {\n border-collapse: collapse;\n }\n\n .friends th {\n border-bottom: 1px solid;\n }\n .friends td, .friends th {\n border-left: 1px solid;\n padding: 5px 10px;\n }\n .friends td:first-child, .friends th:first-child {\n border-left: none;\n }\n\n .sortorder:after {\n content: '\\25b2'; // BLACK UP-POINTING TRIANGLE\n }\n .sortorder.reverse:after {\n content: '\\25bc'; // BLACK DOWN-POINTING TRIANGLE\n }\n \n \n // Element locators\n var unsortButton = element(by.partialButtonText('unsorted'));\n var nameHeader = element(by.partialButtonText('Name'));\n var phoneHeader = element(by.partialButtonText('Phone'));\n var ageHeader = element(by.partialButtonText('Age'));\n var firstName = element(by.repeater('friends').column('friend.name').row(0));\n var lastName = element(by.repeater('friends').column('friend.name').row(4));\n\n it('should sort friends by some property, when clicking on the column header', function() {\n expect(firstName.getText()).toBe('Adam');\n expect(lastName.getText()).toBe('John');\n\n phoneHeader.click();\n expect(firstName.getText()).toBe('John');\n expect(lastName.getText()).toBe('Mary');\n\n nameHeader.click();\n expect(firstName.getText()).toBe('Adam');\n expect(lastName.getText()).toBe('Mike');\n\n ageHeader.click();\n expect(firstName.getText()).toBe('John');\n expect(lastName.getText()).toBe('Adam');\n });\n\n it('should sort friends in reverse order, when clicking on the same column', function() {\n expect(firstName.getText()).toBe('Adam');\n expect(lastName.getText()).toBe('John');\n\n ageHeader.click();\n expect(firstName.getText()).toBe('John');\n expect(lastName.getText()).toBe('Adam');\n\n ageHeader.click();\n expect(firstName.getText()).toBe('Adam');\n expect(lastName.getText()).toBe('John');\n });\n\n it('should restore the original order, when clicking \"Set to unsorted\"', function() {\n expect(firstName.getText()).toBe('Adam');\n expect(lastName.getText()).toBe('John');\n\n unsortButton.click();\n expect(firstName.getText()).toBe('John');\n expect(lastName.getText()).toBe('Julie');\n });\n \n
\n *
\n *\n * @example\n * ### Using `orderBy` inside a controller\n *\n * It is also possible to call the `orderBy` filter manually, by injecting `orderByFilter`, and\n * calling it with the desired parameters. (Alternatively, you could inject the `$filter` factory\n * and retrieve the `orderBy` filter with `$filter('orderBy')`.)\n *\n \n \n
\n
Sort by = {{propertyName}}; reverse = {{reverse}}
\n
\n \n
\n \n \n \n \n \n \n \n \n \n \n \n
\n \n \n \n \n \n \n \n \n
{{friend.name}}{{friend.phone}}{{friend.age}}
\n
\n
\n \n angular.module('orderByExample3', [])\n .controller('ExampleController', ['$scope', 'orderByFilter', function($scope, orderBy) {\n var friends = [\n {name: 'John', phone: '555-1212', age: 10},\n {name: 'Mary', phone: '555-9876', age: 19},\n {name: 'Mike', phone: '555-4321', age: 21},\n {name: 'Adam', phone: '555-5678', age: 35},\n {name: 'Julie', phone: '555-8765', age: 29}\n ];\n\n $scope.propertyName = 'age';\n $scope.reverse = true;\n $scope.friends = orderBy(friends, $scope.propertyName, $scope.reverse);\n\n $scope.sortBy = function(propertyName) {\n $scope.reverse = (propertyName !== null && $scope.propertyName === propertyName)\n ? !$scope.reverse : false;\n $scope.propertyName = propertyName;\n $scope.friends = orderBy(friends, $scope.propertyName, $scope.reverse);\n };\n }]);\n \n \n .friends {\n border-collapse: collapse;\n }\n\n .friends th {\n border-bottom: 1px solid;\n }\n .friends td, .friends th {\n border-left: 1px solid;\n padding: 5px 10px;\n }\n .friends td:first-child, .friends th:first-child {\n border-left: none;\n }\n\n .sortorder:after {\n content: '\\25b2'; // BLACK UP-POINTING TRIANGLE\n }\n .sortorder.reverse:after {\n content: '\\25bc'; // BLACK DOWN-POINTING TRIANGLE\n }\n \n \n // Element locators\n var unsortButton = element(by.partialButtonText('unsorted'));\n var nameHeader = element(by.partialButtonText('Name'));\n var phoneHeader = element(by.partialButtonText('Phone'));\n var ageHeader = element(by.partialButtonText('Age'));\n var firstName = element(by.repeater('friends').column('friend.name').row(0));\n var lastName = element(by.repeater('friends').column('friend.name').row(4));\n\n it('should sort friends by some property, when clicking on the column header', function() {\n expect(firstName.getText()).toBe('Adam');\n expect(lastName.getText()).toBe('John');\n\n phoneHeader.click();\n expect(firstName.getText()).toBe('John');\n expect(lastName.getText()).toBe('Mary');\n\n nameHeader.click();\n expect(firstName.getText()).toBe('Adam');\n expect(lastName.getText()).toBe('Mike');\n\n ageHeader.click();\n expect(firstName.getText()).toBe('John');\n expect(lastName.getText()).toBe('Adam');\n });\n\n it('should sort friends in reverse order, when clicking on the same column', function() {\n expect(firstName.getText()).toBe('Adam');\n expect(lastName.getText()).toBe('John');\n\n ageHeader.click();\n expect(firstName.getText()).toBe('John');\n expect(lastName.getText()).toBe('Adam');\n\n ageHeader.click();\n expect(firstName.getText()).toBe('Adam');\n expect(lastName.getText()).toBe('John');\n });\n\n it('should restore the original order, when clicking \"Set to unsorted\"', function() {\n expect(firstName.getText()).toBe('Adam');\n expect(lastName.getText()).toBe('John');\n\n unsortButton.click();\n expect(firstName.getText()).toBe('John');\n expect(lastName.getText()).toBe('Julie');\n });\n \n
\n *
\n *\n * @example\n * ### Using a custom comparator\n *\n * If you have very specific requirements about the way items are sorted, you can pass your own\n * comparator function. For example, you might need to compare some strings in a locale-sensitive\n * way. (When specifying a custom comparator, you also need to pass a value for the `reverse`\n * argument - passing `false` retains the default sorting order, i.e. ascending.)\n *\n \n \n
\n
\n

Locale-sensitive Comparator

\n \n \n \n \n \n \n \n \n \n
NameFavorite Letter
{{friend.name}}{{friend.favoriteLetter}}
\n
\n
\n

Default Comparator

\n \n \n \n \n \n \n \n \n \n
NameFavorite Letter
{{friend.name}}{{friend.favoriteLetter}}
\n
\n
\n
\n \n angular.module('orderByExample4', [])\n .controller('ExampleController', ['$scope', function($scope) {\n $scope.friends = [\n {name: 'John', favoriteLetter: 'Ä'},\n {name: 'Mary', favoriteLetter: 'Ü'},\n {name: 'Mike', favoriteLetter: 'Ö'},\n {name: 'Adam', favoriteLetter: 'H'},\n {name: 'Julie', favoriteLetter: 'Z'}\n ];\n\n $scope.localeSensitiveComparator = function(v1, v2) {\n // If we don't get strings, just compare by index\n if (v1.type !== 'string' || v2.type !== 'string') {\n return (v1.index < v2.index) ? -1 : 1;\n }\n\n // Compare strings alphabetically, taking locale into account\n return v1.value.localeCompare(v2.value);\n };\n }]);\n \n \n .friends-container {\n display: inline-block;\n margin: 0 30px;\n }\n\n .friends {\n border-collapse: collapse;\n }\n\n .friends th {\n border-bottom: 1px solid;\n }\n .friends td, .friends th {\n border-left: 1px solid;\n padding: 5px 10px;\n }\n .friends td:first-child, .friends th:first-child {\n border-left: none;\n }\n \n \n // Element locators\n var container = element(by.css('.custom-comparator'));\n var names = container.all(by.repeater('friends').column('friend.name'));\n\n it('should sort friends by favorite letter (in correct alphabetical order)', function() {\n expect(names.get(0).getText()).toBe('John');\n expect(names.get(1).getText()).toBe('Adam');\n expect(names.get(2).getText()).toBe('Mike');\n expect(names.get(3).getText()).toBe('Mary');\n expect(names.get(4).getText()).toBe('Julie');\n });\n \n
\n *\n */\norderByFilter.$inject = ['$parse'];\nfunction orderByFilter($parse) {\n return function(array, sortPredicate, reverseOrder, compareFn) {\n\n if (array == null) return array;\n if (!isArrayLike(array)) {\n throw minErr('orderBy')('notarray', 'Expected array but received: {0}', array);\n }\n\n if (!isArray(sortPredicate)) { sortPredicate = [sortPredicate]; }\n if (sortPredicate.length === 0) { sortPredicate = ['+']; }\n\n var predicates = processPredicates(sortPredicate);\n\n var descending = reverseOrder ? -1 : 1;\n\n // Define the `compare()` function. Use a default comparator if none is specified.\n var compare = isFunction(compareFn) ? compareFn : defaultCompare;\n\n // The next three lines are a version of a Swartzian Transform idiom from Perl\n // (sometimes called the Decorate-Sort-Undecorate idiom)\n // See https://en.wikipedia.org/wiki/Schwartzian_transform\n var compareValues = Array.prototype.map.call(array, getComparisonObject);\n compareValues.sort(doComparison);\n array = compareValues.map(function(item) { return item.value; });\n\n return array;\n\n function getComparisonObject(value, index) {\n // NOTE: We are adding an extra `tieBreaker` value based on the element's index.\n // This will be used to keep the sort stable when none of the input predicates can\n // distinguish between two elements.\n return {\n value: value,\n tieBreaker: {value: index, type: 'number', index: index},\n predicateValues: predicates.map(function(predicate) {\n return getPredicateValue(predicate.get(value), index);\n })\n };\n }\n\n function doComparison(v1, v2) {\n for (var i = 0, ii = predicates.length; i < ii; i++) {\n var result = compare(v1.predicateValues[i], v2.predicateValues[i]);\n if (result) {\n return result * predicates[i].descending * descending;\n }\n }\n\n return compare(v1.tieBreaker, v2.tieBreaker) * descending;\n }\n };\n\n function processPredicates(sortPredicates) {\n return sortPredicates.map(function(predicate) {\n var descending = 1, get = identity;\n\n if (isFunction(predicate)) {\n get = predicate;\n } else if (isString(predicate)) {\n if ((predicate.charAt(0) === '+' || predicate.charAt(0) === '-')) {\n descending = predicate.charAt(0) === '-' ? -1 : 1;\n predicate = predicate.substring(1);\n }\n if (predicate !== '') {\n get = $parse(predicate);\n if (get.constant) {\n var key = get();\n get = function(value) { return value[key]; };\n }\n }\n }\n return {get: get, descending: descending};\n });\n }\n\n function isPrimitive(value) {\n switch (typeof value) {\n case 'number': /* falls through */\n case 'boolean': /* falls through */\n case 'string':\n return true;\n default:\n return false;\n }\n }\n\n function objectValue(value) {\n // If `valueOf` is a valid function use that\n if (isFunction(value.valueOf)) {\n value = value.valueOf();\n if (isPrimitive(value)) return value;\n }\n // If `toString` is a valid function and not the one from `Object.prototype` use that\n if (hasCustomToString(value)) {\n value = value.toString();\n if (isPrimitive(value)) return value;\n }\n\n return value;\n }\n\n function getPredicateValue(value, index) {\n var type = typeof value;\n if (value === null) {\n type = 'string';\n value = 'null';\n } else if (type === 'object') {\n value = objectValue(value);\n }\n return {value: value, type: type, index: index};\n }\n\n function defaultCompare(v1, v2) {\n var result = 0;\n var type1 = v1.type;\n var type2 = v2.type;\n\n if (type1 === type2) {\n var value1 = v1.value;\n var value2 = v2.value;\n\n if (type1 === 'string') {\n // Compare strings case-insensitively\n value1 = value1.toLowerCase();\n value2 = value2.toLowerCase();\n } else if (type1 === 'object') {\n // For basic objects, use the position of the object\n // in the collection instead of the value\n if (isObject(value1)) value1 = v1.index;\n if (isObject(value2)) value2 = v2.index;\n }\n\n if (value1 !== value2) {\n result = value1 < value2 ? -1 : 1;\n }\n } else {\n result = type1 < type2 ? -1 : 1;\n }\n\n return result;\n }\n}\n\nfunction ngDirective(directive) {\n if (isFunction(directive)) {\n directive = {\n link: directive\n };\n }\n directive.restrict = directive.restrict || 'AC';\n return valueFn(directive);\n}\n\n/**\n * @ngdoc directive\n * @name a\n * @restrict E\n *\n * @description\n * Modifies the default behavior of the html a tag so that the default action is prevented when\n * the href attribute is empty.\n *\n * For dynamically creating `href` attributes for a tags, see the {@link ng.ngHref `ngHref`} directive.\n */\nvar htmlAnchorDirective = valueFn({\n restrict: 'E',\n compile: function(element, attr) {\n if (!attr.href && !attr.xlinkHref) {\n return function(scope, element) {\n // If the linked element is not an anchor tag anymore, do nothing\n if (element[0].nodeName.toLowerCase() !== 'a') return;\n\n // SVGAElement does not use the href attribute, but rather the 'xlinkHref' attribute.\n var href = toString.call(element.prop('href')) === '[object SVGAnimatedString]' ?\n 'xlink:href' : 'href';\n element.on('click', function(event) {\n // if we have no href url, then don't navigate anywhere.\n if (!element.attr(href)) {\n event.preventDefault();\n }\n });\n };\n }\n }\n});\n\n/**\n * @ngdoc directive\n * @name ngHref\n * @restrict A\n * @priority 99\n *\n * @description\n * Using Angular markup like `{{hash}}` in an href attribute will\n * make the link go to the wrong URL if the user clicks it before\n * Angular has a chance to replace the `{{hash}}` markup with its\n * value. Until Angular replaces the markup the link will be broken\n * and will most likely return a 404 error. The `ngHref` directive\n * solves this problem.\n *\n * The wrong way to write it:\n * ```html\n * link1\n * ```\n *\n * The correct way to write it:\n * ```html\n * link1\n * ```\n *\n * @element A\n * @param {template} ngHref any string which can contain `{{}}` markup.\n *\n * @example\n * This example shows various combinations of `href`, `ng-href` and `ng-click` attributes\n * in links and their different behaviors:\n \n \n
\n link 1 (link, don't reload)
\n link 2 (link, don't reload)
\n link 3 (link, reload!)
\n anchor (link, don't reload)
\n anchor (no link)
\n link (link, change location)\n
\n \n it('should execute ng-click but not reload when href without value', function() {\n element(by.id('link-1')).click();\n expect(element(by.model('value')).getAttribute('value')).toEqual('1');\n expect(element(by.id('link-1')).getAttribute('href')).toBe('');\n });\n\n it('should execute ng-click but not reload when href empty string', function() {\n element(by.id('link-2')).click();\n expect(element(by.model('value')).getAttribute('value')).toEqual('2');\n expect(element(by.id('link-2')).getAttribute('href')).toBe('');\n });\n\n it('should execute ng-click and change url when ng-href specified', function() {\n expect(element(by.id('link-3')).getAttribute('href')).toMatch(/\\/123$/);\n\n element(by.id('link-3')).click();\n\n // At this point, we navigate away from an Angular page, so we need\n // to use browser.driver to get the base webdriver.\n\n browser.wait(function() {\n return browser.driver.getCurrentUrl().then(function(url) {\n return url.match(/\\/123$/);\n });\n }, 5000, 'page should navigate to /123');\n });\n\n it('should execute ng-click but not reload when href empty string and name specified', function() {\n element(by.id('link-4')).click();\n expect(element(by.model('value')).getAttribute('value')).toEqual('4');\n expect(element(by.id('link-4')).getAttribute('href')).toBe('');\n });\n\n it('should execute ng-click but not reload when no href but name specified', function() {\n element(by.id('link-5')).click();\n expect(element(by.model('value')).getAttribute('value')).toEqual('5');\n expect(element(by.id('link-5')).getAttribute('href')).toBe(null);\n });\n\n it('should only change url when only ng-href', function() {\n element(by.model('value')).clear();\n element(by.model('value')).sendKeys('6');\n expect(element(by.id('link-6')).getAttribute('href')).toMatch(/\\/6$/);\n\n element(by.id('link-6')).click();\n\n // At this point, we navigate away from an Angular page, so we need\n // to use browser.driver to get the base webdriver.\n browser.wait(function() {\n return browser.driver.getCurrentUrl().then(function(url) {\n return url.match(/\\/6$/);\n });\n }, 5000, 'page should navigate to /6');\n });\n \n
\n */\n\n/**\n * @ngdoc directive\n * @name ngSrc\n * @restrict A\n * @priority 99\n *\n * @description\n * Using Angular markup like `{{hash}}` in a `src` attribute doesn't\n * work right: The browser will fetch from the URL with the literal\n * text `{{hash}}` until Angular replaces the expression inside\n * `{{hash}}`. The `ngSrc` directive solves this problem.\n *\n * The buggy way to write it:\n * ```html\n * \"Description\"/\n * ```\n *\n * The correct way to write it:\n * ```html\n * \"Description\"\n * ```\n *\n * @element IMG\n * @param {template} ngSrc any string which can contain `{{}}` markup.\n */\n\n/**\n * @ngdoc directive\n * @name ngSrcset\n * @restrict A\n * @priority 99\n *\n * @description\n * Using Angular markup like `{{hash}}` in a `srcset` attribute doesn't\n * work right: The browser will fetch from the URL with the literal\n * text `{{hash}}` until Angular replaces the expression inside\n * `{{hash}}`. The `ngSrcset` directive solves this problem.\n *\n * The buggy way to write it:\n * ```html\n * \"Description\"/\n * ```\n *\n * The correct way to write it:\n * ```html\n * \"Description\"\n * ```\n *\n * @element IMG\n * @param {template} ngSrcset any string which can contain `{{}}` markup.\n */\n\n/**\n * @ngdoc directive\n * @name ngDisabled\n * @restrict A\n * @priority 100\n *\n * @description\n *\n * This directive sets the `disabled` attribute on the element if the\n * {@link guide/expression expression} inside `ngDisabled` evaluates to truthy.\n *\n * A special directive is necessary because we cannot use interpolation inside the `disabled`\n * attribute. See the {@link guide/interpolation interpolation guide} for more info.\n *\n * @example\n \n \n
\n \n
\n \n it('should toggle button', function() {\n expect(element(by.css('button')).getAttribute('disabled')).toBeFalsy();\n element(by.model('checked')).click();\n expect(element(by.css('button')).getAttribute('disabled')).toBeTruthy();\n });\n \n
\n *\n * @element INPUT\n * @param {expression} ngDisabled If the {@link guide/expression expression} is truthy,\n * then the `disabled` attribute will be set on the element\n */\n\n\n/**\n * @ngdoc directive\n * @name ngChecked\n * @restrict A\n * @priority 100\n *\n * @description\n * Sets the `checked` attribute on the element, if the expression inside `ngChecked` is truthy.\n *\n * Note that this directive should not be used together with {@link ngModel `ngModel`},\n * as this can lead to unexpected behavior.\n *\n * A special directive is necessary because we cannot use interpolation inside the `checked`\n * attribute. See the {@link guide/interpolation interpolation guide} for more info.\n *\n * @example\n \n \n
\n \n
\n \n it('should check both checkBoxes', function() {\n expect(element(by.id('checkSlave')).getAttribute('checked')).toBeFalsy();\n element(by.model('master')).click();\n expect(element(by.id('checkSlave')).getAttribute('checked')).toBeTruthy();\n });\n \n
\n *\n * @element INPUT\n * @param {expression} ngChecked If the {@link guide/expression expression} is truthy,\n * then the `checked` attribute will be set on the element\n */\n\n\n/**\n * @ngdoc directive\n * @name ngReadonly\n * @restrict A\n * @priority 100\n *\n * @description\n *\n * Sets the `readonly` attribute on the element, if the expression inside `ngReadonly` is truthy.\n * Note that `readonly` applies only to `input` elements with specific types. [See the input docs on\n * MDN](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/input#attr-readonly) for more information.\n *\n * A special directive is necessary because we cannot use interpolation inside the `readonly`\n * attribute. See the {@link guide/interpolation interpolation guide} for more info.\n *\n * @example\n \n \n
\n \n
\n \n it('should toggle readonly attr', function() {\n expect(element(by.css('[type=\"text\"]')).getAttribute('readonly')).toBeFalsy();\n element(by.model('checked')).click();\n expect(element(by.css('[type=\"text\"]')).getAttribute('readonly')).toBeTruthy();\n });\n \n
\n *\n * @element INPUT\n * @param {expression} ngReadonly If the {@link guide/expression expression} is truthy,\n * then special attribute \"readonly\" will be set on the element\n */\n\n\n/**\n * @ngdoc directive\n * @name ngSelected\n * @restrict A\n * @priority 100\n *\n * @description\n *\n * Sets the `selected` attribute on the element, if the expression inside `ngSelected` is truthy.\n *\n * A special directive is necessary because we cannot use interpolation inside the `selected`\n * attribute. See the {@link guide/interpolation interpolation guide} for more info.\n *\n *
\n * **Note:** `ngSelected` does not interact with the `select` and `ngModel` directives, it only\n * sets the `selected` attribute on the element. If you are using `ngModel` on the select, you\n * should not use `ngSelected` on the options, as `ngModel` will set the select value and\n * selected options.\n *
\n *\n * @example\n \n \n
\n \n
\n \n it('should select Greetings!', function() {\n expect(element(by.id('greet')).getAttribute('selected')).toBeFalsy();\n element(by.model('selected')).click();\n expect(element(by.id('greet')).getAttribute('selected')).toBeTruthy();\n });\n \n
\n *\n * @element OPTION\n * @param {expression} ngSelected If the {@link guide/expression expression} is truthy,\n * then special attribute \"selected\" will be set on the element\n */\n\n/**\n * @ngdoc directive\n * @name ngOpen\n * @restrict A\n * @priority 100\n *\n * @description\n *\n * Sets the `open` attribute on the element, if the expression inside `ngOpen` is truthy.\n *\n * A special directive is necessary because we cannot use interpolation inside the `open`\n * attribute. See the {@link guide/interpolation interpolation guide} for more info.\n *\n * ## A note about browser compatibility\n *\n * Edge, Firefox, and Internet Explorer do not support the `details` element, it is\n * recommended to use {@link ng.ngShow} and {@link ng.ngHide} instead.\n *\n * @example\n \n \n
\n
\n Show/Hide me\n
\n
\n \n it('should toggle open', function() {\n expect(element(by.id('details')).getAttribute('open')).toBeFalsy();\n element(by.model('open')).click();\n expect(element(by.id('details')).getAttribute('open')).toBeTruthy();\n });\n \n
\n *\n * @element DETAILS\n * @param {expression} ngOpen If the {@link guide/expression expression} is truthy,\n * then special attribute \"open\" will be set on the element\n */\n\nvar ngAttributeAliasDirectives = {};\n\n// boolean attrs are evaluated\nforEach(BOOLEAN_ATTR, function(propName, attrName) {\n // binding to multiple is not supported\n if (propName === 'multiple') return;\n\n function defaultLinkFn(scope, element, attr) {\n scope.$watch(attr[normalized], function ngBooleanAttrWatchAction(value) {\n attr.$set(attrName, !!value);\n });\n }\n\n var normalized = directiveNormalize('ng-' + attrName);\n var linkFn = defaultLinkFn;\n\n if (propName === 'checked') {\n linkFn = function(scope, element, attr) {\n // ensuring ngChecked doesn't interfere with ngModel when both are set on the same input\n if (attr.ngModel !== attr[normalized]) {\n defaultLinkFn(scope, element, attr);\n }\n };\n }\n\n ngAttributeAliasDirectives[normalized] = function() {\n return {\n restrict: 'A',\n priority: 100,\n link: linkFn\n };\n };\n});\n\n// aliased input attrs are evaluated\nforEach(ALIASED_ATTR, function(htmlAttr, ngAttr) {\n ngAttributeAliasDirectives[ngAttr] = function() {\n return {\n priority: 100,\n link: function(scope, element, attr) {\n //special case ngPattern when a literal regular expression value\n //is used as the expression (this way we don't have to watch anything).\n if (ngAttr === 'ngPattern' && attr.ngPattern.charAt(0) === '/') {\n var match = attr.ngPattern.match(REGEX_STRING_REGEXP);\n if (match) {\n attr.$set('ngPattern', new RegExp(match[1], match[2]));\n return;\n }\n }\n\n scope.$watch(attr[ngAttr], function ngAttrAliasWatchAction(value) {\n attr.$set(ngAttr, value);\n });\n }\n };\n };\n});\n\n// ng-src, ng-srcset, ng-href are interpolated\nforEach(['src', 'srcset', 'href'], function(attrName) {\n var normalized = directiveNormalize('ng-' + attrName);\n ngAttributeAliasDirectives[normalized] = function() {\n return {\n priority: 99, // it needs to run after the attributes are interpolated\n link: function(scope, element, attr) {\n var propName = attrName,\n name = attrName;\n\n if (attrName === 'href' &&\n toString.call(element.prop('href')) === '[object SVGAnimatedString]') {\n name = 'xlinkHref';\n attr.$attr[name] = 'xlink:href';\n propName = null;\n }\n\n attr.$observe(normalized, function(value) {\n if (!value) {\n if (attrName === 'href') {\n attr.$set(name, null);\n }\n return;\n }\n\n attr.$set(name, value);\n\n // Support: IE 9-11 only\n // On IE, if \"ng:src\" directive declaration is used and \"src\" attribute doesn't exist\n // then calling element.setAttribute('src', 'foo') doesn't do anything, so we need\n // to set the property as well to achieve the desired effect.\n // We use attr[attrName] value since $set can sanitize the url.\n if (msie && propName) element.prop(propName, attr[name]);\n });\n }\n };\n };\n});\n\n/* global -nullFormCtrl, -PENDING_CLASS, -SUBMITTED_CLASS\n */\nvar nullFormCtrl = {\n $addControl: noop,\n $$renameControl: nullFormRenameControl,\n $removeControl: noop,\n $setValidity: noop,\n $setDirty: noop,\n $setPristine: noop,\n $setSubmitted: noop\n},\nPENDING_CLASS = 'ng-pending',\nSUBMITTED_CLASS = 'ng-submitted';\n\nfunction nullFormRenameControl(control, name) {\n control.$name = name;\n}\n\n/**\n * @ngdoc type\n * @name form.FormController\n *\n * @property {boolean} $pristine True if user has not interacted with the form yet.\n * @property {boolean} $dirty True if user has already interacted with the form.\n * @property {boolean} $valid True if all of the containing forms and controls are valid.\n * @property {boolean} $invalid True if at least one containing control or form is invalid.\n * @property {boolean} $pending True if at least one containing control or form is pending.\n * @property {boolean} $submitted True if user has submitted the form even if its invalid.\n *\n * @property {Object} $error Is an object hash, containing references to controls or\n * forms with failing validators, where:\n *\n * - keys are validation tokens (error names),\n * - values are arrays of controls or forms that have a failing validator for given error name.\n *\n * Built-in validation tokens:\n *\n * - `email`\n * - `max`\n * - `maxlength`\n * - `min`\n * - `minlength`\n * - `number`\n * - `pattern`\n * - `required`\n * - `url`\n * - `date`\n * - `datetimelocal`\n * - `time`\n * - `week`\n * - `month`\n *\n * @description\n * `FormController` keeps track of all its controls and nested forms as well as the state of them,\n * such as being valid/invalid or dirty/pristine.\n *\n * Each {@link ng.directive:form form} directive creates an instance\n * of `FormController`.\n *\n */\n//asks for $scope to fool the BC controller module\nFormController.$inject = ['$element', '$attrs', '$scope', '$animate', '$interpolate'];\nfunction FormController($element, $attrs, $scope, $animate, $interpolate) {\n this.$$controls = [];\n\n // init state\n this.$error = {};\n this.$$success = {};\n this.$pending = undefined;\n this.$name = $interpolate($attrs.name || $attrs.ngForm || '')($scope);\n this.$dirty = false;\n this.$pristine = true;\n this.$valid = true;\n this.$invalid = false;\n this.$submitted = false;\n this.$$parentForm = nullFormCtrl;\n\n this.$$element = $element;\n this.$$animate = $animate;\n\n setupValidity(this);\n}\n\nFormController.prototype = {\n /**\n * @ngdoc method\n * @name form.FormController#$rollbackViewValue\n *\n * @description\n * Rollback all form controls pending updates to the `$modelValue`.\n *\n * Updates may be pending by a debounced event or because the input is waiting for a some future\n * event defined in `ng-model-options`. This method is typically needed by the reset button of\n * a form that uses `ng-model-options` to pend updates.\n */\n $rollbackViewValue: function() {\n forEach(this.$$controls, function(control) {\n control.$rollbackViewValue();\n });\n },\n\n /**\n * @ngdoc method\n * @name form.FormController#$commitViewValue\n *\n * @description\n * Commit all form controls pending updates to the `$modelValue`.\n *\n * Updates may be pending by a debounced event or because the input is waiting for a some future\n * event defined in `ng-model-options`. This method is rarely needed as `NgModelController`\n * usually handles calling this in response to input events.\n */\n $commitViewValue: function() {\n forEach(this.$$controls, function(control) {\n control.$commitViewValue();\n });\n },\n\n /**\n * @ngdoc method\n * @name form.FormController#$addControl\n * @param {object} control control object, either a {@link form.FormController} or an\n * {@link ngModel.NgModelController}\n *\n * @description\n * Register a control with the form. Input elements using ngModelController do this automatically\n * when they are linked.\n *\n * Note that the current state of the control will not be reflected on the new parent form. This\n * is not an issue with normal use, as freshly compiled and linked controls are in a `$pristine`\n * state.\n *\n * However, if the method is used programmatically, for example by adding dynamically created controls,\n * or controls that have been previously removed without destroying their corresponding DOM element,\n * it's the developers responsibility to make sure the current state propagates to the parent form.\n *\n * For example, if an input control is added that is already `$dirty` and has `$error` properties,\n * calling `$setDirty()` and `$validate()` afterwards will propagate the state to the parent form.\n */\n $addControl: function(control) {\n // Breaking change - before, inputs whose name was \"hasOwnProperty\" were quietly ignored\n // and not added to the scope. Now we throw an error.\n assertNotHasOwnProperty(control.$name, 'input');\n this.$$controls.push(control);\n\n if (control.$name) {\n this[control.$name] = control;\n }\n\n control.$$parentForm = this;\n },\n\n // Private API: rename a form control\n $$renameControl: function(control, newName) {\n var oldName = control.$name;\n\n if (this[oldName] === control) {\n delete this[oldName];\n }\n this[newName] = control;\n control.$name = newName;\n },\n\n /**\n * @ngdoc method\n * @name form.FormController#$removeControl\n * @param {object} control control object, either a {@link form.FormController} or an\n * {@link ngModel.NgModelController}\n *\n * @description\n * Deregister a control from the form.\n *\n * Input elements using ngModelController do this automatically when they are destroyed.\n *\n * Note that only the removed control's validation state (`$errors`etc.) will be removed from the\n * form. `$dirty`, `$submitted` states will not be changed, because the expected behavior can be\n * different from case to case. For example, removing the only `$dirty` control from a form may or\n * may not mean that the form is still `$dirty`.\n */\n $removeControl: function(control) {\n if (control.$name && this[control.$name] === control) {\n delete this[control.$name];\n }\n forEach(this.$pending, function(value, name) {\n // eslint-disable-next-line no-invalid-this\n this.$setValidity(name, null, control);\n }, this);\n forEach(this.$error, function(value, name) {\n // eslint-disable-next-line no-invalid-this\n this.$setValidity(name, null, control);\n }, this);\n forEach(this.$$success, function(value, name) {\n // eslint-disable-next-line no-invalid-this\n this.$setValidity(name, null, control);\n }, this);\n\n arrayRemove(this.$$controls, control);\n control.$$parentForm = nullFormCtrl;\n },\n\n /**\n * @ngdoc method\n * @name form.FormController#$setDirty\n *\n * @description\n * Sets the form to a dirty state.\n *\n * This method can be called to add the 'ng-dirty' class and set the form to a dirty\n * state (ng-dirty class). This method will also propagate to parent forms.\n */\n $setDirty: function() {\n this.$$animate.removeClass(this.$$element, PRISTINE_CLASS);\n this.$$animate.addClass(this.$$element, DIRTY_CLASS);\n this.$dirty = true;\n this.$pristine = false;\n this.$$parentForm.$setDirty();\n },\n\n /**\n * @ngdoc method\n * @name form.FormController#$setPristine\n *\n * @description\n * Sets the form to its pristine state.\n *\n * This method sets the form's `$pristine` state to true, the `$dirty` state to false, removes\n * the `ng-dirty` class and adds the `ng-pristine` class. Additionally, it sets the `$submitted`\n * state to false.\n *\n * This method will also propagate to all the controls contained in this form.\n *\n * Setting a form back to a pristine state is often useful when we want to 'reuse' a form after\n * saving or resetting it.\n */\n $setPristine: function() {\n this.$$animate.setClass(this.$$element, PRISTINE_CLASS, DIRTY_CLASS + ' ' + SUBMITTED_CLASS);\n this.$dirty = false;\n this.$pristine = true;\n this.$submitted = false;\n forEach(this.$$controls, function(control) {\n control.$setPristine();\n });\n },\n\n /**\n * @ngdoc method\n * @name form.FormController#$setUntouched\n *\n * @description\n * Sets the form to its untouched state.\n *\n * This method can be called to remove the 'ng-touched' class and set the form controls to their\n * untouched state (ng-untouched class).\n *\n * Setting a form controls back to their untouched state is often useful when setting the form\n * back to its pristine state.\n */\n $setUntouched: function() {\n forEach(this.$$controls, function(control) {\n control.$setUntouched();\n });\n },\n\n /**\n * @ngdoc method\n * @name form.FormController#$setSubmitted\n *\n * @description\n * Sets the form to its submitted state.\n */\n $setSubmitted: function() {\n this.$$animate.addClass(this.$$element, SUBMITTED_CLASS);\n this.$submitted = true;\n this.$$parentForm.$setSubmitted();\n }\n};\n\n/**\n * @ngdoc method\n * @name form.FormController#$setValidity\n *\n * @description\n * Sets the validity of a form control.\n *\n * This method will also propagate to parent forms.\n */\naddSetValidityMethod({\n clazz: FormController,\n set: function(object, property, controller) {\n var list = object[property];\n if (!list) {\n object[property] = [controller];\n } else {\n var index = list.indexOf(controller);\n if (index === -1) {\n list.push(controller);\n }\n }\n },\n unset: function(object, property, controller) {\n var list = object[property];\n if (!list) {\n return;\n }\n arrayRemove(list, controller);\n if (list.length === 0) {\n delete object[property];\n }\n }\n});\n\n/**\n * @ngdoc directive\n * @name ngForm\n * @restrict EAC\n *\n * @description\n * Nestable alias of {@link ng.directive:form `form`} directive. HTML\n * does not allow nesting of form elements. It is useful to nest forms, for example if the validity of a\n * sub-group of controls needs to be determined.\n *\n * Note: the purpose of `ngForm` is to group controls,\n * but not to be a replacement for the `
` tag with all of its capabilities\n * (e.g. posting to the server, ...).\n *\n * @param {string=} ngForm|name Name of the form. If specified, the form controller will be published into\n * related scope, under this name.\n *\n */\n\n /**\n * @ngdoc directive\n * @name form\n * @restrict E\n *\n * @description\n * Directive that instantiates\n * {@link form.FormController FormController}.\n *\n * If the `name` attribute is specified, the form controller is published onto the current scope under\n * this name.\n *\n * # Alias: {@link ng.directive:ngForm `ngForm`}\n *\n * In Angular, forms can be nested. This means that the outer form is valid when all of the child\n * forms are valid as well. However, browsers do not allow nesting of `` elements, so\n * Angular provides the {@link ng.directive:ngForm `ngForm`} directive, which behaves identically to\n * `form` but can be nested. Nested forms can be useful, for example, if the validity of a sub-group\n * of controls needs to be determined.\n *\n * # CSS classes\n * - `ng-valid` is set if the form is valid.\n * - `ng-invalid` is set if the form is invalid.\n * - `ng-pending` is set if the form is pending.\n * - `ng-pristine` is set if the form is pristine.\n * - `ng-dirty` is set if the form is dirty.\n * - `ng-submitted` is set if the form was submitted.\n *\n * Keep in mind that ngAnimate can detect each of these classes when added and removed.\n *\n *\n * # Submitting a form and preventing the default action\n *\n * Since the role of forms in client-side Angular applications is different than in classical\n * roundtrip apps, it is desirable for the browser not to translate the form submission into a full\n * page reload that sends the data to the server. Instead some javascript logic should be triggered\n * to handle the form submission in an application-specific way.\n *\n * For this reason, Angular prevents the default action (form submission to the server) unless the\n * `` element has an `action` attribute specified.\n *\n * You can use one of the following two ways to specify what javascript method should be called when\n * a form is submitted:\n *\n * - {@link ng.directive:ngSubmit ngSubmit} directive on the form element\n * - {@link ng.directive:ngClick ngClick} directive on the first\n * button or input field of type submit (input[type=submit])\n *\n * To prevent double execution of the handler, use only one of the {@link ng.directive:ngSubmit ngSubmit}\n * or {@link ng.directive:ngClick ngClick} directives.\n * This is because of the following form submission rules in the HTML specification:\n *\n * - If a form has only one input field then hitting enter in this field triggers form submit\n * (`ngSubmit`)\n * - if a form has 2+ input fields and no buttons or input[type=submit] then hitting enter\n * doesn't trigger submit\n * - if a form has one or more input fields and one or more buttons or input[type=submit] then\n * hitting enter in any of the input fields will trigger the click handler on the *first* button or\n * input[type=submit] (`ngClick`) *and* a submit handler on the enclosing form (`ngSubmit`)\n *\n * Any pending `ngModelOptions` changes will take place immediately when an enclosing form is\n * submitted. Note that `ngClick` events will occur before the model is updated. Use `ngSubmit`\n * to have access to the updated model.\n *\n * ## Animation Hooks\n *\n * Animations in ngForm are triggered when any of the associated CSS classes are added and removed.\n * These classes are: `.ng-pristine`, `.ng-dirty`, `.ng-invalid` and `.ng-valid` as well as any\n * other validations that are performed within the form. Animations in ngForm are similar to how\n * they work in ngClass and animations can be hooked into using CSS transitions, keyframes as well\n * as JS animations.\n *\n * The following example shows a simple way to utilize CSS transitions to style a form element\n * that has been rendered as invalid after it has been validated:\n *\n *
\n * //be sure to include ngAnimate as a module to hook into more\n * //advanced animations\n * .my-form {\n *   transition:0.5s linear all;\n *   background: white;\n * }\n * .my-form.ng-invalid {\n *   background: red;\n *   color:white;\n * }\n * 
\n *\n * @example\n \n \n \n \n \n userType: \n Required!
\n userType = {{userType}}
\n myForm.input.$valid = {{myForm.input.$valid}}
\n myForm.input.$error = {{myForm.input.$error}}
\n myForm.$valid = {{myForm.$valid}}
\n myForm.$error.required = {{!!myForm.$error.required}}
\n \n
\n \n it('should initialize to model', function() {\n var userType = element(by.binding('userType'));\n var valid = element(by.binding('myForm.input.$valid'));\n\n expect(userType.getText()).toContain('guest');\n expect(valid.getText()).toContain('true');\n });\n\n it('should be invalid if empty', function() {\n var userType = element(by.binding('userType'));\n var valid = element(by.binding('myForm.input.$valid'));\n var userInput = element(by.model('userType'));\n\n userInput.clear();\n userInput.sendKeys('');\n\n expect(userType.getText()).toEqual('userType =');\n expect(valid.getText()).toContain('false');\n });\n \n
\n *\n * @param {string=} name Name of the form. If specified, the form controller will be published into\n * related scope, under this name.\n */\nvar formDirectiveFactory = function(isNgForm) {\n return ['$timeout', '$parse', function($timeout, $parse) {\n var formDirective = {\n name: 'form',\n restrict: isNgForm ? 'EAC' : 'E',\n require: ['form', '^^?form'], //first is the form's own ctrl, second is an optional parent form\n controller: FormController,\n compile: function ngFormCompile(formElement, attr) {\n // Setup initial state of the control\n formElement.addClass(PRISTINE_CLASS).addClass(VALID_CLASS);\n\n var nameAttr = attr.name ? 'name' : (isNgForm && attr.ngForm ? 'ngForm' : false);\n\n return {\n pre: function ngFormPreLink(scope, formElement, attr, ctrls) {\n var controller = ctrls[0];\n\n // if `action` attr is not present on the form, prevent the default action (submission)\n if (!('action' in attr)) {\n // we can't use jq events because if a form is destroyed during submission the default\n // action is not prevented. see #1238\n //\n // IE 9 is not affected because it doesn't fire a submit event and try to do a full\n // page reload if the form was destroyed by submission of the form via a click handler\n // on a button in the form. Looks like an IE9 specific bug.\n var handleFormSubmission = function(event) {\n scope.$apply(function() {\n controller.$commitViewValue();\n controller.$setSubmitted();\n });\n\n event.preventDefault();\n };\n\n formElement[0].addEventListener('submit', handleFormSubmission);\n\n // unregister the preventDefault listener so that we don't not leak memory but in a\n // way that will achieve the prevention of the default action.\n formElement.on('$destroy', function() {\n $timeout(function() {\n formElement[0].removeEventListener('submit', handleFormSubmission);\n }, 0, false);\n });\n }\n\n var parentFormCtrl = ctrls[1] || controller.$$parentForm;\n parentFormCtrl.$addControl(controller);\n\n var setter = nameAttr ? getSetter(controller.$name) : noop;\n\n if (nameAttr) {\n setter(scope, controller);\n attr.$observe(nameAttr, function(newValue) {\n if (controller.$name === newValue) return;\n setter(scope, undefined);\n controller.$$parentForm.$$renameControl(controller, newValue);\n setter = getSetter(controller.$name);\n setter(scope, controller);\n });\n }\n formElement.on('$destroy', function() {\n controller.$$parentForm.$removeControl(controller);\n setter(scope, undefined);\n extend(controller, nullFormCtrl); //stop propagating child destruction handlers upwards\n });\n }\n };\n }\n };\n\n return formDirective;\n\n function getSetter(expression) {\n if (expression === '') {\n //create an assignable expression, so forms with an empty name can be renamed later\n return $parse('this[\"\"]').assign;\n }\n return $parse(expression).assign || noop;\n }\n }];\n};\n\nvar formDirective = formDirectiveFactory();\nvar ngFormDirective = formDirectiveFactory(true);\n\n\n\n// helper methods\nfunction setupValidity(instance) {\n instance.$$classCache = {};\n instance.$$classCache[INVALID_CLASS] = !(instance.$$classCache[VALID_CLASS] = instance.$$element.hasClass(VALID_CLASS));\n}\nfunction addSetValidityMethod(context) {\n var clazz = context.clazz,\n set = context.set,\n unset = context.unset;\n\n clazz.prototype.$setValidity = function(validationErrorKey, state, controller) {\n if (isUndefined(state)) {\n createAndSet(this, '$pending', validationErrorKey, controller);\n } else {\n unsetAndCleanup(this, '$pending', validationErrorKey, controller);\n }\n if (!isBoolean(state)) {\n unset(this.$error, validationErrorKey, controller);\n unset(this.$$success, validationErrorKey, controller);\n } else {\n if (state) {\n unset(this.$error, validationErrorKey, controller);\n set(this.$$success, validationErrorKey, controller);\n } else {\n set(this.$error, validationErrorKey, controller);\n unset(this.$$success, validationErrorKey, controller);\n }\n }\n if (this.$pending) {\n cachedToggleClass(this, PENDING_CLASS, true);\n this.$valid = this.$invalid = undefined;\n toggleValidationCss(this, '', null);\n } else {\n cachedToggleClass(this, PENDING_CLASS, false);\n this.$valid = isObjectEmpty(this.$error);\n this.$invalid = !this.$valid;\n toggleValidationCss(this, '', this.$valid);\n }\n\n // re-read the state as the set/unset methods could have\n // combined state in this.$error[validationError] (used for forms),\n // where setting/unsetting only increments/decrements the value,\n // and does not replace it.\n var combinedState;\n if (this.$pending && this.$pending[validationErrorKey]) {\n combinedState = undefined;\n } else if (this.$error[validationErrorKey]) {\n combinedState = false;\n } else if (this.$$success[validationErrorKey]) {\n combinedState = true;\n } else {\n combinedState = null;\n }\n\n toggleValidationCss(this, validationErrorKey, combinedState);\n this.$$parentForm.$setValidity(validationErrorKey, combinedState, this);\n };\n\n function createAndSet(ctrl, name, value, controller) {\n if (!ctrl[name]) {\n ctrl[name] = {};\n }\n set(ctrl[name], value, controller);\n }\n\n function unsetAndCleanup(ctrl, name, value, controller) {\n if (ctrl[name]) {\n unset(ctrl[name], value, controller);\n }\n if (isObjectEmpty(ctrl[name])) {\n ctrl[name] = undefined;\n }\n }\n\n function cachedToggleClass(ctrl, className, switchValue) {\n if (switchValue && !ctrl.$$classCache[className]) {\n ctrl.$$animate.addClass(ctrl.$$element, className);\n ctrl.$$classCache[className] = true;\n } else if (!switchValue && ctrl.$$classCache[className]) {\n ctrl.$$animate.removeClass(ctrl.$$element, className);\n ctrl.$$classCache[className] = false;\n }\n }\n\n function toggleValidationCss(ctrl, validationErrorKey, isValid) {\n validationErrorKey = validationErrorKey ? '-' + snake_case(validationErrorKey, '-') : '';\n\n cachedToggleClass(ctrl, VALID_CLASS + validationErrorKey, isValid === true);\n cachedToggleClass(ctrl, INVALID_CLASS + validationErrorKey, isValid === false);\n }\n}\n\nfunction isObjectEmpty(obj) {\n if (obj) {\n for (var prop in obj) {\n if (obj.hasOwnProperty(prop)) {\n return false;\n }\n }\n }\n return true;\n}\n\n/* global\n VALID_CLASS: false,\n INVALID_CLASS: false,\n PRISTINE_CLASS: false,\n DIRTY_CLASS: false,\n ngModelMinErr: false\n*/\n\n// Regex code was initially obtained from SO prior to modification: https://stackoverflow.com/questions/3143070/javascript-regex-iso-datetime#answer-3143231\nvar ISO_DATE_REGEXP = /^\\d{4,}-[01]\\d-[0-3]\\dT[0-2]\\d:[0-5]\\d:[0-5]\\d\\.\\d+(?:[+-][0-2]\\d:[0-5]\\d|Z)$/;\n// See valid URLs in RFC3987 (http://tools.ietf.org/html/rfc3987)\n// Note: We are being more lenient, because browsers are too.\n// 1. Scheme\n// 2. Slashes\n// 3. Username\n// 4. Password\n// 5. Hostname\n// 6. Port\n// 7. Path\n// 8. Query\n// 9. Fragment\n// 1111111111111111 222 333333 44444 55555555555555555555555 666 77777777 8888888 999\nvar URL_REGEXP = /^[a-z][a-z\\d.+-]*:\\/*(?:[^:@]+(?::[^@]+)?@)?(?:[^\\s:/?#]+|\\[[a-f\\d:]+])(?::\\d+)?(?:\\/[^?#]*)?(?:\\?[^#]*)?(?:#.*)?$/i;\n// eslint-disable-next-line max-len\nvar EMAIL_REGEXP = /^(?=.{1,254}$)(?=.{1,64}@)[-!#$%&'*+/0-9=?A-Z^_`a-z{|}~]+(\\.[-!#$%&'*+/0-9=?A-Z^_`a-z{|}~]+)*@[A-Za-z0-9]([A-Za-z0-9-]{0,61}[A-Za-z0-9])?(\\.[A-Za-z0-9]([A-Za-z0-9-]{0,61}[A-Za-z0-9])?)*$/;\nvar NUMBER_REGEXP = /^\\s*(-|\\+)?(\\d+|(\\d*(\\.\\d*)))([eE][+-]?\\d+)?\\s*$/;\nvar DATE_REGEXP = /^(\\d{4,})-(\\d{2})-(\\d{2})$/;\nvar DATETIMELOCAL_REGEXP = /^(\\d{4,})-(\\d\\d)-(\\d\\d)T(\\d\\d):(\\d\\d)(?::(\\d\\d)(\\.\\d{1,3})?)?$/;\nvar WEEK_REGEXP = /^(\\d{4,})-W(\\d\\d)$/;\nvar MONTH_REGEXP = /^(\\d{4,})-(\\d\\d)$/;\nvar TIME_REGEXP = /^(\\d\\d):(\\d\\d)(?::(\\d\\d)(\\.\\d{1,3})?)?$/;\n\nvar PARTIAL_VALIDATION_EVENTS = 'keydown wheel mousedown';\nvar PARTIAL_VALIDATION_TYPES = createMap();\nforEach('date,datetime-local,month,time,week'.split(','), function(type) {\n PARTIAL_VALIDATION_TYPES[type] = true;\n});\n\nvar inputType = {\n\n /**\n * @ngdoc input\n * @name input[text]\n *\n * @description\n * Standard HTML text input with angular data binding, inherited by most of the `input` elements.\n *\n *\n * @param {string} ngModel Assignable angular expression to data-bind to.\n * @param {string=} name Property name of the form under which the control is published.\n * @param {string=} required Adds `required` validation error key if the value is not entered.\n * @param {string=} ngRequired Adds `required` attribute and `required` validation constraint to\n * the element when the ngRequired expression evaluates to true. Use `ngRequired` instead of\n * `required` when you want to data-bind to the `required` attribute.\n * @param {number=} ngMinlength Sets `minlength` validation error key if the value is shorter than\n * minlength.\n * @param {number=} ngMaxlength Sets `maxlength` validation error key if the value is longer than\n * maxlength. Setting the attribute to a negative or non-numeric value, allows view values of\n * any length.\n * @param {string=} pattern Similar to `ngPattern` except that the attribute value is the actual string\n * that contains the regular expression body that will be converted to a regular expression\n * as in the ngPattern directive.\n * @param {string=} ngPattern Sets `pattern` validation error key if the ngModel {@link ngModel.NgModelController#$viewValue $viewValue}\n * does not match a RegExp found by evaluating the Angular expression given in the attribute value.\n * If the expression evaluates to a RegExp object, then this is used directly.\n * If the expression evaluates to a string, then it will be converted to a RegExp\n * after wrapping it in `^` and `$` characters. For instance, `\"abc\"` will be converted to\n * `new RegExp('^abc$')`.
\n * **Note:** Avoid using the `g` flag on the RegExp, as it will cause each successive search to\n * start at the index of the last search's match, thus not taking the whole input value into\n * account.\n * @param {string=} ngChange Angular expression to be executed when input changes due to user\n * interaction with the input element.\n * @param {boolean=} [ngTrim=true] If set to false Angular will not automatically trim the input.\n * This parameter is ignored for input[type=password] controls, which will never trim the\n * input.\n *\n * @example\n \n \n \n
\n \n
\n \n Required!\n \n Single word only!\n
\n text = {{example.text}}
\n myForm.input.$valid = {{myForm.input.$valid}}
\n myForm.input.$error = {{myForm.input.$error}}
\n myForm.$valid = {{myForm.$valid}}
\n myForm.$error.required = {{!!myForm.$error.required}}
\n
\n
\n \n var text = element(by.binding('example.text'));\n var valid = element(by.binding('myForm.input.$valid'));\n var input = element(by.model('example.text'));\n\n it('should initialize to model', function() {\n expect(text.getText()).toContain('guest');\n expect(valid.getText()).toContain('true');\n });\n\n it('should be invalid if empty', function() {\n input.clear();\n input.sendKeys('');\n\n expect(text.getText()).toEqual('text =');\n expect(valid.getText()).toContain('false');\n });\n\n it('should be invalid if multi word', function() {\n input.clear();\n input.sendKeys('hello world');\n\n expect(valid.getText()).toContain('false');\n });\n \n
\n */\n 'text': textInputType,\n\n /**\n * @ngdoc input\n * @name input[date]\n *\n * @description\n * Input with date validation and transformation. In browsers that do not yet support\n * the HTML5 date input, a text element will be used. In that case, text must be entered in a valid ISO-8601\n * date format (yyyy-MM-dd), for example: `2009-01-06`. Since many\n * modern browsers do not yet support this input type, it is important to provide cues to users on the\n * expected input format via a placeholder or label.\n *\n * The model must always be a Date object, otherwise Angular will throw an error.\n * Invalid `Date` objects (dates whose `getTime()` is `NaN`) will be rendered as an empty string.\n *\n * The timezone to be used to read/write the `Date` instance in the model can be defined using\n * {@link ng.directive:ngModelOptions ngModelOptions}. By default, this is the timezone of the browser.\n *\n * @param {string} ngModel Assignable angular expression to data-bind to.\n * @param {string=} name Property name of the form under which the control is published.\n * @param {string=} min Sets the `min` validation error key if the value entered is less than `min`. This must be a\n * valid ISO date string (yyyy-MM-dd). You can also use interpolation inside this attribute\n * (e.g. `min=\"{{minDate | date:'yyyy-MM-dd'}}\"`). Note that `min` will also add native HTML5\n * constraint validation.\n * @param {string=} max Sets the `max` validation error key if the value entered is greater than `max`. This must be\n * a valid ISO date string (yyyy-MM-dd). You can also use interpolation inside this attribute\n * (e.g. `max=\"{{maxDate | date:'yyyy-MM-dd'}}\"`). Note that `max` will also add native HTML5\n * constraint validation.\n * @param {(date|string)=} ngMin Sets the `min` validation constraint to the Date / ISO date string\n * the `ngMin` expression evaluates to. Note that it does not set the `min` attribute.\n * @param {(date|string)=} ngMax Sets the `max` validation constraint to the Date / ISO date string\n * the `ngMax` expression evaluates to. Note that it does not set the `max` attribute.\n * @param {string=} required Sets `required` validation error key if the value is not entered.\n * @param {string=} ngRequired Adds `required` attribute and `required` validation constraint to\n * the element when the ngRequired expression evaluates to true. Use `ngRequired` instead of\n * `required` when you want to data-bind to the `required` attribute.\n * @param {string=} ngChange Angular expression to be executed when input changes due to user\n * interaction with the input element.\n *\n * @example\n \n \n \n
\n \n \n
\n \n Required!\n \n Not a valid date!\n
\n value = {{example.value | date: \"yyyy-MM-dd\"}}
\n myForm.input.$valid = {{myForm.input.$valid}}
\n myForm.input.$error = {{myForm.input.$error}}
\n myForm.$valid = {{myForm.$valid}}
\n myForm.$error.required = {{!!myForm.$error.required}}
\n
\n
\n \n var value = element(by.binding('example.value | date: \"yyyy-MM-dd\"'));\n var valid = element(by.binding('myForm.input.$valid'));\n\n // currently protractor/webdriver does not support\n // sending keys to all known HTML5 input controls\n // for various browsers (see https://github.com/angular/protractor/issues/562).\n function setInput(val) {\n // set the value of the element and force validation.\n var scr = \"var ipt = document.getElementById('exampleInput'); \" +\n \"ipt.value = '\" + val + \"';\" +\n \"angular.element(ipt).scope().$apply(function(s) { s.myForm[ipt.name].$setViewValue('\" + val + \"'); });\";\n browser.executeScript(scr);\n }\n\n it('should initialize to model', function() {\n expect(value.getText()).toContain('2013-10-22');\n expect(valid.getText()).toContain('myForm.input.$valid = true');\n });\n\n it('should be invalid if empty', function() {\n setInput('');\n expect(value.getText()).toEqual('value =');\n expect(valid.getText()).toContain('myForm.input.$valid = false');\n });\n\n it('should be invalid if over max', function() {\n setInput('2015-01-01');\n expect(value.getText()).toContain('');\n expect(valid.getText()).toContain('myForm.input.$valid = false');\n });\n \n
\n */\n 'date': createDateInputType('date', DATE_REGEXP,\n createDateParser(DATE_REGEXP, ['yyyy', 'MM', 'dd']),\n 'yyyy-MM-dd'),\n\n /**\n * @ngdoc input\n * @name input[datetime-local]\n *\n * @description\n * Input with datetime validation and transformation. In browsers that do not yet support\n * the HTML5 date input, a text element will be used. In that case, the text must be entered in a valid ISO-8601\n * local datetime format (yyyy-MM-ddTHH:mm:ss), for example: `2010-12-28T14:57:00`.\n *\n * The model must always be a Date object, otherwise Angular will throw an error.\n * Invalid `Date` objects (dates whose `getTime()` is `NaN`) will be rendered as an empty string.\n *\n * The timezone to be used to read/write the `Date` instance in the model can be defined using\n * {@link ng.directive:ngModelOptions ngModelOptions}. By default, this is the timezone of the browser.\n *\n * @param {string} ngModel Assignable angular expression to data-bind to.\n * @param {string=} name Property name of the form under which the control is published.\n * @param {string=} min Sets the `min` validation error key if the value entered is less than `min`.\n * This must be a valid ISO datetime format (yyyy-MM-ddTHH:mm:ss). You can also use interpolation\n * inside this attribute (e.g. `min=\"{{minDatetimeLocal | date:'yyyy-MM-ddTHH:mm:ss'}}\"`).\n * Note that `min` will also add native HTML5 constraint validation.\n * @param {string=} max Sets the `max` validation error key if the value entered is greater than `max`.\n * This must be a valid ISO datetime format (yyyy-MM-ddTHH:mm:ss). You can also use interpolation\n * inside this attribute (e.g. `max=\"{{maxDatetimeLocal | date:'yyyy-MM-ddTHH:mm:ss'}}\"`).\n * Note that `max` will also add native HTML5 constraint validation.\n * @param {(date|string)=} ngMin Sets the `min` validation error key to the Date / ISO datetime string\n * the `ngMin` expression evaluates to. Note that it does not set the `min` attribute.\n * @param {(date|string)=} ngMax Sets the `max` validation error key to the Date / ISO datetime string\n * the `ngMax` expression evaluates to. Note that it does not set the `max` attribute.\n * @param {string=} required Sets `required` validation error key if the value is not entered.\n * @param {string=} ngRequired Adds `required` attribute and `required` validation constraint to\n * the element when the ngRequired expression evaluates to true. Use `ngRequired` instead of\n * `required` when you want to data-bind to the `required` attribute.\n * @param {string=} ngChange Angular expression to be executed when input changes due to user\n * interaction with the input element.\n *\n * @example\n \n \n \n
\n \n \n
\n \n Required!\n \n Not a valid date!\n
\n value = {{example.value | date: \"yyyy-MM-ddTHH:mm:ss\"}}
\n myForm.input.$valid = {{myForm.input.$valid}}
\n myForm.input.$error = {{myForm.input.$error}}
\n myForm.$valid = {{myForm.$valid}}
\n myForm.$error.required = {{!!myForm.$error.required}}
\n
\n
\n \n var value = element(by.binding('example.value | date: \"yyyy-MM-ddTHH:mm:ss\"'));\n var valid = element(by.binding('myForm.input.$valid'));\n\n // currently protractor/webdriver does not support\n // sending keys to all known HTML5 input controls\n // for various browsers (https://github.com/angular/protractor/issues/562).\n function setInput(val) {\n // set the value of the element and force validation.\n var scr = \"var ipt = document.getElementById('exampleInput'); \" +\n \"ipt.value = '\" + val + \"';\" +\n \"angular.element(ipt).scope().$apply(function(s) { s.myForm[ipt.name].$setViewValue('\" + val + \"'); });\";\n browser.executeScript(scr);\n }\n\n it('should initialize to model', function() {\n expect(value.getText()).toContain('2010-12-28T14:57:00');\n expect(valid.getText()).toContain('myForm.input.$valid = true');\n });\n\n it('should be invalid if empty', function() {\n setInput('');\n expect(value.getText()).toEqual('value =');\n expect(valid.getText()).toContain('myForm.input.$valid = false');\n });\n\n it('should be invalid if over max', function() {\n setInput('2015-01-01T23:59:00');\n expect(value.getText()).toContain('');\n expect(valid.getText()).toContain('myForm.input.$valid = false');\n });\n \n
\n */\n 'datetime-local': createDateInputType('datetimelocal', DATETIMELOCAL_REGEXP,\n createDateParser(DATETIMELOCAL_REGEXP, ['yyyy', 'MM', 'dd', 'HH', 'mm', 'ss', 'sss']),\n 'yyyy-MM-ddTHH:mm:ss.sss'),\n\n /**\n * @ngdoc input\n * @name input[time]\n *\n * @description\n * Input with time validation and transformation. In browsers that do not yet support\n * the HTML5 time input, a text element will be used. In that case, the text must be entered in a valid ISO-8601\n * local time format (HH:mm:ss), for example: `14:57:00`. Model must be a Date object. This binding will always output a\n * Date object to the model of January 1, 1970, or local date `new Date(1970, 0, 1, HH, mm, ss)`.\n *\n * The model must always be a Date object, otherwise Angular will throw an error.\n * Invalid `Date` objects (dates whose `getTime()` is `NaN`) will be rendered as an empty string.\n *\n * The timezone to be used to read/write the `Date` instance in the model can be defined using\n * {@link ng.directive:ngModelOptions ngModelOptions}. By default, this is the timezone of the browser.\n *\n * @param {string} ngModel Assignable angular expression to data-bind to.\n * @param {string=} name Property name of the form under which the control is published.\n * @param {string=} min Sets the `min` validation error key if the value entered is less than `min`.\n * This must be a valid ISO time format (HH:mm:ss). You can also use interpolation inside this\n * attribute (e.g. `min=\"{{minTime | date:'HH:mm:ss'}}\"`). Note that `min` will also add\n * native HTML5 constraint validation.\n * @param {string=} max Sets the `max` validation error key if the value entered is greater than `max`.\n * This must be a valid ISO time format (HH:mm:ss). You can also use interpolation inside this\n * attribute (e.g. `max=\"{{maxTime | date:'HH:mm:ss'}}\"`). Note that `max` will also add\n * native HTML5 constraint validation.\n * @param {(date|string)=} ngMin Sets the `min` validation constraint to the Date / ISO time string the\n * `ngMin` expression evaluates to. Note that it does not set the `min` attribute.\n * @param {(date|string)=} ngMax Sets the `max` validation constraint to the Date / ISO time string the\n * `ngMax` expression evaluates to. Note that it does not set the `max` attribute.\n * @param {string=} required Sets `required` validation error key if the value is not entered.\n * @param {string=} ngRequired Adds `required` attribute and `required` validation constraint to\n * the element when the ngRequired expression evaluates to true. Use `ngRequired` instead of\n * `required` when you want to data-bind to the `required` attribute.\n * @param {string=} ngChange Angular expression to be executed when input changes due to user\n * interaction with the input element.\n *\n * @example\n \n \n \n
\n \n \n
\n \n Required!\n \n Not a valid date!\n
\n value = {{example.value | date: \"HH:mm:ss\"}}
\n myForm.input.$valid = {{myForm.input.$valid}}
\n myForm.input.$error = {{myForm.input.$error}}
\n myForm.$valid = {{myForm.$valid}}
\n myForm.$error.required = {{!!myForm.$error.required}}
\n
\n
\n \n var value = element(by.binding('example.value | date: \"HH:mm:ss\"'));\n var valid = element(by.binding('myForm.input.$valid'));\n\n // currently protractor/webdriver does not support\n // sending keys to all known HTML5 input controls\n // for various browsers (https://github.com/angular/protractor/issues/562).\n function setInput(val) {\n // set the value of the element and force validation.\n var scr = \"var ipt = document.getElementById('exampleInput'); \" +\n \"ipt.value = '\" + val + \"';\" +\n \"angular.element(ipt).scope().$apply(function(s) { s.myForm[ipt.name].$setViewValue('\" + val + \"'); });\";\n browser.executeScript(scr);\n }\n\n it('should initialize to model', function() {\n expect(value.getText()).toContain('14:57:00');\n expect(valid.getText()).toContain('myForm.input.$valid = true');\n });\n\n it('should be invalid if empty', function() {\n setInput('');\n expect(value.getText()).toEqual('value =');\n expect(valid.getText()).toContain('myForm.input.$valid = false');\n });\n\n it('should be invalid if over max', function() {\n setInput('23:59:00');\n expect(value.getText()).toContain('');\n expect(valid.getText()).toContain('myForm.input.$valid = false');\n });\n \n
\n */\n 'time': createDateInputType('time', TIME_REGEXP,\n createDateParser(TIME_REGEXP, ['HH', 'mm', 'ss', 'sss']),\n 'HH:mm:ss.sss'),\n\n /**\n * @ngdoc input\n * @name input[week]\n *\n * @description\n * Input with week-of-the-year validation and transformation to Date. In browsers that do not yet support\n * the HTML5 week input, a text element will be used. In that case, the text must be entered in a valid ISO-8601\n * week format (yyyy-W##), for example: `2013-W02`.\n *\n * The model must always be a Date object, otherwise Angular will throw an error.\n * Invalid `Date` objects (dates whose `getTime()` is `NaN`) will be rendered as an empty string.\n *\n * The timezone to be used to read/write the `Date` instance in the model can be defined using\n * {@link ng.directive:ngModelOptions ngModelOptions}. By default, this is the timezone of the browser.\n *\n * @param {string} ngModel Assignable angular expression to data-bind to.\n * @param {string=} name Property name of the form under which the control is published.\n * @param {string=} min Sets the `min` validation error key if the value entered is less than `min`.\n * This must be a valid ISO week format (yyyy-W##). You can also use interpolation inside this\n * attribute (e.g. `min=\"{{minWeek | date:'yyyy-Www'}}\"`). Note that `min` will also add\n * native HTML5 constraint validation.\n * @param {string=} max Sets the `max` validation error key if the value entered is greater than `max`.\n * This must be a valid ISO week format (yyyy-W##). You can also use interpolation inside this\n * attribute (e.g. `max=\"{{maxWeek | date:'yyyy-Www'}}\"`). Note that `max` will also add\n * native HTML5 constraint validation.\n * @param {(date|string)=} ngMin Sets the `min` validation constraint to the Date / ISO week string\n * the `ngMin` expression evaluates to. Note that it does not set the `min` attribute.\n * @param {(date|string)=} ngMax Sets the `max` validation constraint to the Date / ISO week string\n * the `ngMax` expression evaluates to. Note that it does not set the `max` attribute.\n * @param {string=} required Sets `required` validation error key if the value is not entered.\n * @param {string=} ngRequired Adds `required` attribute and `required` validation constraint to\n * the element when the ngRequired expression evaluates to true. Use `ngRequired` instead of\n * `required` when you want to data-bind to the `required` attribute.\n * @param {string=} ngChange Angular expression to be executed when input changes due to user\n * interaction with the input element.\n *\n * @example\n \n \n \n
\n \n
\n \n Required!\n \n Not a valid date!\n
\n value = {{example.value | date: \"yyyy-Www\"}}
\n myForm.input.$valid = {{myForm.input.$valid}}
\n myForm.input.$error = {{myForm.input.$error}}
\n myForm.$valid = {{myForm.$valid}}
\n myForm.$error.required = {{!!myForm.$error.required}}
\n
\n
\n \n var value = element(by.binding('example.value | date: \"yyyy-Www\"'));\n var valid = element(by.binding('myForm.input.$valid'));\n\n // currently protractor/webdriver does not support\n // sending keys to all known HTML5 input controls\n // for various browsers (https://github.com/angular/protractor/issues/562).\n function setInput(val) {\n // set the value of the element and force validation.\n var scr = \"var ipt = document.getElementById('exampleInput'); \" +\n \"ipt.value = '\" + val + \"';\" +\n \"angular.element(ipt).scope().$apply(function(s) { s.myForm[ipt.name].$setViewValue('\" + val + \"'); });\";\n browser.executeScript(scr);\n }\n\n it('should initialize to model', function() {\n expect(value.getText()).toContain('2013-W01');\n expect(valid.getText()).toContain('myForm.input.$valid = true');\n });\n\n it('should be invalid if empty', function() {\n setInput('');\n expect(value.getText()).toEqual('value =');\n expect(valid.getText()).toContain('myForm.input.$valid = false');\n });\n\n it('should be invalid if over max', function() {\n setInput('2015-W01');\n expect(value.getText()).toContain('');\n expect(valid.getText()).toContain('myForm.input.$valid = false');\n });\n \n
\n */\n 'week': createDateInputType('week', WEEK_REGEXP, weekParser, 'yyyy-Www'),\n\n /**\n * @ngdoc input\n * @name input[month]\n *\n * @description\n * Input with month validation and transformation. In browsers that do not yet support\n * the HTML5 month input, a text element will be used. In that case, the text must be entered in a valid ISO-8601\n * month format (yyyy-MM), for example: `2009-01`.\n *\n * The model must always be a Date object, otherwise Angular will throw an error.\n * Invalid `Date` objects (dates whose `getTime()` is `NaN`) will be rendered as an empty string.\n * If the model is not set to the first of the month, the next view to model update will set it\n * to the first of the month.\n *\n * The timezone to be used to read/write the `Date` instance in the model can be defined using\n * {@link ng.directive:ngModelOptions ngModelOptions}. By default, this is the timezone of the browser.\n *\n * @param {string} ngModel Assignable angular expression to data-bind to.\n * @param {string=} name Property name of the form under which the control is published.\n * @param {string=} min Sets the `min` validation error key if the value entered is less than `min`.\n * This must be a valid ISO month format (yyyy-MM). You can also use interpolation inside this\n * attribute (e.g. `min=\"{{minMonth | date:'yyyy-MM'}}\"`). Note that `min` will also add\n * native HTML5 constraint validation.\n * @param {string=} max Sets the `max` validation error key if the value entered is greater than `max`.\n * This must be a valid ISO month format (yyyy-MM). You can also use interpolation inside this\n * attribute (e.g. `max=\"{{maxMonth | date:'yyyy-MM'}}\"`). Note that `max` will also add\n * native HTML5 constraint validation.\n * @param {(date|string)=} ngMin Sets the `min` validation constraint to the Date / ISO week string\n * the `ngMin` expression evaluates to. Note that it does not set the `min` attribute.\n * @param {(date|string)=} ngMax Sets the `max` validation constraint to the Date / ISO week string\n * the `ngMax` expression evaluates to. Note that it does not set the `max` attribute.\n\n * @param {string=} required Sets `required` validation error key if the value is not entered.\n * @param {string=} ngRequired Adds `required` attribute and `required` validation constraint to\n * the element when the ngRequired expression evaluates to true. Use `ngRequired` instead of\n * `required` when you want to data-bind to the `required` attribute.\n * @param {string=} ngChange Angular expression to be executed when input changes due to user\n * interaction with the input element.\n *\n * @example\n \n \n \n
\n \n \n
\n \n Required!\n \n Not a valid month!\n
\n value = {{example.value | date: \"yyyy-MM\"}}
\n myForm.input.$valid = {{myForm.input.$valid}}
\n myForm.input.$error = {{myForm.input.$error}}
\n myForm.$valid = {{myForm.$valid}}
\n myForm.$error.required = {{!!myForm.$error.required}}
\n
\n
\n \n var value = element(by.binding('example.value | date: \"yyyy-MM\"'));\n var valid = element(by.binding('myForm.input.$valid'));\n\n // currently protractor/webdriver does not support\n // sending keys to all known HTML5 input controls\n // for various browsers (https://github.com/angular/protractor/issues/562).\n function setInput(val) {\n // set the value of the element and force validation.\n var scr = \"var ipt = document.getElementById('exampleInput'); \" +\n \"ipt.value = '\" + val + \"';\" +\n \"angular.element(ipt).scope().$apply(function(s) { s.myForm[ipt.name].$setViewValue('\" + val + \"'); });\";\n browser.executeScript(scr);\n }\n\n it('should initialize to model', function() {\n expect(value.getText()).toContain('2013-10');\n expect(valid.getText()).toContain('myForm.input.$valid = true');\n });\n\n it('should be invalid if empty', function() {\n setInput('');\n expect(value.getText()).toEqual('value =');\n expect(valid.getText()).toContain('myForm.input.$valid = false');\n });\n\n it('should be invalid if over max', function() {\n setInput('2015-01');\n expect(value.getText()).toContain('');\n expect(valid.getText()).toContain('myForm.input.$valid = false');\n });\n \n
\n */\n 'month': createDateInputType('month', MONTH_REGEXP,\n createDateParser(MONTH_REGEXP, ['yyyy', 'MM']),\n 'yyyy-MM'),\n\n /**\n * @ngdoc input\n * @name input[number]\n *\n * @description\n * Text input with number validation and transformation. Sets the `number` validation\n * error if not a valid number.\n *\n *
\n * The model must always be of type `number` otherwise Angular will throw an error.\n * Be aware that a string containing a number is not enough. See the {@link ngModel:numfmt}\n * error docs for more information and an example of how to convert your model if necessary.\n *
\n *\n * ## Issues with HTML5 constraint validation\n *\n * In browsers that follow the\n * [HTML5 specification](https://html.spec.whatwg.org/multipage/forms.html#number-state-%28type=number%29),\n * `input[number]` does not work as expected with {@link ngModelOptions `ngModelOptions.allowInvalid`}.\n * If a non-number is entered in the input, the browser will report the value as an empty string,\n * which means the view / model values in `ngModel` and subsequently the scope value\n * will also be an empty string.\n *\n *\n * @param {string} ngModel Assignable angular expression to data-bind to.\n * @param {string=} name Property name of the form under which the control is published.\n * @param {string=} min Sets the `min` validation error key if the value entered is less than `min`.\n * Can be interpolated.\n * @param {string=} max Sets the `max` validation error key if the value entered is greater than `max`.\n * Can be interpolated.\n * @param {string=} ngMin Like `min`, sets the `min` validation error key if the value entered is less than `ngMin`,\n * but does not trigger HTML5 native validation. Takes an expression.\n * @param {string=} ngMax Like `max`, sets the `max` validation error key if the value entered is greater than `ngMax`,\n * but does not trigger HTML5 native validation. Takes an expression.\n * @param {string=} step Sets the `step` validation error key if the value entered does not fit the `step` constraint.\n * Can be interpolated.\n * @param {string=} ngStep Like `step`, sets the `step` validation error key if the value entered does not fit the `ngStep` constraint,\n * but does not trigger HTML5 native validation. Takes an expression.\n * @param {string=} required Sets `required` validation error key if the value is not entered.\n * @param {string=} ngRequired Adds `required` attribute and `required` validation constraint to\n * the element when the ngRequired expression evaluates to true. Use `ngRequired` instead of\n * `required` when you want to data-bind to the `required` attribute.\n * @param {number=} ngMinlength Sets `minlength` validation error key if the value is shorter than\n * minlength.\n * @param {number=} ngMaxlength Sets `maxlength` validation error key if the value is longer than\n * maxlength. Setting the attribute to a negative or non-numeric value, allows view values of\n * any length.\n * @param {string=} pattern Similar to `ngPattern` except that the attribute value is the actual string\n * that contains the regular expression body that will be converted to a regular expression\n * as in the ngPattern directive.\n * @param {string=} ngPattern Sets `pattern` validation error key if the ngModel {@link ngModel.NgModelController#$viewValue $viewValue}\n * does not match a RegExp found by evaluating the Angular expression given in the attribute value.\n * If the expression evaluates to a RegExp object, then this is used directly.\n * If the expression evaluates to a string, then it will be converted to a RegExp\n * after wrapping it in `^` and `$` characters. For instance, `\"abc\"` will be converted to\n * `new RegExp('^abc$')`.
\n * **Note:** Avoid using the `g` flag on the RegExp, as it will cause each successive search to\n * start at the index of the last search's match, thus not taking the whole input value into\n * account.\n * @param {string=} ngChange Angular expression to be executed when input changes due to user\n * interaction with the input element.\n *\n * @example\n \n \n \n
\n \n
\n \n Required!\n \n Not valid number!\n
\n value = {{example.value}}
\n myForm.input.$valid = {{myForm.input.$valid}}
\n myForm.input.$error = {{myForm.input.$error}}
\n myForm.$valid = {{myForm.$valid}}
\n myForm.$error.required = {{!!myForm.$error.required}}
\n
\n
\n \n var value = element(by.binding('example.value'));\n var valid = element(by.binding('myForm.input.$valid'));\n var input = element(by.model('example.value'));\n\n it('should initialize to model', function() {\n expect(value.getText()).toContain('12');\n expect(valid.getText()).toContain('true');\n });\n\n it('should be invalid if empty', function() {\n input.clear();\n input.sendKeys('');\n expect(value.getText()).toEqual('value =');\n expect(valid.getText()).toContain('false');\n });\n\n it('should be invalid if over max', function() {\n input.clear();\n input.sendKeys('123');\n expect(value.getText()).toEqual('value =');\n expect(valid.getText()).toContain('false');\n });\n \n
\n */\n 'number': numberInputType,\n\n\n /**\n * @ngdoc input\n * @name input[url]\n *\n * @description\n * Text input with URL validation. Sets the `url` validation error key if the content is not a\n * valid URL.\n *\n *
\n * **Note:** `input[url]` uses a regex to validate urls that is derived from the regex\n * used in Chromium. If you need stricter validation, you can use `ng-pattern` or modify\n * the built-in validators (see the {@link guide/forms Forms guide})\n *
\n *\n * @param {string} ngModel Assignable angular expression to data-bind to.\n * @param {string=} name Property name of the form under which the control is published.\n * @param {string=} required Sets `required` validation error key if the value is not entered.\n * @param {string=} ngRequired Adds `required` attribute and `required` validation constraint to\n * the element when the ngRequired expression evaluates to true. Use `ngRequired` instead of\n * `required` when you want to data-bind to the `required` attribute.\n * @param {number=} ngMinlength Sets `minlength` validation error key if the value is shorter than\n * minlength.\n * @param {number=} ngMaxlength Sets `maxlength` validation error key if the value is longer than\n * maxlength. Setting the attribute to a negative or non-numeric value, allows view values of\n * any length.\n * @param {string=} pattern Similar to `ngPattern` except that the attribute value is the actual string\n * that contains the regular expression body that will be converted to a regular expression\n * as in the ngPattern directive.\n * @param {string=} ngPattern Sets `pattern` validation error key if the ngModel {@link ngModel.NgModelController#$viewValue $viewValue}\n * does not match a RegExp found by evaluating the Angular expression given in the attribute value.\n * If the expression evaluates to a RegExp object, then this is used directly.\n * If the expression evaluates to a string, then it will be converted to a RegExp\n * after wrapping it in `^` and `$` characters. For instance, `\"abc\"` will be converted to\n * `new RegExp('^abc$')`.
\n * **Note:** Avoid using the `g` flag on the RegExp, as it will cause each successive search to\n * start at the index of the last search's match, thus not taking the whole input value into\n * account.\n * @param {string=} ngChange Angular expression to be executed when input changes due to user\n * interaction with the input element.\n *\n * @example\n \n \n \n
\n
\n \n var text = element(by.binding('url.text'));\n var valid = element(by.binding('myForm.input.$valid'));\n var input = element(by.model('url.text'));\n\n it('should initialize to model', function() {\n expect(text.getText()).toContain('http://google.com');\n expect(valid.getText()).toContain('true');\n });\n\n it('should be invalid if empty', function() {\n input.clear();\n input.sendKeys('');\n\n expect(text.getText()).toEqual('text =');\n expect(valid.getText()).toContain('false');\n });\n\n it('should be invalid if not url', function() {\n input.clear();\n input.sendKeys('box');\n\n expect(valid.getText()).toContain('false');\n });\n \n
\n */\n 'url': urlInputType,\n\n\n /**\n * @ngdoc input\n * @name input[email]\n *\n * @description\n * Text input with email validation. Sets the `email` validation error key if not a valid email\n * address.\n *\n *
\n * **Note:** `input[email]` uses a regex to validate email addresses that is derived from the regex\n * used in Chromium. If you need stricter validation (e.g. requiring a top-level domain), you can\n * use `ng-pattern` or modify the built-in validators (see the {@link guide/forms Forms guide})\n *
\n *\n * @param {string} ngModel Assignable angular expression to data-bind to.\n * @param {string=} name Property name of the form under which the control is published.\n * @param {string=} required Sets `required` validation error key if the value is not entered.\n * @param {string=} ngRequired Adds `required` attribute and `required` validation constraint to\n * the element when the ngRequired expression evaluates to true. Use `ngRequired` instead of\n * `required` when you want to data-bind to the `required` attribute.\n * @param {number=} ngMinlength Sets `minlength` validation error key if the value is shorter than\n * minlength.\n * @param {number=} ngMaxlength Sets `maxlength` validation error key if the value is longer than\n * maxlength. Setting the attribute to a negative or non-numeric value, allows view values of\n * any length.\n * @param {string=} pattern Similar to `ngPattern` except that the attribute value is the actual string\n * that contains the regular expression body that will be converted to a regular expression\n * as in the ngPattern directive.\n * @param {string=} ngPattern Sets `pattern` validation error key if the ngModel {@link ngModel.NgModelController#$viewValue $viewValue}\n * does not match a RegExp found by evaluating the Angular expression given in the attribute value.\n * If the expression evaluates to a RegExp object, then this is used directly.\n * If the expression evaluates to a string, then it will be converted to a RegExp\n * after wrapping it in `^` and `$` characters. For instance, `\"abc\"` will be converted to\n * `new RegExp('^abc$')`.
\n * **Note:** Avoid using the `g` flag on the RegExp, as it will cause each successive search to\n * start at the index of the last search's match, thus not taking the whole input value into\n * account.\n * @param {string=} ngChange Angular expression to be executed when input changes due to user\n * interaction with the input element.\n *\n * @example\n \n \n \n
\n \n
\n \n Required!\n \n Not valid email!\n
\n text = {{email.text}}
\n myForm.input.$valid = {{myForm.input.$valid}}
\n myForm.input.$error = {{myForm.input.$error}}
\n myForm.$valid = {{myForm.$valid}}
\n myForm.$error.required = {{!!myForm.$error.required}}
\n myForm.$error.email = {{!!myForm.$error.email}}
\n
\n
\n \n var text = element(by.binding('email.text'));\n var valid = element(by.binding('myForm.input.$valid'));\n var input = element(by.model('email.text'));\n\n it('should initialize to model', function() {\n expect(text.getText()).toContain('me@example.com');\n expect(valid.getText()).toContain('true');\n });\n\n it('should be invalid if empty', function() {\n input.clear();\n input.sendKeys('');\n expect(text.getText()).toEqual('text =');\n expect(valid.getText()).toContain('false');\n });\n\n it('should be invalid if not email', function() {\n input.clear();\n input.sendKeys('xxx');\n\n expect(valid.getText()).toContain('false');\n });\n \n
\n */\n 'email': emailInputType,\n\n\n /**\n * @ngdoc input\n * @name input[radio]\n *\n * @description\n * HTML radio button.\n *\n * @param {string} ngModel Assignable angular expression to data-bind to.\n * @param {string} value The value to which the `ngModel` expression should be set when selected.\n * Note that `value` only supports `string` values, i.e. the scope model needs to be a string,\n * too. Use `ngValue` if you need complex models (`number`, `object`, ...).\n * @param {string=} name Property name of the form under which the control is published.\n * @param {string=} ngChange Angular expression to be executed when input changes due to user\n * interaction with the input element.\n * @param {string} ngValue Angular expression to which `ngModel` will be be set when the radio\n * is selected. Should be used instead of the `value` attribute if you need\n * a non-string `ngModel` (`boolean`, `array`, ...).\n *\n * @example\n \n \n \n
\n
\n
\n
\n color = {{color.name | json}}
\n
\n Note that `ng-value=\"specialValue\"` sets radio item's value to be the value of `$scope.specialValue`.\n
\n \n it('should change state', function() {\n var inputs = element.all(by.model('color.name'));\n var color = element(by.binding('color.name'));\n\n expect(color.getText()).toContain('blue');\n\n inputs.get(0).click();\n expect(color.getText()).toContain('red');\n\n inputs.get(1).click();\n expect(color.getText()).toContain('green');\n });\n \n
\n */\n 'radio': radioInputType,\n\n /**\n * @ngdoc input\n * @name input[range]\n *\n * @description\n * Native range input with validation and transformation.\n *\n * The model for the range input must always be a `Number`.\n *\n * IE9 and other browsers that do not support the `range` type fall back\n * to a text input without any default values for `min`, `max` and `step`. Model binding,\n * validation and number parsing are nevertheless supported.\n *\n * Browsers that support range (latest Chrome, Safari, Firefox, Edge) treat `input[range]`\n * in a way that never allows the input to hold an invalid value. That means:\n * - any non-numerical value is set to `(max + min) / 2`.\n * - any numerical value that is less than the current min val, or greater than the current max val\n * is set to the min / max val respectively.\n * - additionally, the current `step` is respected, so the nearest value that satisfies a step\n * is used.\n *\n * See the [HTML Spec on input[type=range]](https://www.w3.org/TR/html5/forms.html#range-state-(type=range))\n * for more info.\n *\n * This has the following consequences for Angular:\n *\n * Since the element value should always reflect the current model value, a range input\n * will set the bound ngModel expression to the value that the browser has set for the\n * input element. For example, in the following input ``,\n * if the application sets `model.value = null`, the browser will set the input to `'50'`.\n * Angular will then set the model to `50`, to prevent input and model value being out of sync.\n *\n * That means the model for range will immediately be set to `50` after `ngModel` has been\n * initialized. It also means a range input can never have the required error.\n *\n * This does not only affect changes to the model value, but also to the values of the `min`,\n * `max`, and `step` attributes. When these change in a way that will cause the browser to modify\n * the input value, Angular will also update the model value.\n *\n * Automatic value adjustment also means that a range input element can never have the `required`,\n * `min`, or `max` errors.\n *\n * However, `step` is currently only fully implemented by Firefox. Other browsers have problems\n * when the step value changes dynamically - they do not adjust the element value correctly, but\n * instead may set the `stepMismatch` error. If that's the case, the Angular will set the `step`\n * error on the input, and set the model to `undefined`.\n *\n * Note that `input[range]` is not compatible with`ngMax`, `ngMin`, and `ngStep`, because they do\n * not set the `min` and `max` attributes, which means that the browser won't automatically adjust\n * the input value based on their values, and will always assume min = 0, max = 100, and step = 1.\n *\n * @param {string} ngModel Assignable angular expression to data-bind to.\n * @param {string=} name Property name of the form under which the control is published.\n * @param {string=} min Sets the `min` validation to ensure that the value entered is greater\n * than `min`. Can be interpolated.\n * @param {string=} max Sets the `max` validation to ensure that the value entered is less than `max`.\n * Can be interpolated.\n * @param {string=} step Sets the `step` validation to ensure that the value entered matches the `step`\n * Can be interpolated.\n * @param {string=} ngChange Angular expression to be executed when the ngModel value changes due\n * to user interaction with the input element.\n * @param {expression=} ngChecked If the expression is truthy, then the `checked` attribute will be set on the\n * element. **Note** : `ngChecked` should not be used alongside `ngModel`.\n * Checkout {@link ng.directive:ngChecked ngChecked} for usage.\n *\n * @example\n \n \n \n
\n\n Model as range: \n
\n Model as number:
\n Min:
\n Max:
\n value = {{value}}
\n myForm.range.$valid = {{myForm.range.$valid}}
\n myForm.range.$error = {{myForm.range.$error}}\n
\n
\n
\n\n * ## Range Input with ngMin & ngMax attributes\n\n * @example\n \n \n \n
\n Model as range: \n
\n Model as number:
\n Min:
\n Max:
\n value = {{value}}
\n myForm.range.$valid = {{myForm.range.$valid}}
\n myForm.range.$error = {{myForm.range.$error}}\n
\n
\n
\n\n */\n 'range': rangeInputType,\n\n /**\n * @ngdoc input\n * @name input[checkbox]\n *\n * @description\n * HTML checkbox.\n *\n * @param {string} ngModel Assignable angular expression to data-bind to.\n * @param {string=} name Property name of the form under which the control is published.\n * @param {expression=} ngTrueValue The value to which the expression should be set when selected.\n * @param {expression=} ngFalseValue The value to which the expression should be set when not selected.\n * @param {string=} ngChange Angular expression to be executed when input changes due to user\n * interaction with the input element.\n *\n * @example\n \n \n \n
\n
\n
\n value1 = {{checkboxModel.value1}}
\n value2 = {{checkboxModel.value2}}
\n
\n
\n \n it('should change state', function() {\n var value1 = element(by.binding('checkboxModel.value1'));\n var value2 = element(by.binding('checkboxModel.value2'));\n\n expect(value1.getText()).toContain('true');\n expect(value2.getText()).toContain('YES');\n\n element(by.model('checkboxModel.value1')).click();\n element(by.model('checkboxModel.value2')).click();\n\n expect(value1.getText()).toContain('false');\n expect(value2.getText()).toContain('NO');\n });\n \n
\n */\n 'checkbox': checkboxInputType,\n\n 'hidden': noop,\n 'button': noop,\n 'submit': noop,\n 'reset': noop,\n 'file': noop\n};\n\nfunction stringBasedInputType(ctrl) {\n ctrl.$formatters.push(function(value) {\n return ctrl.$isEmpty(value) ? value : value.toString();\n });\n}\n\nfunction textInputType(scope, element, attr, ctrl, $sniffer, $browser) {\n baseInputType(scope, element, attr, ctrl, $sniffer, $browser);\n stringBasedInputType(ctrl);\n}\n\nfunction baseInputType(scope, element, attr, ctrl, $sniffer, $browser) {\n var type = lowercase(element[0].type);\n\n // In composition mode, users are still inputting intermediate text buffer,\n // hold the listener until composition is done.\n // More about composition events: https://developer.mozilla.org/en-US/docs/Web/API/CompositionEvent\n if (!$sniffer.android) {\n var composing = false;\n\n element.on('compositionstart', function() {\n composing = true;\n });\n\n element.on('compositionend', function() {\n composing = false;\n listener();\n });\n }\n\n var timeout;\n\n var listener = function(ev) {\n if (timeout) {\n $browser.defer.cancel(timeout);\n timeout = null;\n }\n if (composing) return;\n var value = element.val(),\n event = ev && ev.type;\n\n // By default we will trim the value\n // If the attribute ng-trim exists we will avoid trimming\n // If input type is 'password', the value is never trimmed\n if (type !== 'password' && (!attr.ngTrim || attr.ngTrim !== 'false')) {\n value = trim(value);\n }\n\n // If a control is suffering from bad input (due to native validators), browsers discard its\n // value, so it may be necessary to revalidate (by calling $setViewValue again) even if the\n // control's value is the same empty value twice in a row.\n if (ctrl.$viewValue !== value || (value === '' && ctrl.$$hasNativeValidators)) {\n ctrl.$setViewValue(value, event);\n }\n };\n\n // if the browser does support \"input\" event, we are fine - except on IE9 which doesn't fire the\n // input event on backspace, delete or cut\n if ($sniffer.hasEvent('input')) {\n element.on('input', listener);\n } else {\n var deferListener = function(ev, input, origValue) {\n if (!timeout) {\n timeout = $browser.defer(function() {\n timeout = null;\n if (!input || input.value !== origValue) {\n listener(ev);\n }\n });\n }\n };\n\n element.on('keydown', /** @this */ function(event) {\n var key = event.keyCode;\n\n // ignore\n // command modifiers arrows\n if (key === 91 || (15 < key && key < 19) || (37 <= key && key <= 40)) return;\n\n deferListener(event, this, this.value);\n });\n\n // if user modifies input value using context menu in IE, we need \"paste\" and \"cut\" events to catch it\n if ($sniffer.hasEvent('paste')) {\n element.on('paste cut', deferListener);\n }\n }\n\n // if user paste into input using mouse on older browser\n // or form autocomplete on newer browser, we need \"change\" event to catch it\n element.on('change', listener);\n\n // Some native input types (date-family) have the ability to change validity without\n // firing any input/change events.\n // For these event types, when native validators are present and the browser supports the type,\n // check for validity changes on various DOM events.\n if (PARTIAL_VALIDATION_TYPES[type] && ctrl.$$hasNativeValidators && type === attr.type) {\n element.on(PARTIAL_VALIDATION_EVENTS, /** @this */ function(ev) {\n if (!timeout) {\n var validity = this[VALIDITY_STATE_PROPERTY];\n var origBadInput = validity.badInput;\n var origTypeMismatch = validity.typeMismatch;\n timeout = $browser.defer(function() {\n timeout = null;\n if (validity.badInput !== origBadInput || validity.typeMismatch !== origTypeMismatch) {\n listener(ev);\n }\n });\n }\n });\n }\n\n ctrl.$render = function() {\n // Workaround for Firefox validation #12102.\n var value = ctrl.$isEmpty(ctrl.$viewValue) ? '' : ctrl.$viewValue;\n if (element.val() !== value) {\n element.val(value);\n }\n };\n}\n\nfunction weekParser(isoWeek, existingDate) {\n if (isDate(isoWeek)) {\n return isoWeek;\n }\n\n if (isString(isoWeek)) {\n WEEK_REGEXP.lastIndex = 0;\n var parts = WEEK_REGEXP.exec(isoWeek);\n if (parts) {\n var year = +parts[1],\n week = +parts[2],\n hours = 0,\n minutes = 0,\n seconds = 0,\n milliseconds = 0,\n firstThurs = getFirstThursdayOfYear(year),\n addDays = (week - 1) * 7;\n\n if (existingDate) {\n hours = existingDate.getHours();\n minutes = existingDate.getMinutes();\n seconds = existingDate.getSeconds();\n milliseconds = existingDate.getMilliseconds();\n }\n\n return new Date(year, 0, firstThurs.getDate() + addDays, hours, minutes, seconds, milliseconds);\n }\n }\n\n return NaN;\n}\n\nfunction createDateParser(regexp, mapping) {\n return function(iso, date) {\n var parts, map;\n\n if (isDate(iso)) {\n return iso;\n }\n\n if (isString(iso)) {\n // When a date is JSON'ified to wraps itself inside of an extra\n // set of double quotes. This makes the date parsing code unable\n // to match the date string and parse it as a date.\n if (iso.charAt(0) === '\"' && iso.charAt(iso.length - 1) === '\"') {\n iso = iso.substring(1, iso.length - 1);\n }\n if (ISO_DATE_REGEXP.test(iso)) {\n return new Date(iso);\n }\n regexp.lastIndex = 0;\n parts = regexp.exec(iso);\n\n if (parts) {\n parts.shift();\n if (date) {\n map = {\n yyyy: date.getFullYear(),\n MM: date.getMonth() + 1,\n dd: date.getDate(),\n HH: date.getHours(),\n mm: date.getMinutes(),\n ss: date.getSeconds(),\n sss: date.getMilliseconds() / 1000\n };\n } else {\n map = { yyyy: 1970, MM: 1, dd: 1, HH: 0, mm: 0, ss: 0, sss: 0 };\n }\n\n forEach(parts, function(part, index) {\n if (index < mapping.length) {\n map[mapping[index]] = +part;\n }\n });\n return new Date(map.yyyy, map.MM - 1, map.dd, map.HH, map.mm, map.ss || 0, map.sss * 1000 || 0);\n }\n }\n\n return NaN;\n };\n}\n\nfunction createDateInputType(type, regexp, parseDate, format) {\n return function dynamicDateInputType(scope, element, attr, ctrl, $sniffer, $browser, $filter) {\n badInputChecker(scope, element, attr, ctrl);\n baseInputType(scope, element, attr, ctrl, $sniffer, $browser);\n var timezone = ctrl && ctrl.$options.getOption('timezone');\n var previousDate;\n\n ctrl.$$parserName = type;\n ctrl.$parsers.push(function(value) {\n if (ctrl.$isEmpty(value)) return null;\n if (regexp.test(value)) {\n // Note: We cannot read ctrl.$modelValue, as there might be a different\n // parser/formatter in the processing chain so that the model\n // contains some different data format!\n var parsedDate = parseDate(value, previousDate);\n if (timezone) {\n parsedDate = convertTimezoneToLocal(parsedDate, timezone);\n }\n return parsedDate;\n }\n return undefined;\n });\n\n ctrl.$formatters.push(function(value) {\n if (value && !isDate(value)) {\n throw ngModelMinErr('datefmt', 'Expected `{0}` to be a date', value);\n }\n if (isValidDate(value)) {\n previousDate = value;\n if (previousDate && timezone) {\n previousDate = convertTimezoneToLocal(previousDate, timezone, true);\n }\n return $filter('date')(value, format, timezone);\n } else {\n previousDate = null;\n return '';\n }\n });\n\n if (isDefined(attr.min) || attr.ngMin) {\n var minVal;\n ctrl.$validators.min = function(value) {\n return !isValidDate(value) || isUndefined(minVal) || parseDate(value) >= minVal;\n };\n attr.$observe('min', function(val) {\n minVal = parseObservedDateValue(val);\n ctrl.$validate();\n });\n }\n\n if (isDefined(attr.max) || attr.ngMax) {\n var maxVal;\n ctrl.$validators.max = function(value) {\n return !isValidDate(value) || isUndefined(maxVal) || parseDate(value) <= maxVal;\n };\n attr.$observe('max', function(val) {\n maxVal = parseObservedDateValue(val);\n ctrl.$validate();\n });\n }\n\n function isValidDate(value) {\n // Invalid Date: getTime() returns NaN\n return value && !(value.getTime && value.getTime() !== value.getTime());\n }\n\n function parseObservedDateValue(val) {\n return isDefined(val) && !isDate(val) ? parseDate(val) || undefined : val;\n }\n };\n}\n\nfunction badInputChecker(scope, element, attr, ctrl) {\n var node = element[0];\n var nativeValidation = ctrl.$$hasNativeValidators = isObject(node.validity);\n if (nativeValidation) {\n ctrl.$parsers.push(function(value) {\n var validity = element.prop(VALIDITY_STATE_PROPERTY) || {};\n return validity.badInput || validity.typeMismatch ? undefined : value;\n });\n }\n}\n\nfunction numberFormatterParser(ctrl) {\n ctrl.$$parserName = 'number';\n ctrl.$parsers.push(function(value) {\n if (ctrl.$isEmpty(value)) return null;\n if (NUMBER_REGEXP.test(value)) return parseFloat(value);\n return undefined;\n });\n\n ctrl.$formatters.push(function(value) {\n if (!ctrl.$isEmpty(value)) {\n if (!isNumber(value)) {\n throw ngModelMinErr('numfmt', 'Expected `{0}` to be a number', value);\n }\n value = value.toString();\n }\n return value;\n });\n}\n\nfunction parseNumberAttrVal(val) {\n if (isDefined(val) && !isNumber(val)) {\n val = parseFloat(val);\n }\n return !isNumberNaN(val) ? val : undefined;\n}\n\nfunction isNumberInteger(num) {\n // See http://stackoverflow.com/questions/14636536/how-to-check-if-a-variable-is-an-integer-in-javascript#14794066\n // (minus the assumption that `num` is a number)\n\n // eslint-disable-next-line no-bitwise\n return (num | 0) === num;\n}\n\nfunction countDecimals(num) {\n var numString = num.toString();\n var decimalSymbolIndex = numString.indexOf('.');\n\n if (decimalSymbolIndex === -1) {\n if (-1 < num && num < 1) {\n // It may be in the exponential notation format (`1e-X`)\n var match = /e-(\\d+)$/.exec(numString);\n\n if (match) {\n return Number(match[1]);\n }\n }\n\n return 0;\n }\n\n return numString.length - decimalSymbolIndex - 1;\n}\n\nfunction isValidForStep(viewValue, stepBase, step) {\n // At this point `stepBase` and `step` are expected to be non-NaN values\n // and `viewValue` is expected to be a valid stringified number.\n var value = Number(viewValue);\n\n // Due to limitations in Floating Point Arithmetic (e.g. `0.3 - 0.2 !== 0.1` or\n // `0.5 % 0.1 !== 0`), we need to convert all numbers to integers.\n if (!isNumberInteger(value) || !isNumberInteger(stepBase) || !isNumberInteger(step)) {\n var decimalCount = Math.max(countDecimals(value), countDecimals(stepBase), countDecimals(step));\n var multiplier = Math.pow(10, decimalCount);\n\n value = value * multiplier;\n stepBase = stepBase * multiplier;\n step = step * multiplier;\n }\n\n return (value - stepBase) % step === 0;\n}\n\nfunction numberInputType(scope, element, attr, ctrl, $sniffer, $browser) {\n badInputChecker(scope, element, attr, ctrl);\n numberFormatterParser(ctrl);\n baseInputType(scope, element, attr, ctrl, $sniffer, $browser);\n\n var minVal;\n var maxVal;\n\n if (isDefined(attr.min) || attr.ngMin) {\n ctrl.$validators.min = function(value) {\n return ctrl.$isEmpty(value) || isUndefined(minVal) || value >= minVal;\n };\n\n attr.$observe('min', function(val) {\n minVal = parseNumberAttrVal(val);\n // TODO(matsko): implement validateLater to reduce number of validations\n ctrl.$validate();\n });\n }\n\n if (isDefined(attr.max) || attr.ngMax) {\n ctrl.$validators.max = function(value) {\n return ctrl.$isEmpty(value) || isUndefined(maxVal) || value <= maxVal;\n };\n\n attr.$observe('max', function(val) {\n maxVal = parseNumberAttrVal(val);\n // TODO(matsko): implement validateLater to reduce number of validations\n ctrl.$validate();\n });\n }\n\n if (isDefined(attr.step) || attr.ngStep) {\n var stepVal;\n ctrl.$validators.step = function(modelValue, viewValue) {\n return ctrl.$isEmpty(viewValue) || isUndefined(stepVal) ||\n isValidForStep(viewValue, minVal || 0, stepVal);\n };\n\n attr.$observe('step', function(val) {\n stepVal = parseNumberAttrVal(val);\n // TODO(matsko): implement validateLater to reduce number of validations\n ctrl.$validate();\n });\n }\n}\n\nfunction rangeInputType(scope, element, attr, ctrl, $sniffer, $browser) {\n badInputChecker(scope, element, attr, ctrl);\n numberFormatterParser(ctrl);\n baseInputType(scope, element, attr, ctrl, $sniffer, $browser);\n\n var supportsRange = ctrl.$$hasNativeValidators && element[0].type === 'range',\n minVal = supportsRange ? 0 : undefined,\n maxVal = supportsRange ? 100 : undefined,\n stepVal = supportsRange ? 1 : undefined,\n validity = element[0].validity,\n hasMinAttr = isDefined(attr.min),\n hasMaxAttr = isDefined(attr.max),\n hasStepAttr = isDefined(attr.step);\n\n var originalRender = ctrl.$render;\n\n ctrl.$render = supportsRange && isDefined(validity.rangeUnderflow) && isDefined(validity.rangeOverflow) ?\n //Browsers that implement range will set these values automatically, but reading the adjusted values after\n //$render would cause the min / max validators to be applied with the wrong value\n function rangeRender() {\n originalRender();\n ctrl.$setViewValue(element.val());\n } :\n originalRender;\n\n if (hasMinAttr) {\n ctrl.$validators.min = supportsRange ?\n // Since all browsers set the input to a valid value, we don't need to check validity\n function noopMinValidator() { return true; } :\n // non-support browsers validate the min val\n function minValidator(modelValue, viewValue) {\n return ctrl.$isEmpty(viewValue) || isUndefined(minVal) || viewValue >= minVal;\n };\n\n setInitialValueAndObserver('min', minChange);\n }\n\n if (hasMaxAttr) {\n ctrl.$validators.max = supportsRange ?\n // Since all browsers set the input to a valid value, we don't need to check validity\n function noopMaxValidator() { return true; } :\n // non-support browsers validate the max val\n function maxValidator(modelValue, viewValue) {\n return ctrl.$isEmpty(viewValue) || isUndefined(maxVal) || viewValue <= maxVal;\n };\n\n setInitialValueAndObserver('max', maxChange);\n }\n\n if (hasStepAttr) {\n ctrl.$validators.step = supportsRange ?\n function nativeStepValidator() {\n // Currently, only FF implements the spec on step change correctly (i.e. adjusting the\n // input element value to a valid value). It's possible that other browsers set the stepMismatch\n // validity error instead, so we can at least report an error in that case.\n return !validity.stepMismatch;\n } :\n // ngStep doesn't set the setp attr, so the browser doesn't adjust the input value as setting step would\n function stepValidator(modelValue, viewValue) {\n return ctrl.$isEmpty(viewValue) || isUndefined(stepVal) ||\n isValidForStep(viewValue, minVal || 0, stepVal);\n };\n\n setInitialValueAndObserver('step', stepChange);\n }\n\n function setInitialValueAndObserver(htmlAttrName, changeFn) {\n // interpolated attributes set the attribute value only after a digest, but we need the\n // attribute value when the input is first rendered, so that the browser can adjust the\n // input value based on the min/max value\n element.attr(htmlAttrName, attr[htmlAttrName]);\n attr.$observe(htmlAttrName, changeFn);\n }\n\n function minChange(val) {\n minVal = parseNumberAttrVal(val);\n // ignore changes before model is initialized\n if (isNumberNaN(ctrl.$modelValue)) {\n return;\n }\n\n if (supportsRange) {\n var elVal = element.val();\n // IE11 doesn't set the el val correctly if the minVal is greater than the element value\n if (minVal > elVal) {\n elVal = minVal;\n element.val(elVal);\n }\n ctrl.$setViewValue(elVal);\n } else {\n // TODO(matsko): implement validateLater to reduce number of validations\n ctrl.$validate();\n }\n }\n\n function maxChange(val) {\n maxVal = parseNumberAttrVal(val);\n // ignore changes before model is initialized\n if (isNumberNaN(ctrl.$modelValue)) {\n return;\n }\n\n if (supportsRange) {\n var elVal = element.val();\n // IE11 doesn't set the el val correctly if the maxVal is less than the element value\n if (maxVal < elVal) {\n element.val(maxVal);\n // IE11 and Chrome don't set the value to the minVal when max < min\n elVal = maxVal < minVal ? minVal : maxVal;\n }\n ctrl.$setViewValue(elVal);\n } else {\n // TODO(matsko): implement validateLater to reduce number of validations\n ctrl.$validate();\n }\n }\n\n function stepChange(val) {\n stepVal = parseNumberAttrVal(val);\n // ignore changes before model is initialized\n if (isNumberNaN(ctrl.$modelValue)) {\n return;\n }\n\n // Some browsers don't adjust the input value correctly, but set the stepMismatch error\n if (supportsRange && ctrl.$viewValue !== element.val()) {\n ctrl.$setViewValue(element.val());\n } else {\n // TODO(matsko): implement validateLater to reduce number of validations\n ctrl.$validate();\n }\n }\n}\n\nfunction urlInputType(scope, element, attr, ctrl, $sniffer, $browser) {\n // Note: no badInputChecker here by purpose as `url` is only a validation\n // in browsers, i.e. we can always read out input.value even if it is not valid!\n baseInputType(scope, element, attr, ctrl, $sniffer, $browser);\n stringBasedInputType(ctrl);\n\n ctrl.$$parserName = 'url';\n ctrl.$validators.url = function(modelValue, viewValue) {\n var value = modelValue || viewValue;\n return ctrl.$isEmpty(value) || URL_REGEXP.test(value);\n };\n}\n\nfunction emailInputType(scope, element, attr, ctrl, $sniffer, $browser) {\n // Note: no badInputChecker here by purpose as `url` is only a validation\n // in browsers, i.e. we can always read out input.value even if it is not valid!\n baseInputType(scope, element, attr, ctrl, $sniffer, $browser);\n stringBasedInputType(ctrl);\n\n ctrl.$$parserName = 'email';\n ctrl.$validators.email = function(modelValue, viewValue) {\n var value = modelValue || viewValue;\n return ctrl.$isEmpty(value) || EMAIL_REGEXP.test(value);\n };\n}\n\nfunction radioInputType(scope, element, attr, ctrl) {\n var doTrim = !attr.ngTrim || trim(attr.ngTrim) !== 'false';\n // make the name unique, if not defined\n if (isUndefined(attr.name)) {\n element.attr('name', nextUid());\n }\n\n var listener = function(ev) {\n var value;\n if (element[0].checked) {\n value = attr.value;\n if (doTrim) {\n value = trim(value);\n }\n ctrl.$setViewValue(value, ev && ev.type);\n }\n };\n\n element.on('click', listener);\n\n ctrl.$render = function() {\n var value = attr.value;\n if (doTrim) {\n value = trim(value);\n }\n element[0].checked = (value === ctrl.$viewValue);\n };\n\n attr.$observe('value', ctrl.$render);\n}\n\nfunction parseConstantExpr($parse, context, name, expression, fallback) {\n var parseFn;\n if (isDefined(expression)) {\n parseFn = $parse(expression);\n if (!parseFn.constant) {\n throw ngModelMinErr('constexpr', 'Expected constant expression for `{0}`, but saw ' +\n '`{1}`.', name, expression);\n }\n return parseFn(context);\n }\n return fallback;\n}\n\nfunction checkboxInputType(scope, element, attr, ctrl, $sniffer, $browser, $filter, $parse) {\n var trueValue = parseConstantExpr($parse, scope, 'ngTrueValue', attr.ngTrueValue, true);\n var falseValue = parseConstantExpr($parse, scope, 'ngFalseValue', attr.ngFalseValue, false);\n\n var listener = function(ev) {\n ctrl.$setViewValue(element[0].checked, ev && ev.type);\n };\n\n element.on('click', listener);\n\n ctrl.$render = function() {\n element[0].checked = ctrl.$viewValue;\n };\n\n // Override the standard `$isEmpty` because the $viewValue of an empty checkbox is always set to `false`\n // This is because of the parser below, which compares the `$modelValue` with `trueValue` to convert\n // it to a boolean.\n ctrl.$isEmpty = function(value) {\n return value === false;\n };\n\n ctrl.$formatters.push(function(value) {\n return equals(value, trueValue);\n });\n\n ctrl.$parsers.push(function(value) {\n return value ? trueValue : falseValue;\n });\n}\n\n\n/**\n * @ngdoc directive\n * @name textarea\n * @restrict E\n *\n * @description\n * HTML textarea element control with angular data-binding. The data-binding and validation\n * properties of this element are exactly the same as those of the\n * {@link ng.directive:input input element}.\n *\n * @param {string} ngModel Assignable angular expression to data-bind to.\n * @param {string=} name Property name of the form under which the control is published.\n * @param {string=} required Sets `required` validation error key if the value is not entered.\n * @param {string=} ngRequired Adds `required` attribute and `required` validation constraint to\n * the element when the ngRequired expression evaluates to true. Use `ngRequired` instead of\n * `required` when you want to data-bind to the `required` attribute.\n * @param {number=} ngMinlength Sets `minlength` validation error key if the value is shorter than\n * minlength.\n * @param {number=} ngMaxlength Sets `maxlength` validation error key if the value is longer than\n * maxlength. Setting the attribute to a negative or non-numeric value, allows view values of any\n * length.\n * @param {string=} ngPattern Sets `pattern` validation error key if the ngModel {@link ngModel.NgModelController#$viewValue $viewValue}\n * does not match a RegExp found by evaluating the Angular expression given in the attribute value.\n * If the expression evaluates to a RegExp object, then this is used directly.\n * If the expression evaluates to a string, then it will be converted to a RegExp\n * after wrapping it in `^` and `$` characters. For instance, `\"abc\"` will be converted to\n * `new RegExp('^abc$')`.
\n * **Note:** Avoid using the `g` flag on the RegExp, as it will cause each successive search to\n * start at the index of the last search's match, thus not taking the whole input value into\n * account.\n * @param {string=} ngChange Angular expression to be executed when input changes due to user\n * interaction with the input element.\n * @param {boolean=} [ngTrim=true] If set to false Angular will not automatically trim the input.\n *\n * @knownIssue\n *\n * When specifying the `placeholder` attribute of `\n *
{{ list | json }}
\n * \n * \n * it(\"should split the text by newlines\", function() {\n * var listInput = element(by.model('list'));\n * var output = element(by.binding('list | json'));\n * listInput.sendKeys('abc\\ndef\\nghi');\n * expect(output.getText()).toContain('[\\n \"abc\",\\n \"def\",\\n \"ghi\"\\n]');\n * });\n * \n * \n *\n * @element input\n * @param {string=} ngList optional delimiter that should be used to split the value.\n */\nvar ngListDirective = function() {\n return {\n restrict: 'A',\n priority: 100,\n require: 'ngModel',\n link: function(scope, element, attr, ctrl) {\n var ngList = attr.ngList || ', ';\n var trimValues = attr.ngTrim !== 'false';\n var separator = trimValues ? trim(ngList) : ngList;\n\n var parse = function(viewValue) {\n // If the viewValue is invalid (say required but empty) it will be `undefined`\n if (isUndefined(viewValue)) return;\n\n var list = [];\n\n if (viewValue) {\n forEach(viewValue.split(separator), function(value) {\n if (value) list.push(trimValues ? trim(value) : value);\n });\n }\n\n return list;\n };\n\n ctrl.$parsers.push(parse);\n ctrl.$formatters.push(function(value) {\n if (isArray(value)) {\n return value.join(ngList);\n }\n\n return undefined;\n });\n\n // Override the standard $isEmpty because an empty array means the input is empty.\n ctrl.$isEmpty = function(value) {\n return !value || !value.length;\n };\n }\n };\n};\n\n/* global VALID_CLASS: true,\n INVALID_CLASS: true,\n PRISTINE_CLASS: true,\n DIRTY_CLASS: true,\n UNTOUCHED_CLASS: true,\n TOUCHED_CLASS: true,\n PENDING_CLASS: true,\n addSetValidityMethod: true,\n setupValidity: true,\n defaultModelOptions: false\n*/\n\n\nvar VALID_CLASS = 'ng-valid',\n INVALID_CLASS = 'ng-invalid',\n PRISTINE_CLASS = 'ng-pristine',\n DIRTY_CLASS = 'ng-dirty',\n UNTOUCHED_CLASS = 'ng-untouched',\n TOUCHED_CLASS = 'ng-touched',\n EMPTY_CLASS = 'ng-empty',\n NOT_EMPTY_CLASS = 'ng-not-empty';\n\nvar ngModelMinErr = minErr('ngModel');\n\n/**\n * @ngdoc type\n * @name ngModel.NgModelController\n *\n * @property {*} $viewValue The actual value from the control's view. For `input` elements, this is a\n * String. See {@link ngModel.NgModelController#$setViewValue} for information about when the $viewValue\n * is set.\n * @property {*} $modelValue The value in the model that the control is bound to.\n * @property {Array.} $parsers Array of functions to execute, as a pipeline, whenever\n the control reads value from the DOM. The functions are called in array order, each passing\n its return value through to the next. The last return value is forwarded to the\n {@link ngModel.NgModelController#$validators `$validators`} collection.\n\nParsers are used to sanitize / convert the {@link ngModel.NgModelController#$viewValue\n`$viewValue`}.\n\nReturning `undefined` from a parser means a parse error occurred. In that case,\nno {@link ngModel.NgModelController#$validators `$validators`} will run and the `ngModel`\nwill be set to `undefined` unless {@link ngModelOptions `ngModelOptions.allowInvalid`}\nis set to `true`. The parse error is stored in `ngModel.$error.parse`.\n\n *\n * @property {Array.} $formatters Array of functions to execute, as a pipeline, whenever\n the model value changes. The functions are called in reverse array order, each passing the value through to the\n next. The last return value is used as the actual DOM value.\n Used to format / convert values for display in the control.\n * ```js\n * function formatter(value) {\n * if (value) {\n * return value.toUpperCase();\n * }\n * }\n * ngModel.$formatters.push(formatter);\n * ```\n *\n * @property {Object.} $validators A collection of validators that are applied\n * whenever the model value changes. The key value within the object refers to the name of the\n * validator while the function refers to the validation operation. The validation operation is\n * provided with the model value as an argument and must return a true or false value depending\n * on the response of that validation.\n *\n * ```js\n * ngModel.$validators.validCharacters = function(modelValue, viewValue) {\n * var value = modelValue || viewValue;\n * return /[0-9]+/.test(value) &&\n * /[a-z]+/.test(value) &&\n * /[A-Z]+/.test(value) &&\n * /\\W+/.test(value);\n * };\n * ```\n *\n * @property {Object.} $asyncValidators A collection of validations that are expected to\n * perform an asynchronous validation (e.g. a HTTP request). The validation function that is provided\n * is expected to return a promise when it is run during the model validation process. Once the promise\n * is delivered then the validation status will be set to true when fulfilled and false when rejected.\n * When the asynchronous validators are triggered, each of the validators will run in parallel and the model\n * value will only be updated once all validators have been fulfilled. As long as an asynchronous validator\n * is unfulfilled, its key will be added to the controllers `$pending` property. Also, all asynchronous validators\n * will only run once all synchronous validators have passed.\n *\n * Please note that if $http is used then it is important that the server returns a success HTTP response code\n * in order to fulfill the validation and a status level of `4xx` in order to reject the validation.\n *\n * ```js\n * ngModel.$asyncValidators.uniqueUsername = function(modelValue, viewValue) {\n * var value = modelValue || viewValue;\n *\n * // Lookup user by username\n * return $http.get('/api/users/' + value).\n * then(function resolved() {\n * //username exists, this means validation fails\n * return $q.reject('exists');\n * }, function rejected() {\n * //username does not exist, therefore this validation passes\n * return true;\n * });\n * };\n * ```\n *\n * @property {Array.} $viewChangeListeners Array of functions to execute whenever the\n * view value has changed. It is called with no arguments, and its return value is ignored.\n * This can be used in place of additional $watches against the model value.\n *\n * @property {Object} $error An object hash with all failing validator ids as keys.\n * @property {Object} $pending An object hash with all pending validator ids as keys.\n *\n * @property {boolean} $untouched True if control has not lost focus yet.\n * @property {boolean} $touched True if control has lost focus.\n * @property {boolean} $pristine True if user has not interacted with the control yet.\n * @property {boolean} $dirty True if user has already interacted with the control.\n * @property {boolean} $valid True if there is no error.\n * @property {boolean} $invalid True if at least one error on the control.\n * @property {string} $name The name attribute of the control.\n *\n * @description\n *\n * `NgModelController` provides API for the {@link ngModel `ngModel`} directive.\n * The controller contains services for data-binding, validation, CSS updates, and value formatting\n * and parsing. It purposefully does not contain any logic which deals with DOM rendering or\n * listening to DOM events.\n * Such DOM related logic should be provided by other directives which make use of\n * `NgModelController` for data-binding to control elements.\n * Angular provides this DOM logic for most {@link input `input`} elements.\n * At the end of this page you can find a {@link ngModel.NgModelController#custom-control-example\n * custom control example} that uses `ngModelController` to bind to `contenteditable` elements.\n *\n * @example\n * ### Custom Control Example\n * This example shows how to use `NgModelController` with a custom control to achieve\n * data-binding. Notice how different directives (`contenteditable`, `ng-model`, and `required`)\n * collaborate together to achieve the desired result.\n *\n * `contenteditable` is an HTML5 attribute, which tells the browser to let the element\n * contents be edited in place by the user.\n *\n * We are using the {@link ng.service:$sce $sce} service here and include the {@link ngSanitize $sanitize}\n * module to automatically remove \"bad\" content like inline event listener (e.g. ``).\n * However, as we are using `$sce` the model can still decide to provide unsafe content if it marks\n * that content using the `$sce` service.\n *\n * \n \n [contenteditable] {\n border: 1px solid black;\n background-color: white;\n min-height: 20px;\n }\n\n .ng-invalid {\n border: 1px solid red;\n }\n\n \n \n angular.module('customControl', ['ngSanitize']).\n directive('contenteditable', ['$sce', function($sce) {\n return {\n restrict: 'A', // only activate on element attribute\n require: '?ngModel', // get a hold of NgModelController\n link: function(scope, element, attrs, ngModel) {\n if (!ngModel) return; // do nothing if no ng-model\n\n // Specify how UI should be updated\n ngModel.$render = function() {\n element.html($sce.getTrustedHtml(ngModel.$viewValue || ''));\n };\n\n // Listen for change events to enable binding\n element.on('blur keyup change', function() {\n scope.$evalAsync(read);\n });\n read(); // initialize\n\n // Write data to the model\n function read() {\n var html = element.html();\n // When we clear the content editable the browser leaves a
behind\n // If strip-br attribute is provided then we strip this out\n if (attrs.stripBr && html === '
') {\n html = '';\n }\n ngModel.$setViewValue(html);\n }\n }\n };\n }]);\n
\n \n
\n
Change me!
\n Required!\n
\n \n
\n
\n \n it('should data-bind and become invalid', function() {\n if (browser.params.browser === 'safari' || browser.params.browser === 'firefox') {\n // SafariDriver can't handle contenteditable\n // and Firefox driver can't clear contenteditables very well\n return;\n }\n var contentEditable = element(by.css('[contenteditable]'));\n var content = 'Change me!';\n\n expect(contentEditable.getText()).toEqual(content);\n\n contentEditable.clear();\n contentEditable.sendKeys(protractor.Key.BACK_SPACE);\n expect(contentEditable.getText()).toEqual('');\n expect(contentEditable.getAttribute('class')).toMatch(/ng-invalid-required/);\n });\n \n *
\n *\n *\n */\nNgModelController.$inject = ['$scope', '$exceptionHandler', '$attrs', '$element', '$parse', '$animate', '$timeout', '$q', '$interpolate'];\nfunction NgModelController($scope, $exceptionHandler, $attr, $element, $parse, $animate, $timeout, $q, $interpolate) {\n this.$viewValue = Number.NaN;\n this.$modelValue = Number.NaN;\n this.$$rawModelValue = undefined; // stores the parsed modelValue / model set from scope regardless of validity.\n this.$validators = {};\n this.$asyncValidators = {};\n this.$parsers = [];\n this.$formatters = [];\n this.$viewChangeListeners = [];\n this.$untouched = true;\n this.$touched = false;\n this.$pristine = true;\n this.$dirty = false;\n this.$valid = true;\n this.$invalid = false;\n this.$error = {}; // keep invalid keys here\n this.$$success = {}; // keep valid keys here\n this.$pending = undefined; // keep pending keys here\n this.$name = $interpolate($attr.name || '', false)($scope);\n this.$$parentForm = nullFormCtrl;\n this.$options = defaultModelOptions;\n\n this.$$parsedNgModel = $parse($attr.ngModel);\n this.$$parsedNgModelAssign = this.$$parsedNgModel.assign;\n this.$$ngModelGet = this.$$parsedNgModel;\n this.$$ngModelSet = this.$$parsedNgModelAssign;\n this.$$pendingDebounce = null;\n this.$$parserValid = undefined;\n\n this.$$currentValidationRunId = 0;\n\n this.$$scope = $scope;\n this.$$attr = $attr;\n this.$$element = $element;\n this.$$animate = $animate;\n this.$$timeout = $timeout;\n this.$$parse = $parse;\n this.$$q = $q;\n this.$$exceptionHandler = $exceptionHandler;\n\n setupValidity(this);\n setupModelWatcher(this);\n}\n\nNgModelController.prototype = {\n $$initGetterSetters: function() {\n if (this.$options.getOption('getterSetter')) {\n var invokeModelGetter = this.$$parse(this.$$attr.ngModel + '()'),\n invokeModelSetter = this.$$parse(this.$$attr.ngModel + '($$$p)');\n\n this.$$ngModelGet = function($scope) {\n var modelValue = this.$$parsedNgModel($scope);\n if (isFunction(modelValue)) {\n modelValue = invokeModelGetter($scope);\n }\n return modelValue;\n };\n this.$$ngModelSet = function($scope, newValue) {\n if (isFunction(this.$$parsedNgModel($scope))) {\n invokeModelSetter($scope, {$$$p: newValue});\n } else {\n this.$$parsedNgModelAssign($scope, newValue);\n }\n };\n } else if (!this.$$parsedNgModel.assign) {\n throw ngModelMinErr('nonassign', 'Expression \\'{0}\\' is non-assignable. Element: {1}',\n this.$$attr.ngModel, startingTag(this.$$element));\n }\n },\n\n\n /**\n * @ngdoc method\n * @name ngModel.NgModelController#$render\n *\n * @description\n * Called when the view needs to be updated. It is expected that the user of the ng-model\n * directive will implement this method.\n *\n * The `$render()` method is invoked in the following situations:\n *\n * * `$rollbackViewValue()` is called. If we are rolling back the view value to the last\n * committed value then `$render()` is called to update the input control.\n * * The value referenced by `ng-model` is changed programmatically and both the `$modelValue` and\n * the `$viewValue` are different from last time.\n *\n * Since `ng-model` does not do a deep watch, `$render()` is only invoked if the values of\n * `$modelValue` and `$viewValue` are actually different from their previous values. If `$modelValue`\n * or `$viewValue` are objects (rather than a string or number) then `$render()` will not be\n * invoked if you only change a property on the objects.\n */\n $render: noop,\n\n /**\n * @ngdoc method\n * @name ngModel.NgModelController#$isEmpty\n *\n * @description\n * This is called when we need to determine if the value of an input is empty.\n *\n * For instance, the required directive does this to work out if the input has data or not.\n *\n * The default `$isEmpty` function checks whether the value is `undefined`, `''`, `null` or `NaN`.\n *\n * You can override this for input directives whose concept of being empty is different from the\n * default. The `checkboxInputType` directive does this because in its case a value of `false`\n * implies empty.\n *\n * @param {*} value The value of the input to check for emptiness.\n * @returns {boolean} True if `value` is \"empty\".\n */\n $isEmpty: function(value) {\n // eslint-disable-next-line no-self-compare\n return isUndefined(value) || value === '' || value === null || value !== value;\n },\n\n $$updateEmptyClasses: function(value) {\n if (this.$isEmpty(value)) {\n this.$$animate.removeClass(this.$$element, NOT_EMPTY_CLASS);\n this.$$animate.addClass(this.$$element, EMPTY_CLASS);\n } else {\n this.$$animate.removeClass(this.$$element, EMPTY_CLASS);\n this.$$animate.addClass(this.$$element, NOT_EMPTY_CLASS);\n }\n },\n\n /**\n * @ngdoc method\n * @name ngModel.NgModelController#$setPristine\n *\n * @description\n * Sets the control to its pristine state.\n *\n * This method can be called to remove the `ng-dirty` class and set the control to its pristine\n * state (`ng-pristine` class). A model is considered to be pristine when the control\n * has not been changed from when first compiled.\n */\n $setPristine: function() {\n this.$dirty = false;\n this.$pristine = true;\n this.$$animate.removeClass(this.$$element, DIRTY_CLASS);\n this.$$animate.addClass(this.$$element, PRISTINE_CLASS);\n },\n\n /**\n * @ngdoc method\n * @name ngModel.NgModelController#$setDirty\n *\n * @description\n * Sets the control to its dirty state.\n *\n * This method can be called to remove the `ng-pristine` class and set the control to its dirty\n * state (`ng-dirty` class). A model is considered to be dirty when the control has been changed\n * from when first compiled.\n */\n $setDirty: function() {\n this.$dirty = true;\n this.$pristine = false;\n this.$$animate.removeClass(this.$$element, PRISTINE_CLASS);\n this.$$animate.addClass(this.$$element, DIRTY_CLASS);\n this.$$parentForm.$setDirty();\n },\n\n /**\n * @ngdoc method\n * @name ngModel.NgModelController#$setUntouched\n *\n * @description\n * Sets the control to its untouched state.\n *\n * This method can be called to remove the `ng-touched` class and set the control to its\n * untouched state (`ng-untouched` class). Upon compilation, a model is set as untouched\n * by default, however this function can be used to restore that state if the model has\n * already been touched by the user.\n */\n $setUntouched: function() {\n this.$touched = false;\n this.$untouched = true;\n this.$$animate.setClass(this.$$element, UNTOUCHED_CLASS, TOUCHED_CLASS);\n },\n\n /**\n * @ngdoc method\n * @name ngModel.NgModelController#$setTouched\n *\n * @description\n * Sets the control to its touched state.\n *\n * This method can be called to remove the `ng-untouched` class and set the control to its\n * touched state (`ng-touched` class). A model is considered to be touched when the user has\n * first focused the control element and then shifted focus away from the control (blur event).\n */\n $setTouched: function() {\n this.$touched = true;\n this.$untouched = false;\n this.$$animate.setClass(this.$$element, TOUCHED_CLASS, UNTOUCHED_CLASS);\n },\n\n /**\n * @ngdoc method\n * @name ngModel.NgModelController#$rollbackViewValue\n *\n * @description\n * Cancel an update and reset the input element's value to prevent an update to the `$modelValue`,\n * which may be caused by a pending debounced event or because the input is waiting for some\n * future event.\n *\n * If you have an input that uses `ng-model-options` to set up debounced updates or updates that\n * depend on special events such as `blur`, there can be a period when the `$viewValue` is out of\n * sync with the ngModel's `$modelValue`.\n *\n * In this case, you can use `$rollbackViewValue()` to manually cancel the debounced / future update\n * and reset the input to the last committed view value.\n *\n * It is also possible that you run into difficulties if you try to update the ngModel's `$modelValue`\n * programmatically before these debounced/future events have resolved/occurred, because Angular's\n * dirty checking mechanism is not able to tell whether the model has actually changed or not.\n *\n * The `$rollbackViewValue()` method should be called before programmatically changing the model of an\n * input which may have such events pending. This is important in order to make sure that the\n * input field will be updated with the new model value and any pending operations are cancelled.\n *\n * \n * \n * angular.module('cancel-update-example', [])\n *\n * .controller('CancelUpdateController', ['$scope', function($scope) {\n * $scope.model = {value1: '', value2: ''};\n *\n * $scope.setEmpty = function(e, value, rollback) {\n * if (e.keyCode === 27) {\n * e.preventDefault();\n * if (rollback) {\n * $scope.myForm[value].$rollbackViewValue();\n * }\n * $scope.model[value] = '';\n * }\n * };\n * }]);\n * \n * \n *
\n *

Both of these inputs are only updated if they are blurred. Hitting escape should\n * empty them. Follow these steps and observe the difference:

\n *
    \n *
  1. Type something in the input. You will see that the model is not yet updated
  2. \n *
  3. Press the Escape key.\n *
      \n *
    1. In the first example, nothing happens, because the model is already '', and no\n * update is detected. If you blur the input, the model will be set to the current view.\n *
    2. \n *
    3. In the second example, the pending update is cancelled, and the input is set back\n * to the last committed view value (''). Blurring the input does nothing.\n *
    4. \n *
    \n *
  4. \n *
\n *\n *
\n *
\n *

Without $rollbackViewValue():

\n * \n * value1: \"{{ model.value1 }}\"\n *
\n *\n *
\n *

With $rollbackViewValue():

\n * \n * value2: \"{{ model.value2 }}\"\n *
\n *
\n *
\n *
\n \n div {\n display: table-cell;\n }\n div:nth-child(1) {\n padding-right: 30px;\n }\n\n \n *
\n */\n $rollbackViewValue: function() {\n this.$$timeout.cancel(this.$$pendingDebounce);\n this.$viewValue = this.$$lastCommittedViewValue;\n this.$render();\n },\n\n /**\n * @ngdoc method\n * @name ngModel.NgModelController#$validate\n *\n * @description\n * Runs each of the registered validators (first synchronous validators and then\n * asynchronous validators).\n * If the validity changes to invalid, the model will be set to `undefined`,\n * unless {@link ngModelOptions `ngModelOptions.allowInvalid`} is `true`.\n * If the validity changes to valid, it will set the model to the last available valid\n * `$modelValue`, i.e. either the last parsed value or the last value set from the scope.\n */\n $validate: function() {\n // ignore $validate before model is initialized\n if (isNumberNaN(this.$modelValue)) {\n return;\n }\n\n var viewValue = this.$$lastCommittedViewValue;\n // Note: we use the $$rawModelValue as $modelValue might have been\n // set to undefined during a view -> model update that found validation\n // errors. We can't parse the view here, since that could change\n // the model although neither viewValue nor the model on the scope changed\n var modelValue = this.$$rawModelValue;\n\n var prevValid = this.$valid;\n var prevModelValue = this.$modelValue;\n\n var allowInvalid = this.$options.getOption('allowInvalid');\n\n var that = this;\n this.$$runValidators(modelValue, viewValue, function(allValid) {\n // If there was no change in validity, don't update the model\n // This prevents changing an invalid modelValue to undefined\n if (!allowInvalid && prevValid !== allValid) {\n // Note: Don't check this.$valid here, as we could have\n // external validators (e.g. calculated on the server),\n // that just call $setValidity and need the model value\n // to calculate their validity.\n that.$modelValue = allValid ? modelValue : undefined;\n\n if (that.$modelValue !== prevModelValue) {\n that.$$writeModelToScope();\n }\n }\n });\n },\n\n $$runValidators: function(modelValue, viewValue, doneCallback) {\n this.$$currentValidationRunId++;\n var localValidationRunId = this.$$currentValidationRunId;\n var that = this;\n\n // check parser error\n if (!processParseErrors()) {\n validationDone(false);\n return;\n }\n if (!processSyncValidators()) {\n validationDone(false);\n return;\n }\n processAsyncValidators();\n\n function processParseErrors() {\n var errorKey = that.$$parserName || 'parse';\n if (isUndefined(that.$$parserValid)) {\n setValidity(errorKey, null);\n } else {\n if (!that.$$parserValid) {\n forEach(that.$validators, function(v, name) {\n setValidity(name, null);\n });\n forEach(that.$asyncValidators, function(v, name) {\n setValidity(name, null);\n });\n }\n // Set the parse error last, to prevent unsetting it, should a $validators key == parserName\n setValidity(errorKey, that.$$parserValid);\n return that.$$parserValid;\n }\n return true;\n }\n\n function processSyncValidators() {\n var syncValidatorsValid = true;\n forEach(that.$validators, function(validator, name) {\n var result = Boolean(validator(modelValue, viewValue));\n syncValidatorsValid = syncValidatorsValid && result;\n setValidity(name, result);\n });\n if (!syncValidatorsValid) {\n forEach(that.$asyncValidators, function(v, name) {\n setValidity(name, null);\n });\n return false;\n }\n return true;\n }\n\n function processAsyncValidators() {\n var validatorPromises = [];\n var allValid = true;\n forEach(that.$asyncValidators, function(validator, name) {\n var promise = validator(modelValue, viewValue);\n if (!isPromiseLike(promise)) {\n throw ngModelMinErr('nopromise',\n 'Expected asynchronous validator to return a promise but got \\'{0}\\' instead.', promise);\n }\n setValidity(name, undefined);\n validatorPromises.push(promise.then(function() {\n setValidity(name, true);\n }, function() {\n allValid = false;\n setValidity(name, false);\n }));\n });\n if (!validatorPromises.length) {\n validationDone(true);\n } else {\n that.$$q.all(validatorPromises).then(function() {\n validationDone(allValid);\n }, noop);\n }\n }\n\n function setValidity(name, isValid) {\n if (localValidationRunId === that.$$currentValidationRunId) {\n that.$setValidity(name, isValid);\n }\n }\n\n function validationDone(allValid) {\n if (localValidationRunId === that.$$currentValidationRunId) {\n\n doneCallback(allValid);\n }\n }\n },\n\n /**\n * @ngdoc method\n * @name ngModel.NgModelController#$commitViewValue\n *\n * @description\n * Commit a pending update to the `$modelValue`.\n *\n * Updates may be pending by a debounced event or because the input is waiting for a some future\n * event defined in `ng-model-options`. this method is rarely needed as `NgModelController`\n * usually handles calling this in response to input events.\n */\n $commitViewValue: function() {\n var viewValue = this.$viewValue;\n\n this.$$timeout.cancel(this.$$pendingDebounce);\n\n // If the view value has not changed then we should just exit, except in the case where there is\n // a native validator on the element. In this case the validation state may have changed even though\n // the viewValue has stayed empty.\n if (this.$$lastCommittedViewValue === viewValue && (viewValue !== '' || !this.$$hasNativeValidators)) {\n return;\n }\n this.$$updateEmptyClasses(viewValue);\n this.$$lastCommittedViewValue = viewValue;\n\n // change to dirty\n if (this.$pristine) {\n this.$setDirty();\n }\n this.$$parseAndValidate();\n },\n\n $$parseAndValidate: function() {\n var viewValue = this.$$lastCommittedViewValue;\n var modelValue = viewValue;\n var that = this;\n\n this.$$parserValid = isUndefined(modelValue) ? undefined : true;\n\n if (this.$$parserValid) {\n for (var i = 0; i < this.$parsers.length; i++) {\n modelValue = this.$parsers[i](modelValue);\n if (isUndefined(modelValue)) {\n this.$$parserValid = false;\n break;\n }\n }\n }\n if (isNumberNaN(this.$modelValue)) {\n // this.$modelValue has not been touched yet...\n this.$modelValue = this.$$ngModelGet(this.$$scope);\n }\n var prevModelValue = this.$modelValue;\n var allowInvalid = this.$options.getOption('allowInvalid');\n this.$$rawModelValue = modelValue;\n\n if (allowInvalid) {\n this.$modelValue = modelValue;\n writeToModelIfNeeded();\n }\n\n // Pass the $$lastCommittedViewValue here, because the cached viewValue might be out of date.\n // This can happen if e.g. $setViewValue is called from inside a parser\n this.$$runValidators(modelValue, this.$$lastCommittedViewValue, function(allValid) {\n if (!allowInvalid) {\n // Note: Don't check this.$valid here, as we could have\n // external validators (e.g. calculated on the server),\n // that just call $setValidity and need the model value\n // to calculate their validity.\n that.$modelValue = allValid ? modelValue : undefined;\n writeToModelIfNeeded();\n }\n });\n\n function writeToModelIfNeeded() {\n if (that.$modelValue !== prevModelValue) {\n that.$$writeModelToScope();\n }\n }\n },\n\n $$writeModelToScope: function() {\n this.$$ngModelSet(this.$$scope, this.$modelValue);\n forEach(this.$viewChangeListeners, function(listener) {\n try {\n listener();\n } catch (e) {\n // eslint-disable-next-line no-invalid-this\n this.$$exceptionHandler(e);\n }\n }, this);\n },\n\n /**\n * @ngdoc method\n * @name ngModel.NgModelController#$setViewValue\n *\n * @description\n * Update the view value.\n *\n * This method should be called when a control wants to change the view value; typically,\n * this is done from within a DOM event handler. For example, the {@link ng.directive:input input}\n * directive calls it when the value of the input changes and {@link ng.directive:select select}\n * calls it when an option is selected.\n *\n * When `$setViewValue` is called, the new `value` will be staged for committing through the `$parsers`\n * and `$validators` pipelines. If there are no special {@link ngModelOptions} specified then the staged\n * value sent directly for processing, finally to be applied to `$modelValue` and then the\n * **expression** specified in the `ng-model` attribute. Lastly, all the registered change listeners,\n * in the `$viewChangeListeners` list, are called.\n *\n * In case the {@link ng.directive:ngModelOptions ngModelOptions} directive is used with `updateOn`\n * and the `default` trigger is not listed, all those actions will remain pending until one of the\n * `updateOn` events is triggered on the DOM element.\n * All these actions will be debounced if the {@link ng.directive:ngModelOptions ngModelOptions}\n * directive is used with a custom debounce for this particular event.\n * Note that a `$digest` is only triggered once the `updateOn` events are fired, or if `debounce`\n * is specified, once the timer runs out.\n *\n * When used with standard inputs, the view value will always be a string (which is in some cases\n * parsed into another type, such as a `Date` object for `input[date]`.)\n * However, custom controls might also pass objects to this method. In this case, we should make\n * a copy of the object before passing it to `$setViewValue`. This is because `ngModel` does not\n * perform a deep watch of objects, it only looks for a change of identity. If you only change\n * the property of the object then ngModel will not realize that the object has changed and\n * will not invoke the `$parsers` and `$validators` pipelines. For this reason, you should\n * not change properties of the copy once it has been passed to `$setViewValue`.\n * Otherwise you may cause the model value on the scope to change incorrectly.\n *\n *
\n * In any case, the value passed to the method should always reflect the current value\n * of the control. For example, if you are calling `$setViewValue` for an input element,\n * you should pass the input DOM value. Otherwise, the control and the scope model become\n * out of sync. It's also important to note that `$setViewValue` does not call `$render` or change\n * the control's DOM value in any way. If we want to change the control's DOM value\n * programmatically, we should update the `ngModel` scope expression. Its new value will be\n * picked up by the model controller, which will run it through the `$formatters`, `$render` it\n * to update the DOM, and finally call `$validate` on it.\n *
\n *\n * @param {*} value value from the view.\n * @param {string} trigger Event that triggered the update.\n */\n $setViewValue: function(value, trigger) {\n this.$viewValue = value;\n if (this.$options.getOption('updateOnDefault')) {\n this.$$debounceViewValueCommit(trigger);\n }\n },\n\n $$debounceViewValueCommit: function(trigger) {\n var debounceDelay = this.$options.getOption('debounce');\n\n if (isNumber(debounceDelay[trigger])) {\n debounceDelay = debounceDelay[trigger];\n } else if (isNumber(debounceDelay['default'])) {\n debounceDelay = debounceDelay['default'];\n }\n\n this.$$timeout.cancel(this.$$pendingDebounce);\n var that = this;\n if (debounceDelay > 0) { // this fails if debounceDelay is an object\n this.$$pendingDebounce = this.$$timeout(function() {\n that.$commitViewValue();\n }, debounceDelay);\n } else if (this.$$scope.$root.$$phase) {\n this.$commitViewValue();\n } else {\n this.$$scope.$apply(function() {\n that.$commitViewValue();\n });\n }\n }\n};\n\nfunction setupModelWatcher(ctrl) {\n // model -> value\n // Note: we cannot use a normal scope.$watch as we want to detect the following:\n // 1. scope value is 'a'\n // 2. user enters 'b'\n // 3. ng-change kicks in and reverts scope value to 'a'\n // -> scope value did not change since the last digest as\n // ng-change executes in apply phase\n // 4. view should be changed back to 'a'\n ctrl.$$scope.$watch(function ngModelWatch() {\n var modelValue = ctrl.$$ngModelGet(ctrl.$$scope);\n\n // if scope model value and ngModel value are out of sync\n // TODO(perf): why not move this to the action fn?\n if (modelValue !== ctrl.$modelValue &&\n // checks for NaN is needed to allow setting the model to NaN when there's an asyncValidator\n // eslint-disable-next-line no-self-compare\n (ctrl.$modelValue === ctrl.$modelValue || modelValue === modelValue)\n ) {\n ctrl.$modelValue = ctrl.$$rawModelValue = modelValue;\n ctrl.$$parserValid = undefined;\n\n var formatters = ctrl.$formatters,\n idx = formatters.length;\n\n var viewValue = modelValue;\n while (idx--) {\n viewValue = formatters[idx](viewValue);\n }\n if (ctrl.$viewValue !== viewValue) {\n ctrl.$$updateEmptyClasses(viewValue);\n ctrl.$viewValue = ctrl.$$lastCommittedViewValue = viewValue;\n ctrl.$render();\n\n // It is possible that model and view value have been updated during render\n ctrl.$$runValidators(ctrl.$modelValue, ctrl.$viewValue, noop);\n }\n }\n\n return modelValue;\n });\n}\n\n/**\n * @ngdoc method\n * @name ngModel.NgModelController#$setValidity\n *\n * @description\n * Change the validity state, and notify the form.\n *\n * This method can be called within $parsers/$formatters or a custom validation implementation.\n * However, in most cases it should be sufficient to use the `ngModel.$validators` and\n * `ngModel.$asyncValidators` collections which will call `$setValidity` automatically.\n *\n * @param {string} validationErrorKey Name of the validator. The `validationErrorKey` will be assigned\n * to either `$error[validationErrorKey]` or `$pending[validationErrorKey]`\n * (for unfulfilled `$asyncValidators`), so that it is available for data-binding.\n * The `validationErrorKey` should be in camelCase and will get converted into dash-case\n * for class name. Example: `myError` will result in `ng-valid-my-error` and `ng-invalid-my-error`\n * class and can be bound to as `{{someForm.someControl.$error.myError}}` .\n * @param {boolean} isValid Whether the current state is valid (true), invalid (false), pending (undefined),\n * or skipped (null). Pending is used for unfulfilled `$asyncValidators`.\n * Skipped is used by Angular when validators do not run because of parse errors and\n * when `$asyncValidators` do not run because any of the `$validators` failed.\n */\naddSetValidityMethod({\n clazz: NgModelController,\n set: function(object, property) {\n object[property] = true;\n },\n unset: function(object, property) {\n delete object[property];\n }\n});\n\n\n/**\n * @ngdoc directive\n * @name ngModel\n *\n * @element input\n * @priority 1\n *\n * @description\n * The `ngModel` directive binds an `input`,`select`, `textarea` (or custom form control) to a\n * property on the scope using {@link ngModel.NgModelController NgModelController},\n * which is created and exposed by this directive.\n *\n * `ngModel` is responsible for:\n *\n * - Binding the view into the model, which other directives such as `input`, `textarea` or `select`\n * require.\n * - Providing validation behavior (i.e. required, number, email, url).\n * - Keeping the state of the control (valid/invalid, dirty/pristine, touched/untouched, validation errors).\n * - Setting related css classes on the element (`ng-valid`, `ng-invalid`, `ng-dirty`, `ng-pristine`, `ng-touched`,\n * `ng-untouched`, `ng-empty`, `ng-not-empty`) including animations.\n * - Registering the control with its parent {@link ng.directive:form form}.\n *\n * Note: `ngModel` will try to bind to the property given by evaluating the expression on the\n * current scope. If the property doesn't already exist on this scope, it will be created\n * implicitly and added to the scope.\n *\n * For best practices on using `ngModel`, see:\n *\n * - [Understanding Scopes](https://github.com/angular/angular.js/wiki/Understanding-Scopes)\n *\n * For basic examples, how to use `ngModel`, see:\n *\n * - {@link ng.directive:input input}\n * - {@link input[text] text}\n * - {@link input[checkbox] checkbox}\n * - {@link input[radio] radio}\n * - {@link input[number] number}\n * - {@link input[email] email}\n * - {@link input[url] url}\n * - {@link input[date] date}\n * - {@link input[datetime-local] datetime-local}\n * - {@link input[time] time}\n * - {@link input[month] month}\n * - {@link input[week] week}\n * - {@link ng.directive:select select}\n * - {@link ng.directive:textarea textarea}\n *\n * # Complex Models (objects or collections)\n *\n * By default, `ngModel` watches the model by reference, not value. This is important to know when\n * binding inputs to models that are objects (e.g. `Date`) or collections (e.g. arrays). If only properties of the\n * object or collection change, `ngModel` will not be notified and so the input will not be re-rendered.\n *\n * The model must be assigned an entirely new object or collection before a re-rendering will occur.\n *\n * Some directives have options that will cause them to use a custom `$watchCollection` on the model expression\n * - for example, `ngOptions` will do so when a `track by` clause is included in the comprehension expression or\n * if the select is given the `multiple` attribute.\n *\n * The `$watchCollection()` method only does a shallow comparison, meaning that changing properties deeper than the\n * first level of the object (or only changing the properties of an item in the collection if it's an array) will still\n * not trigger a re-rendering of the model.\n *\n * # CSS classes\n * The following CSS classes are added and removed on the associated input/select/textarea element\n * depending on the validity of the model.\n *\n * - `ng-valid`: the model is valid\n * - `ng-invalid`: the model is invalid\n * - `ng-valid-[key]`: for each valid key added by `$setValidity`\n * - `ng-invalid-[key]`: for each invalid key added by `$setValidity`\n * - `ng-pristine`: the control hasn't been interacted with yet\n * - `ng-dirty`: the control has been interacted with\n * - `ng-touched`: the control has been blurred\n * - `ng-untouched`: the control hasn't been blurred\n * - `ng-pending`: any `$asyncValidators` are unfulfilled\n * - `ng-empty`: the view does not contain a value or the value is deemed \"empty\", as defined\n * by the {@link ngModel.NgModelController#$isEmpty} method\n * - `ng-not-empty`: the view contains a non-empty value\n *\n * Keep in mind that ngAnimate can detect each of these classes when added and removed.\n *\n * ## Animation Hooks\n *\n * Animations within models are triggered when any of the associated CSS classes are added and removed\n * on the input element which is attached to the model. These classes include: `.ng-pristine`, `.ng-dirty`,\n * `.ng-invalid` and `.ng-valid` as well as any other validations that are performed on the model itself.\n * The animations that are triggered within ngModel are similar to how they work in ngClass and\n * animations can be hooked into using CSS transitions, keyframes as well as JS animations.\n *\n * The following example shows a simple way to utilize CSS transitions to style an input element\n * that has been rendered as invalid after it has been validated:\n *\n *
\n * //be sure to include ngAnimate as a module to hook into more\n * //advanced animations\n * .my-input {\n *   transition:0.5s linear all;\n *   background: white;\n * }\n * .my-input.ng-invalid {\n *   background: red;\n *   color:white;\n * }\n * 
\n *\n * @example\n * \n \n \n \n

\n Update input to see transitions when valid/invalid.\n Integer is a valid value.\n

\n
\n \n
\n
\n *
\n *\n * ## Binding to a getter/setter\n *\n * Sometimes it's helpful to bind `ngModel` to a getter/setter function. A getter/setter is a\n * function that returns a representation of the model when called with zero arguments, and sets\n * the internal state of a model when called with an argument. It's sometimes useful to use this\n * for models that have an internal representation that's different from what the model exposes\n * to the view.\n *\n *
\n * **Best Practice:** It's best to keep getters fast because Angular is likely to call them more\n * frequently than other parts of your code.\n *
\n *\n * You use this behavior by adding `ng-model-options=\"{ getterSetter: true }\"` to an element that\n * has `ng-model` attached to it. You can also add `ng-model-options=\"{ getterSetter: true }\"` to\n * a `
`, which will enable this behavior for all ``s within it. See\n * {@link ng.directive:ngModelOptions `ngModelOptions`} for more.\n *\n * The following example shows how to use `ngModel` with a getter/setter:\n *\n * @example\n * \n \n
\n \n \n \n
user.name = 
\n
\n
\n \n angular.module('getterSetterExample', [])\n .controller('ExampleController', ['$scope', function($scope) {\n var _name = 'Brian';\n $scope.user = {\n name: function(newName) {\n // Note that newName can be undefined for two reasons:\n // 1. Because it is called as a getter and thus called with no arguments\n // 2. Because the property should actually be set to undefined. This happens e.g. if the\n // input is invalid\n return arguments.length ? (_name = newName) : _name;\n }\n };\n }]);\n \n *
\n */\nvar ngModelDirective = ['$rootScope', function($rootScope) {\n return {\n restrict: 'A',\n require: ['ngModel', '^?form', '^?ngModelOptions'],\n controller: NgModelController,\n // Prelink needs to run before any input directive\n // so that we can set the NgModelOptions in NgModelController\n // before anyone else uses it.\n priority: 1,\n compile: function ngModelCompile(element) {\n // Setup initial state of the control\n element.addClass(PRISTINE_CLASS).addClass(UNTOUCHED_CLASS).addClass(VALID_CLASS);\n\n return {\n pre: function ngModelPreLink(scope, element, attr, ctrls) {\n var modelCtrl = ctrls[0],\n formCtrl = ctrls[1] || modelCtrl.$$parentForm,\n optionsCtrl = ctrls[2];\n\n if (optionsCtrl) {\n modelCtrl.$options = optionsCtrl.$options;\n }\n\n modelCtrl.$$initGetterSetters();\n\n // notify others, especially parent forms\n formCtrl.$addControl(modelCtrl);\n\n attr.$observe('name', function(newValue) {\n if (modelCtrl.$name !== newValue) {\n modelCtrl.$$parentForm.$$renameControl(modelCtrl, newValue);\n }\n });\n\n scope.$on('$destroy', function() {\n modelCtrl.$$parentForm.$removeControl(modelCtrl);\n });\n },\n post: function ngModelPostLink(scope, element, attr, ctrls) {\n var modelCtrl = ctrls[0];\n if (modelCtrl.$options.getOption('updateOn')) {\n element.on(modelCtrl.$options.getOption('updateOn'), function(ev) {\n modelCtrl.$$debounceViewValueCommit(ev && ev.type);\n });\n }\n\n function setTouched() {\n modelCtrl.$setTouched();\n }\n\n element.on('blur', function() {\n if (modelCtrl.$touched) return;\n\n if ($rootScope.$$phase) {\n scope.$evalAsync(setTouched);\n } else {\n scope.$apply(setTouched);\n }\n });\n }\n };\n }\n };\n}];\n\n/* exported defaultModelOptions */\nvar defaultModelOptions;\nvar DEFAULT_REGEXP = /(\\s+|^)default(\\s+|$)/;\n\n/**\n * @ngdoc type\n * @name ModelOptions\n * @description\n * A container for the options set by the {@link ngModelOptions} directive\n */\nfunction ModelOptions(options) {\n this.$$options = options;\n}\n\nModelOptions.prototype = {\n\n /**\n * @ngdoc method\n * @name ModelOptions#getOption\n * @param {string} name the name of the option to retrieve\n * @returns {*} the value of the option\n * @description\n * Returns the value of the given option\n */\n getOption: function(name) {\n return this.$$options[name];\n },\n\n /**\n * @ngdoc method\n * @name ModelOptions#createChild\n * @param {Object} options a hash of options for the new child that will override the parent's options\n * @return {ModelOptions} a new `ModelOptions` object initialized with the given options.\n */\n createChild: function(options) {\n var inheritAll = false;\n\n // make a shallow copy\n options = extend({}, options);\n\n // Inherit options from the parent if specified by the value `\"$inherit\"`\n forEach(options, /* @this */ function(option, key) {\n if (option === '$inherit') {\n if (key === '*') {\n inheritAll = true;\n } else {\n options[key] = this.$$options[key];\n // `updateOn` is special so we must also inherit the `updateOnDefault` option\n if (key === 'updateOn') {\n options.updateOnDefault = this.$$options.updateOnDefault;\n }\n }\n } else {\n if (key === 'updateOn') {\n // If the `updateOn` property contains the `default` event then we have to remove\n // it from the event list and set the `updateOnDefault` flag.\n options.updateOnDefault = false;\n options[key] = trim(option.replace(DEFAULT_REGEXP, function() {\n options.updateOnDefault = true;\n return ' ';\n }));\n }\n }\n }, this);\n\n if (inheritAll) {\n // We have a property of the form: `\"*\": \"$inherit\"`\n delete options['*'];\n defaults(options, this.$$options);\n }\n\n // Finally add in any missing defaults\n defaults(options, defaultModelOptions.$$options);\n\n return new ModelOptions(options);\n }\n};\n\n\ndefaultModelOptions = new ModelOptions({\n updateOn: '',\n updateOnDefault: true,\n debounce: 0,\n getterSetter: false,\n allowInvalid: false,\n timezone: null\n});\n\n\n/**\n * @ngdoc directive\n * @name ngModelOptions\n *\n * @description\n * This directive allows you to modify the behaviour of {@link ngModel} directives within your\n * application. You can specify an `ngModelOptions` directive on any element. All {@link ngModel}\n * directives will use the options of their nearest `ngModelOptions` ancestor.\n *\n * The `ngModelOptions` settings are found by evaluating the value of the attribute directive as\n * an Angular expression. This expression should evaluate to an object, whose properties contain\n * the settings. For example: `
\n *
\n * \n *
\n *
\n * ```\n *\n * the `input` element will have the following settings\n *\n * ```js\n * { allowInvalid: true, updateOn: 'default', debounce: 0 }\n * ```\n *\n * Notice that the `debounce` setting was not inherited and used the default value instead.\n *\n * You can specify that all undefined settings are automatically inherited from an ancestor by\n * including a property with key of `\"*\"` and value of `\"$inherit\"`.\n *\n * For example given the following fragment of HTML\n *\n *\n * ```html\n *
\n *
\n * \n *
\n *
\n * ```\n *\n * the `input` element will have the following settings\n *\n * ```js\n * { allowInvalid: true, updateOn: 'default', debounce: 200 }\n * ```\n *\n * Notice that the `debounce` setting now inherits the value from the outer `
` element.\n *\n * If you are creating a reusable component then you should be careful when using `\"*\": \"$inherit\"`\n * since you may inadvertently inherit a setting in the future that changes the behavior of your component.\n *\n *\n * ## Triggering and debouncing model updates\n *\n * The `updateOn` and `debounce` properties allow you to specify a custom list of events that will\n * trigger a model update and/or a debouncing delay so that the actual update only takes place when\n * a timer expires; this timer will be reset after another change takes place.\n *\n * Given the nature of `ngModelOptions`, the value displayed inside input fields in the view might\n * be different from the value in the actual model. This means that if you update the model you\n * should also invoke {@link ngModel.NgModelController#$rollbackViewValue} on the relevant input field in\n * order to make sure it is synchronized with the model and that any debounced action is canceled.\n *\n * The easiest way to reference the control's {@link ngModel.NgModelController#$rollbackViewValue}\n * method is by making sure the input is placed inside a form that has a `name` attribute. This is\n * important because `form` controllers are published to the related scope under the name in their\n * `name` attribute.\n *\n * Any pending changes will take place immediately when an enclosing form is submitted via the\n * `submit` event. Note that `ngClick` events will occur before the model is updated. Use `ngSubmit`\n * to have access to the updated model.\n *\n * The following example shows how to override immediate updates. Changes on the inputs within the\n * form will update the model only when the control loses focus (blur event). If `escape` key is\n * pressed while the input field is focused, the value is reset to the value in the current model.\n *\n * \n * \n *
\n *
\n *
\n *
\n *
\n *
user.name = 
\n *
\n *
\n * \n * angular.module('optionsExample', [])\n * .controller('ExampleController', ['$scope', function($scope) {\n * $scope.user = { name: 'say', data: '' };\n *\n * $scope.cancel = function(e) {\n * if (e.keyCode === 27) {\n * $scope.userForm.userName.$rollbackViewValue();\n * }\n * };\n * }]);\n * \n * \n * var model = element(by.binding('user.name'));\n * var input = element(by.model('user.name'));\n * var other = element(by.model('user.data'));\n *\n * it('should allow custom events', function() {\n * input.sendKeys(' hello');\n * input.click();\n * expect(model.getText()).toEqual('say');\n * other.click();\n * expect(model.getText()).toEqual('say hello');\n * });\n *\n * it('should $rollbackViewValue when model changes', function() {\n * input.sendKeys(' hello');\n * expect(input.getAttribute('value')).toEqual('say hello');\n * input.sendKeys(protractor.Key.ESCAPE);\n * expect(input.getAttribute('value')).toEqual('say');\n * other.click();\n * expect(model.getText()).toEqual('say');\n * });\n * \n *
\n *\n * The next example shows how to debounce model changes. Model will be updated only 1 sec after last change.\n * If the `Clear` button is pressed, any debounced action is canceled and the value becomes empty.\n *\n * \n * \n *
\n *
\n * Name:\n * \n *
\n *
\n *
user.name = 
\n *
\n *
\n * \n * angular.module('optionsExample', [])\n * .controller('ExampleController', ['$scope', function($scope) {\n * $scope.user = { name: 'say' };\n * }]);\n * \n *
\n *\n * ## Model updates and validation\n *\n * The default behaviour in `ngModel` is that the model value is set to `undefined` when the\n * validation determines that the value is invalid. By setting the `allowInvalid` property to true,\n * the model will still be updated even if the value is invalid.\n *\n *\n * ## Connecting to the scope\n *\n * By setting the `getterSetter` property to true you are telling ngModel that the `ngModel` expression\n * on the scope refers to a \"getter/setter\" function rather than the value itself.\n *\n * The following example shows how to bind to getter/setters:\n *\n * \n * \n *
\n *
\n * \n *
\n *
user.name = 
\n *
\n *
\n * \n * angular.module('getterSetterExample', [])\n * .controller('ExampleController', ['$scope', function($scope) {\n * var _name = 'Brian';\n * $scope.user = {\n * name: function(newName) {\n * return angular.isDefined(newName) ? (_name = newName) : _name;\n * }\n * };\n * }]);\n * \n *
\n *\n *\n * ## Specifying timezones\n *\n * You can specify the timezone that date/time input directives expect by providing its name in the\n * `timezone` property.\n *\n * @param {Object} ngModelOptions options to apply to {@link ngModel} directives on this element and\n * and its descendents. Valid keys are:\n * - `updateOn`: string specifying which event should the input be bound to. You can set several\n * events using an space delimited list. There is a special event called `default` that\n * matches the default events belonging to the control.\n * - `debounce`: integer value which contains the debounce model update value in milliseconds. A\n * value of 0 triggers an immediate update. If an object is supplied instead, you can specify a\n * custom value for each event. For example:\n * ```\n * ng-model-options=\"{\n * updateOn: 'default blur',\n * debounce: { 'default': 500, 'blur': 0 }\n * }\"\n * ```\n * - `allowInvalid`: boolean value which indicates that the model can be set with values that did\n * not validate correctly instead of the default behavior of setting the model to undefined.\n * - `getterSetter`: boolean value which determines whether or not to treat functions bound to\n * `ngModel` as getters/setters.\n * - `timezone`: Defines the timezone to be used to read/write the `Date` instance in the model for\n * ``, ``, ... . It understands UTC/GMT and the\n * continental US time zone abbreviations, but for general use, use a time zone offset, for\n * example, `'+0430'` (4 hours, 30 minutes east of the Greenwich meridian)\n * If not specified, the timezone of the browser will be used.\n *\n */\nvar ngModelOptionsDirective = function() {\n return {\n restrict: 'A',\n // ngModelOptions needs to run before ngModel and input directives\n priority: 10,\n require: ['ngModelOptions', '?^^ngModelOptions'],\n controller: function NgModelOptionsController() {},\n link: {\n pre: function ngModelOptionsPreLinkFn(scope, element, attrs, ctrls) {\n var optionsCtrl = ctrls[0];\n var parentOptions = ctrls[1] ? ctrls[1].$options : defaultModelOptions;\n optionsCtrl.$options = parentOptions.createChild(scope.$eval(attrs.ngModelOptions));\n }\n }\n };\n};\n\n\n// shallow copy over values from `src` that are not already specified on `dst`\nfunction defaults(dst, src) {\n forEach(src, function(value, key) {\n if (!isDefined(dst[key])) {\n dst[key] = value;\n }\n });\n}\n\n/**\n * @ngdoc directive\n * @name ngNonBindable\n * @restrict AC\n * @priority 1000\n *\n * @description\n * The `ngNonBindable` directive tells Angular not to compile or bind the contents of the current\n * DOM element. This is useful if the element contains what appears to be Angular directives and\n * bindings but which should be ignored by Angular. This could be the case if you have a site that\n * displays snippets of code, for instance.\n *\n * @element ANY\n *\n * @example\n * In this example there are two locations where a simple interpolation binding (`{{}}`) is present,\n * but the one wrapped in `ngNonBindable` is left alone.\n *\n * @example\n \n \n
Normal: {{1 + 2}}
\n
Ignored: {{1 + 2}}
\n
\n \n it('should check ng-non-bindable', function() {\n expect(element(by.binding('1 + 2')).getText()).toContain('3');\n expect(element.all(by.css('div')).last().getText()).toMatch(/1 \\+ 2/);\n });\n \n
\n */\nvar ngNonBindableDirective = ngDirective({ terminal: true, priority: 1000 });\n\n/* exported ngOptionsDirective */\n\n/* global jqLiteRemove */\n\nvar ngOptionsMinErr = minErr('ngOptions');\n\n/**\n * @ngdoc directive\n * @name ngOptions\n * @restrict A\n *\n * @description\n *\n * The `ngOptions` attribute can be used to dynamically generate a list of ``\n * DOM element.\n * * `disable`: The result of this expression will be used to disable the rendered `
\n \n \n it('should show correct pluralized string', function() {\n var withoutOffset = element.all(by.css('ng-pluralize')).get(0);\n var withOffset = element.all(by.css('ng-pluralize')).get(1);\n var countInput = element(by.model('personCount'));\n\n expect(withoutOffset.getText()).toEqual('1 person is viewing.');\n expect(withOffset.getText()).toEqual('Igor is viewing.');\n\n countInput.clear();\n countInput.sendKeys('0');\n\n expect(withoutOffset.getText()).toEqual('Nobody is viewing.');\n expect(withOffset.getText()).toEqual('Nobody is viewing.');\n\n countInput.clear();\n countInput.sendKeys('2');\n\n expect(withoutOffset.getText()).toEqual('2 people are viewing.');\n expect(withOffset.getText()).toEqual('Igor and Misko are viewing.');\n\n countInput.clear();\n countInput.sendKeys('3');\n\n expect(withoutOffset.getText()).toEqual('3 people are viewing.');\n expect(withOffset.getText()).toEqual('Igor, Misko and one other person are viewing.');\n\n countInput.clear();\n countInput.sendKeys('4');\n\n expect(withoutOffset.getText()).toEqual('4 people are viewing.');\n expect(withOffset.getText()).toEqual('Igor, Misko and 2 other people are viewing.');\n });\n it('should show data-bound names', function() {\n var withOffset = element.all(by.css('ng-pluralize')).get(1);\n var personCount = element(by.model('personCount'));\n var person1 = element(by.model('person1'));\n var person2 = element(by.model('person2'));\n personCount.clear();\n personCount.sendKeys('4');\n person1.clear();\n person1.sendKeys('Di');\n person2.clear();\n person2.sendKeys('Vojta');\n expect(withOffset.getText()).toEqual('Di, Vojta and 2 other people are viewing.');\n });\n \n \n */\nvar ngPluralizeDirective = ['$locale', '$interpolate', '$log', function($locale, $interpolate, $log) {\n var BRACE = /{}/g,\n IS_WHEN = /^when(Minus)?(.+)$/;\n\n return {\n link: function(scope, element, attr) {\n var numberExp = attr.count,\n whenExp = attr.$attr.when && element.attr(attr.$attr.when), // we have {{}} in attrs\n offset = attr.offset || 0,\n whens = scope.$eval(whenExp) || {},\n whensExpFns = {},\n startSymbol = $interpolate.startSymbol(),\n endSymbol = $interpolate.endSymbol(),\n braceReplacement = startSymbol + numberExp + '-' + offset + endSymbol,\n watchRemover = angular.noop,\n lastCount;\n\n forEach(attr, function(expression, attributeName) {\n var tmpMatch = IS_WHEN.exec(attributeName);\n if (tmpMatch) {\n var whenKey = (tmpMatch[1] ? '-' : '') + lowercase(tmpMatch[2]);\n whens[whenKey] = element.attr(attr.$attr[attributeName]);\n }\n });\n forEach(whens, function(expression, key) {\n whensExpFns[key] = $interpolate(expression.replace(BRACE, braceReplacement));\n\n });\n\n scope.$watch(numberExp, function ngPluralizeWatchAction(newVal) {\n var count = parseFloat(newVal);\n var countIsNaN = isNumberNaN(count);\n\n if (!countIsNaN && !(count in whens)) {\n // If an explicit number rule such as 1, 2, 3... is defined, just use it.\n // Otherwise, check it against pluralization rules in $locale service.\n count = $locale.pluralCat(count - offset);\n }\n\n // If both `count` and `lastCount` are NaN, we don't need to re-register a watch.\n // In JS `NaN !== NaN`, so we have to explicitly check.\n if ((count !== lastCount) && !(countIsNaN && isNumberNaN(lastCount))) {\n watchRemover();\n var whenExpFn = whensExpFns[count];\n if (isUndefined(whenExpFn)) {\n if (newVal != null) {\n $log.debug('ngPluralize: no rule defined for \\'' + count + '\\' in ' + whenExp);\n }\n watchRemover = noop;\n updateElementText();\n } else {\n watchRemover = scope.$watch(whenExpFn, updateElementText);\n }\n lastCount = count;\n }\n });\n\n function updateElementText(newText) {\n element.text(newText || '');\n }\n }\n };\n}];\n\n/* exported ngRepeatDirective */\n\n/**\n * @ngdoc directive\n * @name ngRepeat\n * @multiElement\n *\n * @description\n * The `ngRepeat` directive instantiates a template once per item from a collection. Each template\n * instance gets its own scope, where the given loop variable is set to the current collection item,\n * and `$index` is set to the item index or key.\n *\n * Special properties are exposed on the local scope of each template instance, including:\n *\n * | Variable | Type | Details |\n * |-----------|-----------------|-----------------------------------------------------------------------------|\n * | `$index` | {@type number} | iterator offset of the repeated element (0..length-1) |\n * | `$first` | {@type boolean} | true if the repeated element is first in the iterator. |\n * | `$middle` | {@type boolean} | true if the repeated element is between the first and last in the iterator. |\n * | `$last` | {@type boolean} | true if the repeated element is last in the iterator. |\n * | `$even` | {@type boolean} | true if the iterator position `$index` is even (otherwise false). |\n * | `$odd` | {@type boolean} | true if the iterator position `$index` is odd (otherwise false). |\n *\n *
\n * Creating aliases for these properties is possible with {@link ng.directive:ngInit `ngInit`}.\n * This may be useful when, for instance, nesting ngRepeats.\n *
\n *\n *\n * # Iterating over object properties\n *\n * It is possible to get `ngRepeat` to iterate over the properties of an object using the following\n * syntax:\n *\n * ```js\n *
...
\n * ```\n *\n * However, there are a few limitations compared to array iteration:\n *\n * - The JavaScript specification does not define the order of keys\n * returned for an object, so Angular relies on the order returned by the browser\n * when running `for key in myObj`. Browsers generally follow the strategy of providing\n * keys in the order in which they were defined, although there are exceptions when keys are deleted\n * and reinstated. See the\n * [MDN page on `delete` for more info](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/delete#Cross-browser_notes).\n *\n * - `ngRepeat` will silently *ignore* object keys starting with `$`, because\n * it's a prefix used by Angular for public (`$`) and private (`$$`) properties.\n *\n * - The built-in filters {@link ng.orderBy orderBy} and {@link ng.filter filter} do not work with\n * objects, and will throw an error if used with one.\n *\n * If you are hitting any of these limitations, the recommended workaround is to convert your object into an array\n * that is sorted into the order that you prefer before providing it to `ngRepeat`. You could\n * do this with a filter such as [toArrayFilter](http://ngmodules.org/modules/angular-toArrayFilter)\n * or implement a `$watch` on the object yourself.\n *\n *\n * # Tracking and Duplicates\n *\n * `ngRepeat` uses {@link $rootScope.Scope#$watchCollection $watchCollection} to detect changes in\n * the collection. When a change happens, `ngRepeat` then makes the corresponding changes to the DOM:\n *\n * * When an item is added, a new instance of the template is added to the DOM.\n * * When an item is removed, its template instance is removed from the DOM.\n * * When items are reordered, their respective templates are reordered in the DOM.\n *\n * To minimize creation of DOM elements, `ngRepeat` uses a function\n * to \"keep track\" of all items in the collection and their corresponding DOM elements.\n * For example, if an item is added to the collection, `ngRepeat` will know that all other items\n * already have DOM elements, and will not re-render them.\n *\n * The default tracking function (which tracks items by their identity) does not allow\n * duplicate items in arrays. This is because when there are duplicates, it is not possible\n * to maintain a one-to-one mapping between collection items and DOM elements.\n *\n * If you do need to repeat duplicate items, you can substitute the default tracking behavior\n * with your own using the `track by` expression.\n *\n * For example, you may track items by the index of each item in the collection, using the\n * special scope property `$index`:\n * ```html\n *
\n * {{n}}\n *
\n * ```\n *\n * You may also use arbitrary expressions in `track by`, including references to custom functions\n * on the scope:\n * ```html\n *
\n * {{n}}\n *
\n * ```\n *\n *
\n * If you are working with objects that have a unique identifier property, you should track\n * by this identifier instead of the object instance. Should you reload your data later, `ngRepeat`\n * will not have to rebuild the DOM elements for items it has already rendered, even if the\n * JavaScript objects in the collection have been substituted for new ones. For large collections,\n * this significantly improves rendering performance. If you don't have a unique identifier,\n * `track by $index` can also provide a performance boost.\n *
\n *\n * ```html\n *
\n * {{model.name}}\n *
\n * ```\n *\n *
\n *
\n * Avoid using `track by $index` when the repeated template contains\n * {@link guide/expression#one-time-binding one-time bindings}. In such cases, the `nth` DOM\n * element will always be matched with the `nth` item of the array, so the bindings on that element\n * will not be updated even when the corresponding item changes, essentially causing the view to get\n * out-of-sync with the underlying data.\n *
\n *\n * When no `track by` expression is provided, it is equivalent to tracking by the built-in\n * `$id` function, which tracks items by their identity:\n * ```html\n *
\n * {{obj.prop}}\n *
\n * ```\n *\n *
\n *
\n * **Note:** `track by` must always be the last expression:\n *
\n * ```\n *
\n * {{model.name}}\n *
\n * ```\n *\n *\n * # Special repeat start and end points\n * To repeat a series of elements instead of just one parent element, ngRepeat (as well as other ng directives) supports extending\n * the range of the repeater by defining explicit start and end points by using **ng-repeat-start** and **ng-repeat-end** respectively.\n * The **ng-repeat-start** directive works the same as **ng-repeat**, but will repeat all the HTML code (including the tag it's defined on)\n * up to and including the ending HTML tag where **ng-repeat-end** is placed.\n *\n * The example below makes use of this feature:\n * ```html\n *
\n * Header {{ item }}\n *
\n *
\n * Body {{ item }}\n *
\n *
\n * Footer {{ item }}\n *
\n * ```\n *\n * And with an input of {@type ['A','B']} for the items variable in the example above, the output will evaluate to:\n * ```html\n *
\n * Header A\n *
\n *
\n * Body A\n *
\n *
\n * Footer A\n *
\n *
\n * Header B\n *
\n *
\n * Body B\n *
\n *
\n * Footer B\n *
\n * ```\n *\n * The custom start and end points for ngRepeat also support all other HTML directive syntax flavors provided in AngularJS (such\n * as **data-ng-repeat-start**, **x-ng-repeat-start** and **ng:repeat-start**).\n *\n * @animations\n * | Animation | Occurs |\n * |----------------------------------|-------------------------------------|\n * | {@link ng.$animate#enter enter} | when a new item is added to the list or when an item is revealed after a filter |\n * | {@link ng.$animate#leave leave} | when an item is removed from the list or when an item is filtered out |\n * | {@link ng.$animate#move move } | when an adjacent item is filtered out causing a reorder or when the item contents are reordered |\n *\n * See the example below for defining CSS animations with ngRepeat.\n *\n * @element ANY\n * @scope\n * @priority 1000\n * @param {repeat_expression} ngRepeat The expression indicating how to enumerate a collection. These\n * formats are currently supported:\n *\n * * `variable in expression` – where variable is the user defined loop variable and `expression`\n * is a scope expression giving the collection to enumerate.\n *\n * For example: `album in artist.albums`.\n *\n * * `(key, value) in expression` – where `key` and `value` can be any user defined identifiers,\n * and `expression` is the scope expression giving the collection to enumerate.\n *\n * For example: `(name, age) in {'adam':10, 'amalie':12}`.\n *\n * * `variable in expression track by tracking_expression` – You can also provide an optional tracking expression\n * which can be used to associate the objects in the collection with the DOM elements. If no tracking expression\n * is specified, ng-repeat associates elements by identity. It is an error to have\n * more than one tracking expression value resolve to the same key. (This would mean that two distinct objects are\n * mapped to the same DOM element, which is not possible.)\n *\n * Note that the tracking expression must come last, after any filters, and the alias expression.\n *\n * For example: `item in items` is equivalent to `item in items track by $id(item)`. This implies that the DOM elements\n * will be associated by item identity in the array.\n *\n * For example: `item in items track by $id(item)`. A built in `$id()` function can be used to assign a unique\n * `$$hashKey` property to each item in the array. This property is then used as a key to associated DOM elements\n * with the corresponding item in the array by identity. Moving the same object in array would move the DOM\n * element in the same way in the DOM.\n *\n * For example: `item in items track by item.id` is a typical pattern when the items come from the database. In this\n * case the object identity does not matter. Two objects are considered equivalent as long as their `id`\n * property is same.\n *\n * For example: `item in items | filter:searchText track by item.id` is a pattern that might be used to apply a filter\n * to items in conjunction with a tracking expression.\n *\n * * `variable in expression as alias_expression` – You can also provide an optional alias expression which will then store the\n * intermediate results of the repeater after the filters have been applied. Typically this is used to render a special message\n * when a filter is active on the repeater, but the filtered result set is empty.\n *\n * For example: `item in items | filter:x as results` will store the fragment of the repeated items as `results`, but only after\n * the items have been processed through the filter.\n *\n * Please note that `as [variable name] is not an operator but rather a part of ngRepeat micro-syntax so it can be used only at the end\n * (and not as operator, inside an expression).\n *\n * For example: `item in items | filter : x | orderBy : order | limitTo : limit as results` .\n *\n * @example\n * This example uses `ngRepeat` to display a list of people. A filter is used to restrict the displayed\n * results by name or by age. New (entering) and removed (leaving) items are animated.\n \n \n
\n I have {{friends.length}} friends. They are:\n \n
    \n
  • \n [{{$index + 1}}] {{friend.name}} who is {{friend.age}} years old.\n
  • \n
  • \n No results found...\n
  • \n
\n
\n
\n \n angular.module('ngRepeat', ['ngAnimate']).controller('repeatController', function($scope) {\n $scope.friends = [\n {name:'John', age:25, gender:'boy'},\n {name:'Jessie', age:30, gender:'girl'},\n {name:'Johanna', age:28, gender:'girl'},\n {name:'Joy', age:15, gender:'girl'},\n {name:'Mary', age:28, gender:'girl'},\n {name:'Peter', age:95, gender:'boy'},\n {name:'Sebastian', age:50, gender:'boy'},\n {name:'Erika', age:27, gender:'girl'},\n {name:'Patrick', age:40, gender:'boy'},\n {name:'Samantha', age:60, gender:'girl'}\n ];\n });\n \n \n .example-animate-container {\n background:white;\n border:1px solid black;\n list-style:none;\n margin:0;\n padding:0 10px;\n }\n\n .animate-repeat {\n line-height:30px;\n list-style:none;\n box-sizing:border-box;\n }\n\n .animate-repeat.ng-move,\n .animate-repeat.ng-enter,\n .animate-repeat.ng-leave {\n transition:all linear 0.5s;\n }\n\n .animate-repeat.ng-leave.ng-leave-active,\n .animate-repeat.ng-move,\n .animate-repeat.ng-enter {\n opacity:0;\n max-height:0;\n }\n\n .animate-repeat.ng-leave,\n .animate-repeat.ng-move.ng-move-active,\n .animate-repeat.ng-enter.ng-enter-active {\n opacity:1;\n max-height:30px;\n }\n \n \n var friends = element.all(by.repeater('friend in friends'));\n\n it('should render initial data set', function() {\n expect(friends.count()).toBe(10);\n expect(friends.get(0).getText()).toEqual('[1] John who is 25 years old.');\n expect(friends.get(1).getText()).toEqual('[2] Jessie who is 30 years old.');\n expect(friends.last().getText()).toEqual('[10] Samantha who is 60 years old.');\n expect(element(by.binding('friends.length')).getText())\n .toMatch(\"I have 10 friends. They are:\");\n });\n\n it('should update repeater when filter predicate changes', function() {\n expect(friends.count()).toBe(10);\n\n element(by.model('q')).sendKeys('ma');\n\n expect(friends.count()).toBe(2);\n expect(friends.get(0).getText()).toEqual('[1] Mary who is 28 years old.');\n expect(friends.last().getText()).toEqual('[2] Samantha who is 60 years old.');\n });\n \n
\n */\nvar ngRepeatDirective = ['$parse', '$animate', '$compile', function($parse, $animate, $compile) {\n var NG_REMOVED = '$$NG_REMOVED';\n var ngRepeatMinErr = minErr('ngRepeat');\n\n var updateScope = function(scope, index, valueIdentifier, value, keyIdentifier, key, arrayLength) {\n // TODO(perf): generate setters to shave off ~40ms or 1-1.5%\n scope[valueIdentifier] = value;\n if (keyIdentifier) scope[keyIdentifier] = key;\n scope.$index = index;\n scope.$first = (index === 0);\n scope.$last = (index === (arrayLength - 1));\n scope.$middle = !(scope.$first || scope.$last);\n // eslint-disable-next-line no-bitwise\n scope.$odd = !(scope.$even = (index & 1) === 0);\n };\n\n var getBlockStart = function(block) {\n return block.clone[0];\n };\n\n var getBlockEnd = function(block) {\n return block.clone[block.clone.length - 1];\n };\n\n\n return {\n restrict: 'A',\n multiElement: true,\n transclude: 'element',\n priority: 1000,\n terminal: true,\n $$tlb: true,\n compile: function ngRepeatCompile($element, $attr) {\n var expression = $attr.ngRepeat;\n var ngRepeatEndComment = $compile.$$createComment('end ngRepeat', expression);\n\n var match = expression.match(/^\\s*([\\s\\S]+?)\\s+in\\s+([\\s\\S]+?)(?:\\s+as\\s+([\\s\\S]+?))?(?:\\s+track\\s+by\\s+([\\s\\S]+?))?\\s*$/);\n\n if (!match) {\n throw ngRepeatMinErr('iexp', 'Expected expression in form of \\'_item_ in _collection_[ track by _id_]\\' but got \\'{0}\\'.',\n expression);\n }\n\n var lhs = match[1];\n var rhs = match[2];\n var aliasAs = match[3];\n var trackByExp = match[4];\n\n match = lhs.match(/^(?:(\\s*[$\\w]+)|\\(\\s*([$\\w]+)\\s*,\\s*([$\\w]+)\\s*\\))$/);\n\n if (!match) {\n throw ngRepeatMinErr('iidexp', '\\'_item_\\' in \\'_item_ in _collection_\\' should be an identifier or \\'(_key_, _value_)\\' expression, but got \\'{0}\\'.',\n lhs);\n }\n var valueIdentifier = match[3] || match[1];\n var keyIdentifier = match[2];\n\n if (aliasAs && (!/^[$a-zA-Z_][$a-zA-Z0-9_]*$/.test(aliasAs) ||\n /^(null|undefined|this|\\$index|\\$first|\\$middle|\\$last|\\$even|\\$odd|\\$parent|\\$root|\\$id)$/.test(aliasAs))) {\n throw ngRepeatMinErr('badident', 'alias \\'{0}\\' is invalid --- must be a valid JS identifier which is not a reserved name.',\n aliasAs);\n }\n\n var trackByExpGetter, trackByIdExpFn, trackByIdArrayFn, trackByIdObjFn;\n var hashFnLocals = {$id: hashKey};\n\n if (trackByExp) {\n trackByExpGetter = $parse(trackByExp);\n } else {\n trackByIdArrayFn = function(key, value) {\n return hashKey(value);\n };\n trackByIdObjFn = function(key) {\n return key;\n };\n }\n\n return function ngRepeatLink($scope, $element, $attr, ctrl, $transclude) {\n\n if (trackByExpGetter) {\n trackByIdExpFn = function(key, value, index) {\n // assign key, value, and $index to the locals so that they can be used in hash functions\n if (keyIdentifier) hashFnLocals[keyIdentifier] = key;\n hashFnLocals[valueIdentifier] = value;\n hashFnLocals.$index = index;\n return trackByExpGetter($scope, hashFnLocals);\n };\n }\n\n // Store a list of elements from previous run. This is a hash where key is the item from the\n // iterator, and the value is objects with following properties.\n // - scope: bound scope\n // - element: previous element.\n // - index: position\n //\n // We are using no-proto object so that we don't need to guard against inherited props via\n // hasOwnProperty.\n var lastBlockMap = createMap();\n\n //watch props\n $scope.$watchCollection(rhs, function ngRepeatAction(collection) {\n var index, length,\n previousNode = $element[0], // node that cloned nodes should be inserted after\n // initialized to the comment node anchor\n nextNode,\n // Same as lastBlockMap but it has the current state. It will become the\n // lastBlockMap on the next iteration.\n nextBlockMap = createMap(),\n collectionLength,\n key, value, // key/value of iteration\n trackById,\n trackByIdFn,\n collectionKeys,\n block, // last object information {scope, element, id}\n nextBlockOrder,\n elementsToRemove;\n\n if (aliasAs) {\n $scope[aliasAs] = collection;\n }\n\n if (isArrayLike(collection)) {\n collectionKeys = collection;\n trackByIdFn = trackByIdExpFn || trackByIdArrayFn;\n } else {\n trackByIdFn = trackByIdExpFn || trackByIdObjFn;\n // if object, extract keys, in enumeration order, unsorted\n collectionKeys = [];\n for (var itemKey in collection) {\n if (hasOwnProperty.call(collection, itemKey) && itemKey.charAt(0) !== '$') {\n collectionKeys.push(itemKey);\n }\n }\n }\n\n collectionLength = collectionKeys.length;\n nextBlockOrder = new Array(collectionLength);\n\n // locate existing items\n for (index = 0; index < collectionLength; index++) {\n key = (collection === collectionKeys) ? index : collectionKeys[index];\n value = collection[key];\n trackById = trackByIdFn(key, value, index);\n if (lastBlockMap[trackById]) {\n // found previously seen block\n block = lastBlockMap[trackById];\n delete lastBlockMap[trackById];\n nextBlockMap[trackById] = block;\n nextBlockOrder[index] = block;\n } else if (nextBlockMap[trackById]) {\n // if collision detected. restore lastBlockMap and throw an error\n forEach(nextBlockOrder, function(block) {\n if (block && block.scope) lastBlockMap[block.id] = block;\n });\n throw ngRepeatMinErr('dupes',\n 'Duplicates in a repeater are not allowed. Use \\'track by\\' expression to specify unique keys. Repeater: {0}, Duplicate key: {1}, Duplicate value: {2}',\n expression, trackById, value);\n } else {\n // new never before seen block\n nextBlockOrder[index] = {id: trackById, scope: undefined, clone: undefined};\n nextBlockMap[trackById] = true;\n }\n }\n\n // remove leftover items\n for (var blockKey in lastBlockMap) {\n block = lastBlockMap[blockKey];\n elementsToRemove = getBlockNodes(block.clone);\n $animate.leave(elementsToRemove);\n if (elementsToRemove[0].parentNode) {\n // if the element was not removed yet because of pending animation, mark it as deleted\n // so that we can ignore it later\n for (index = 0, length = elementsToRemove.length; index < length; index++) {\n elementsToRemove[index][NG_REMOVED] = true;\n }\n }\n block.scope.$destroy();\n }\n\n // we are not using forEach for perf reasons (trying to avoid #call)\n for (index = 0; index < collectionLength; index++) {\n key = (collection === collectionKeys) ? index : collectionKeys[index];\n value = collection[key];\n block = nextBlockOrder[index];\n\n if (block.scope) {\n // if we have already seen this object, then we need to reuse the\n // associated scope/element\n\n nextNode = previousNode;\n\n // skip nodes that are already pending removal via leave animation\n do {\n nextNode = nextNode.nextSibling;\n } while (nextNode && nextNode[NG_REMOVED]);\n\n if (getBlockStart(block) !== nextNode) {\n // existing item which got moved\n $animate.move(getBlockNodes(block.clone), null, previousNode);\n }\n previousNode = getBlockEnd(block);\n updateScope(block.scope, index, valueIdentifier, value, keyIdentifier, key, collectionLength);\n } else {\n // new item which we don't know about\n $transclude(function ngRepeatTransclude(clone, scope) {\n block.scope = scope;\n // http://jsperf.com/clone-vs-createcomment\n var endNode = ngRepeatEndComment.cloneNode(false);\n clone[clone.length++] = endNode;\n\n $animate.enter(clone, null, previousNode);\n previousNode = endNode;\n // Note: We only need the first/last node of the cloned nodes.\n // However, we need to keep the reference to the jqlite wrapper as it might be changed later\n // by a directive with templateUrl when its template arrives.\n block.clone = clone;\n nextBlockMap[block.id] = block;\n updateScope(block.scope, index, valueIdentifier, value, keyIdentifier, key, collectionLength);\n });\n }\n }\n lastBlockMap = nextBlockMap;\n });\n };\n }\n };\n}];\n\nvar NG_HIDE_CLASS = 'ng-hide';\nvar NG_HIDE_IN_PROGRESS_CLASS = 'ng-hide-animate';\n/**\n * @ngdoc directive\n * @name ngShow\n * @multiElement\n *\n * @description\n * The `ngShow` directive shows or hides the given HTML element based on the expression\n * provided to the `ngShow` attribute. The element is shown or hidden by removing or adding\n * the `.ng-hide` CSS class onto the element. The `.ng-hide` CSS class is predefined\n * in AngularJS and sets the display style to none (using an !important flag).\n * For CSP mode please add `angular-csp.css` to your html file (see {@link ng.directive:ngCsp ngCsp}).\n *\n * ```html\n * \n *
\n *\n * \n *
\n * ```\n *\n * When the `ngShow` expression evaluates to a falsy value then the `.ng-hide` CSS class is added to the class\n * attribute on the element causing it to become hidden. When truthy, the `.ng-hide` CSS class is removed\n * from the element causing the element not to appear hidden.\n *\n * ## Why is !important used?\n *\n * You may be wondering why !important is used for the `.ng-hide` CSS class. This is because the `.ng-hide` selector\n * can be easily overridden by heavier selectors. For example, something as simple\n * as changing the display style on a HTML list item would make hidden elements appear visible.\n * This also becomes a bigger issue when dealing with CSS frameworks.\n *\n * By using !important, the show and hide behavior will work as expected despite any clash between CSS selector\n * specificity (when !important isn't used with any conflicting styles). If a developer chooses to override the\n * styling to change how to hide an element then it is just a matter of using !important in their own CSS code.\n *\n * ### Overriding `.ng-hide`\n *\n * By default, the `.ng-hide` class will style the element with `display: none!important`. If you wish to change\n * the hide behavior with ngShow/ngHide then this can be achieved by restating the styles for the `.ng-hide`\n * class CSS. Note that the selector that needs to be used is actually `.ng-hide:not(.ng-hide-animate)` to cope\n * with extra animation classes that can be added.\n *\n * ```css\n * .ng-hide:not(.ng-hide-animate) {\n * /* this is just another form of hiding an element */\n * display: block!important;\n * position: absolute;\n * top: -9999px;\n * left: -9999px;\n * }\n * ```\n *\n * By default you don't need to override in CSS anything and the animations will work around the display style.\n *\n * ## A note about animations with `ngShow`\n *\n * Animations in ngShow/ngHide work with the show and hide events that are triggered when the directive expression\n * is true and false. This system works like the animation system present with ngClass except that\n * you must also include the !important flag to override the display property\n * so that you can perform an animation when the element is hidden during the time of the animation.\n *\n * ```css\n * //\n * //a working example can be found at the bottom of this page\n * //\n * .my-element.ng-hide-add, .my-element.ng-hide-remove {\n * /* this is required as of 1.3x to properly\n * apply all styling in a show/hide animation */\n * transition: 0s linear all;\n * }\n *\n * .my-element.ng-hide-add-active,\n * .my-element.ng-hide-remove-active {\n * /* the transition is defined in the active class */\n * transition: 1s linear all;\n * }\n *\n * .my-element.ng-hide-add { ... }\n * .my-element.ng-hide-add.ng-hide-add-active { ... }\n * .my-element.ng-hide-remove { ... }\n * .my-element.ng-hide-remove.ng-hide-remove-active { ... }\n * ```\n *\n * Keep in mind that, as of AngularJS version 1.3, there is no need to change the display\n * property to block during animation states--ngAnimate will handle the style toggling automatically for you.\n *\n * @animations\n * | Animation | Occurs |\n * |----------------------------------|-------------------------------------|\n * | {@link $animate#addClass addClass} `.ng-hide` | after the `ngShow` expression evaluates to a non truthy value and just before the contents are set to hidden |\n * | {@link $animate#removeClass removeClass} `.ng-hide` | after the `ngShow` expression evaluates to a truthy value and just before contents are set to visible |\n *\n * @element ANY\n * @param {expression} ngShow If the {@link guide/expression expression} is truthy\n * then the element is shown or hidden respectively.\n *\n * @example\n \n \n Click me:
\n
\n Show:\n
\n I show up when your checkbox is checked.\n
\n
\n
\n Hide:\n
\n I hide when your checkbox is checked.\n
\n
\n
\n \n @import url(../../components/bootstrap-3.1.1/css/bootstrap.css);\n \n \n .animate-show {\n line-height: 20px;\n opacity: 1;\n padding: 10px;\n border: 1px solid black;\n background: white;\n }\n\n .animate-show.ng-hide-add, .animate-show.ng-hide-remove {\n transition: all linear 0.5s;\n }\n\n .animate-show.ng-hide {\n line-height: 0;\n opacity: 0;\n padding: 0 10px;\n }\n\n .check-element {\n padding: 10px;\n border: 1px solid black;\n background: white;\n }\n \n \n var thumbsUp = element(by.css('span.glyphicon-thumbs-up'));\n var thumbsDown = element(by.css('span.glyphicon-thumbs-down'));\n\n it('should check ng-show / ng-hide', function() {\n expect(thumbsUp.isDisplayed()).toBeFalsy();\n expect(thumbsDown.isDisplayed()).toBeTruthy();\n\n element(by.model('checked')).click();\n\n expect(thumbsUp.isDisplayed()).toBeTruthy();\n expect(thumbsDown.isDisplayed()).toBeFalsy();\n });\n \n
\n */\nvar ngShowDirective = ['$animate', function($animate) {\n return {\n restrict: 'A',\n multiElement: true,\n link: function(scope, element, attr) {\n scope.$watch(attr.ngShow, function ngShowWatchAction(value) {\n // we're adding a temporary, animation-specific class for ng-hide since this way\n // we can control when the element is actually displayed on screen without having\n // to have a global/greedy CSS selector that breaks when other animations are run.\n // Read: https://github.com/angular/angular.js/issues/9103#issuecomment-58335845\n $animate[value ? 'removeClass' : 'addClass'](element, NG_HIDE_CLASS, {\n tempClasses: NG_HIDE_IN_PROGRESS_CLASS\n });\n });\n }\n };\n}];\n\n\n/**\n * @ngdoc directive\n * @name ngHide\n * @multiElement\n *\n * @description\n * The `ngHide` directive shows or hides the given HTML element based on the expression\n * provided to the `ngHide` attribute. The element is shown or hidden by removing or adding\n * the `ng-hide` CSS class onto the element. The `.ng-hide` CSS class is predefined\n * in AngularJS and sets the display style to none (using an !important flag).\n * For CSP mode please add `angular-csp.css` to your html file (see {@link ng.directive:ngCsp ngCsp}).\n *\n * ```html\n * \n *
\n *\n * \n *
\n * ```\n *\n * When the `ngHide` expression evaluates to a truthy value then the `.ng-hide` CSS class is added to the class\n * attribute on the element causing it to become hidden. When falsy, the `.ng-hide` CSS class is removed\n * from the element causing the element not to appear hidden.\n *\n * ## Why is !important used?\n *\n * You may be wondering why !important is used for the `.ng-hide` CSS class. This is because the `.ng-hide` selector\n * can be easily overridden by heavier selectors. For example, something as simple\n * as changing the display style on a HTML list item would make hidden elements appear visible.\n * This also becomes a bigger issue when dealing with CSS frameworks.\n *\n * By using !important, the show and hide behavior will work as expected despite any clash between CSS selector\n * specificity (when !important isn't used with any conflicting styles). If a developer chooses to override the\n * styling to change how to hide an element then it is just a matter of using !important in their own CSS code.\n *\n * ### Overriding `.ng-hide`\n *\n * By default, the `.ng-hide` class will style the element with `display: none!important`. If you wish to change\n * the hide behavior with ngShow/ngHide then this can be achieved by restating the styles for the `.ng-hide`\n * class in CSS:\n *\n * ```css\n * .ng-hide {\n * /* this is just another form of hiding an element */\n * display: block!important;\n * position: absolute;\n * top: -9999px;\n * left: -9999px;\n * }\n * ```\n *\n * By default you don't need to override in CSS anything and the animations will work around the display style.\n *\n * ## A note about animations with `ngHide`\n *\n * Animations in ngShow/ngHide work with the show and hide events that are triggered when the directive expression\n * is true and false. This system works like the animation system present with ngClass, except that the `.ng-hide`\n * CSS class is added and removed for you instead of your own CSS class.\n *\n * ```css\n * //\n * //a working example can be found at the bottom of this page\n * //\n * .my-element.ng-hide-add, .my-element.ng-hide-remove {\n * transition: 0.5s linear all;\n * }\n *\n * .my-element.ng-hide-add { ... }\n * .my-element.ng-hide-add.ng-hide-add-active { ... }\n * .my-element.ng-hide-remove { ... }\n * .my-element.ng-hide-remove.ng-hide-remove-active { ... }\n * ```\n *\n * Keep in mind that, as of AngularJS version 1.3, there is no need to change the display\n * property to block during animation states--ngAnimate will handle the style toggling automatically for you.\n *\n * @animations\n * | Animation | Occurs |\n * |----------------------------------|-------------------------------------|\n * | {@link $animate#addClass addClass} `.ng-hide` | after the `ngHide` expression evaluates to a truthy value and just before the contents are set to hidden |\n * | {@link $animate#removeClass removeClass} `.ng-hide` | after the `ngHide` expression evaluates to a non truthy value and just before contents are set to visible |\n *\n *\n * @element ANY\n * @param {expression} ngHide If the {@link guide/expression expression} is truthy then\n * the element is shown or hidden respectively.\n *\n * @example\n \n \n Click me:
\n
\n Show:\n
\n I show up when your checkbox is checked.\n
\n
\n
\n Hide:\n
\n I hide when your checkbox is checked.\n
\n
\n
\n \n @import url(../../components/bootstrap-3.1.1/css/bootstrap.css);\n \n \n .animate-hide {\n transition: all linear 0.5s;\n line-height: 20px;\n opacity: 1;\n padding: 10px;\n border: 1px solid black;\n background: white;\n }\n\n .animate-hide.ng-hide {\n line-height: 0;\n opacity: 0;\n padding: 0 10px;\n }\n\n .check-element {\n padding: 10px;\n border: 1px solid black;\n background: white;\n }\n \n \n var thumbsUp = element(by.css('span.glyphicon-thumbs-up'));\n var thumbsDown = element(by.css('span.glyphicon-thumbs-down'));\n\n it('should check ng-show / ng-hide', function() {\n expect(thumbsUp.isDisplayed()).toBeFalsy();\n expect(thumbsDown.isDisplayed()).toBeTruthy();\n\n element(by.model('checked')).click();\n\n expect(thumbsUp.isDisplayed()).toBeTruthy();\n expect(thumbsDown.isDisplayed()).toBeFalsy();\n });\n \n
\n */\nvar ngHideDirective = ['$animate', function($animate) {\n return {\n restrict: 'A',\n multiElement: true,\n link: function(scope, element, attr) {\n scope.$watch(attr.ngHide, function ngHideWatchAction(value) {\n // The comment inside of the ngShowDirective explains why we add and\n // remove a temporary class for the show/hide animation\n $animate[value ? 'addClass' : 'removeClass'](element,NG_HIDE_CLASS, {\n tempClasses: NG_HIDE_IN_PROGRESS_CLASS\n });\n });\n }\n };\n}];\n\n/**\n * @ngdoc directive\n * @name ngStyle\n * @restrict AC\n *\n * @description\n * The `ngStyle` directive allows you to set CSS style on an HTML element conditionally.\n *\n * @knownIssue\n * You should not use {@link guide/interpolation interpolation} in the value of the `style`\n * attribute, when using the `ngStyle` directive on the same element.\n * See {@link guide/interpolation#known-issues here} for more info.\n *\n * @element ANY\n * @param {expression} ngStyle\n *\n * {@link guide/expression Expression} which evals to an\n * object whose keys are CSS style names and values are corresponding values for those CSS\n * keys.\n *\n * Since some CSS style names are not valid keys for an object, they must be quoted.\n * See the 'background-color' style in the example below.\n *\n * @example\n \n \n \n \n \n
\n Sample Text\n
myStyle={{myStyle}}
\n
\n \n span {\n color: black;\n }\n \n \n var colorSpan = element(by.css('span'));\n\n it('should check ng-style', function() {\n expect(colorSpan.getCssValue('color')).toBe('rgba(0, 0, 0, 1)');\n element(by.css('input[value=\\'set color\\']')).click();\n expect(colorSpan.getCssValue('color')).toBe('rgba(255, 0, 0, 1)');\n element(by.css('input[value=clear]')).click();\n expect(colorSpan.getCssValue('color')).toBe('rgba(0, 0, 0, 1)');\n });\n \n
\n */\nvar ngStyleDirective = ngDirective(function(scope, element, attr) {\n scope.$watch(attr.ngStyle, function ngStyleWatchAction(newStyles, oldStyles) {\n if (oldStyles && (newStyles !== oldStyles)) {\n forEach(oldStyles, function(val, style) { element.css(style, '');});\n }\n if (newStyles) element.css(newStyles);\n }, true);\n});\n\n/**\n * @ngdoc directive\n * @name ngSwitch\n * @restrict EA\n *\n * @description\n * The `ngSwitch` directive is used to conditionally swap DOM structure on your template based on a scope expression.\n * Elements within `ngSwitch` but without `ngSwitchWhen` or `ngSwitchDefault` directives will be preserved at the location\n * as specified in the template.\n *\n * The directive itself works similar to ngInclude, however, instead of downloading template code (or loading it\n * from the template cache), `ngSwitch` simply chooses one of the nested elements and makes it visible based on which element\n * matches the value obtained from the evaluated expression. In other words, you define a container element\n * (where you place the directive), place an expression on the **`on=\"...\"` attribute**\n * (or the **`ng-switch=\"...\"` attribute**), define any inner elements inside of the directive and place\n * a when attribute per element. The when attribute is used to inform ngSwitch which element to display when the on\n * expression is evaluated. If a matching expression is not found via a when attribute then an element with the default\n * attribute is displayed.\n *\n *
\n * Be aware that the attribute values to match against cannot be expressions. They are interpreted\n * as literal string values to match against.\n * For example, **`ng-switch-when=\"someVal\"`** will match against the string `\"someVal\"` not against the\n * value of the expression `$scope.someVal`.\n *
\n\n * @animations\n * | Animation | Occurs |\n * |----------------------------------|-------------------------------------|\n * | {@link ng.$animate#enter enter} | after the ngSwitch contents change and the matched child element is placed inside the container |\n * | {@link ng.$animate#leave leave} | after the ngSwitch contents change and just before the former contents are removed from the DOM |\n *\n * @usage\n *\n * ```\n * \n * ...\n * ...\n * ...\n * \n * ```\n *\n *\n * @scope\n * @priority 1200\n * @param {*} ngSwitch|on expression to match against ng-switch-when.\n * On child elements add:\n *\n * * `ngSwitchWhen`: the case statement to match against. If match then this\n * case will be displayed. If the same match appears multiple times, all the\n * elements will be displayed. It is possible to associate multiple values to\n * the same `ngSwitchWhen` by defining the optional attribute\n * `ngSwitchWhenSeparator`. The separator will be used to split the value of\n * the `ngSwitchWhen` attribute into multiple tokens, and the element will show\n * if any of the `ngSwitch` evaluates to any of these tokens.\n * * `ngSwitchDefault`: the default case when no other case match. If there\n * are multiple default cases, all of them will be displayed when no other\n * case match.\n *\n *\n * @example\n \n \n
\n \n selection={{selection}}\n
\n
\n
Settings Div
\n
Home Span
\n
default
\n
\n
\n
\n \n angular.module('switchExample', ['ngAnimate'])\n .controller('ExampleController', ['$scope', function($scope) {\n $scope.items = ['settings', 'home', 'options', 'other'];\n $scope.selection = $scope.items[0];\n }]);\n \n \n .animate-switch-container {\n position:relative;\n background:white;\n border:1px solid black;\n height:40px;\n overflow:hidden;\n }\n\n .animate-switch {\n padding:10px;\n }\n\n .animate-switch.ng-animate {\n transition:all cubic-bezier(0.250, 0.460, 0.450, 0.940) 0.5s;\n\n position:absolute;\n top:0;\n left:0;\n right:0;\n bottom:0;\n }\n\n .animate-switch.ng-leave.ng-leave-active,\n .animate-switch.ng-enter {\n top:-50px;\n }\n .animate-switch.ng-leave,\n .animate-switch.ng-enter.ng-enter-active {\n top:0;\n }\n \n \n var switchElem = element(by.css('[ng-switch]'));\n var select = element(by.model('selection'));\n\n it('should start in settings', function() {\n expect(switchElem.getText()).toMatch(/Settings Div/);\n });\n it('should change to home', function() {\n select.all(by.css('option')).get(1).click();\n expect(switchElem.getText()).toMatch(/Home Span/);\n });\n it('should change to settings via \"options\"', function() {\n select.all(by.css('option')).get(2).click();\n expect(switchElem.getText()).toMatch(/Settings Div/);\n });\n it('should select default', function() {\n select.all(by.css('option')).get(3).click();\n expect(switchElem.getText()).toMatch(/default/);\n });\n \n
\n */\nvar ngSwitchDirective = ['$animate', '$compile', function($animate, $compile) {\n return {\n require: 'ngSwitch',\n\n // asks for $scope to fool the BC controller module\n controller: ['$scope', function NgSwitchController() {\n this.cases = {};\n }],\n link: function(scope, element, attr, ngSwitchController) {\n var watchExpr = attr.ngSwitch || attr.on,\n selectedTranscludes = [],\n selectedElements = [],\n previousLeaveAnimations = [],\n selectedScopes = [];\n\n var spliceFactory = function(array, index) {\n return function(response) {\n if (response !== false) array.splice(index, 1);\n };\n };\n\n scope.$watch(watchExpr, function ngSwitchWatchAction(value) {\n var i, ii;\n\n // Start with the last, in case the array is modified during the loop\n while (previousLeaveAnimations.length) {\n $animate.cancel(previousLeaveAnimations.pop());\n }\n\n for (i = 0, ii = selectedScopes.length; i < ii; ++i) {\n var selected = getBlockNodes(selectedElements[i].clone);\n selectedScopes[i].$destroy();\n var runner = previousLeaveAnimations[i] = $animate.leave(selected);\n runner.done(spliceFactory(previousLeaveAnimations, i));\n }\n\n selectedElements.length = 0;\n selectedScopes.length = 0;\n\n if ((selectedTranscludes = ngSwitchController.cases['!' + value] || ngSwitchController.cases['?'])) {\n forEach(selectedTranscludes, function(selectedTransclude) {\n selectedTransclude.transclude(function(caseElement, selectedScope) {\n selectedScopes.push(selectedScope);\n var anchor = selectedTransclude.element;\n caseElement[caseElement.length++] = $compile.$$createComment('end ngSwitchWhen');\n var block = { clone: caseElement };\n\n selectedElements.push(block);\n $animate.enter(caseElement, anchor.parent(), anchor);\n });\n });\n }\n });\n }\n };\n}];\n\nvar ngSwitchWhenDirective = ngDirective({\n transclude: 'element',\n priority: 1200,\n require: '^ngSwitch',\n multiElement: true,\n link: function(scope, element, attrs, ctrl, $transclude) {\n\n var cases = attrs.ngSwitchWhen.split(attrs.ngSwitchWhenSeparator).sort().filter(\n // Filter duplicate cases\n function(element, index, array) { return array[index - 1] !== element; }\n );\n\n forEach(cases, function(whenCase) {\n ctrl.cases['!' + whenCase] = (ctrl.cases['!' + whenCase] || []);\n ctrl.cases['!' + whenCase].push({ transclude: $transclude, element: element });\n });\n }\n});\n\nvar ngSwitchDefaultDirective = ngDirective({\n transclude: 'element',\n priority: 1200,\n require: '^ngSwitch',\n multiElement: true,\n link: function(scope, element, attr, ctrl, $transclude) {\n ctrl.cases['?'] = (ctrl.cases['?'] || []);\n ctrl.cases['?'].push({ transclude: $transclude, element: element });\n }\n});\n\n/**\n * @ngdoc directive\n * @name ngTransclude\n * @restrict EAC\n *\n * @description\n * Directive that marks the insertion point for the transcluded DOM of the nearest parent directive that uses transclusion.\n *\n * You can specify that you want to insert a named transclusion slot, instead of the default slot, by providing the slot name\n * as the value of the `ng-transclude` or `ng-transclude-slot` attribute.\n *\n * If the transcluded content is not empty (i.e. contains one or more DOM nodes, including whitespace text nodes), any existing\n * content of this element will be removed before the transcluded content is inserted.\n * If the transcluded content is empty (or only whitespace), the existing content is left intact. This lets you provide fallback\n * content in the case that no transcluded content is provided.\n *\n * @element ANY\n *\n * @param {string} ngTransclude|ngTranscludeSlot the name of the slot to insert at this point. If this is not provided, is empty\n * or its value is the same as the name of the attribute then the default slot is used.\n *\n * @example\n * ### Basic transclusion\n * This example demonstrates basic transclusion of content into a component directive.\n * \n * \n * \n *
\n *
\n *
\n * {{text}}\n *
\n *
\n * \n * it('should have transcluded', function() {\n * var titleElement = element(by.model('title'));\n * titleElement.clear();\n * titleElement.sendKeys('TITLE');\n * var textElement = element(by.model('text'));\n * textElement.clear();\n * textElement.sendKeys('TEXT');\n * expect(element(by.binding('title')).getText()).toEqual('TITLE');\n * expect(element(by.binding('text')).getText()).toEqual('TEXT');\n * });\n * \n *
\n *\n * @example\n * ### Transclude fallback content\n * This example shows how to use `NgTransclude` with fallback content, that\n * is displayed if no transcluded content is provided.\n *\n * \n * \n * \n * \n * \n * \n * \n * Button2\n * \n * \n * \n * it('should have different transclude element content', function() {\n * expect(element(by.id('fallback')).getText()).toBe('Button1');\n * expect(element(by.id('modified')).getText()).toBe('Button2');\n * });\n * \n * \n *\n * @example\n * ### Multi-slot transclusion\n * This example demonstrates using multi-slot transclusion in a component directive.\n * \n * \n * \n *
\n *
\n *
\n * \n * {{title}}\n *

{{text}}

\n *
\n *
\n *
\n * \n * angular.module('multiSlotTranscludeExample', [])\n * .directive('pane', function() {\n * return {\n * restrict: 'E',\n * transclude: {\n * 'title': '?paneTitle',\n * 'body': 'paneBody',\n * 'footer': '?paneFooter'\n * },\n * template: '
' +\n * '
Fallback Title
' +\n * '
' +\n * '
Fallback Footer
' +\n * '
'\n * };\n * })\n * .controller('ExampleController', ['$scope', function($scope) {\n * $scope.title = 'Lorem Ipsum';\n * $scope.link = 'https://google.com';\n * $scope.text = 'Neque porro quisquam est qui dolorem ipsum quia dolor...';\n * }]);\n *
\n * \n * it('should have transcluded the title and the body', function() {\n * var titleElement = element(by.model('title'));\n * titleElement.clear();\n * titleElement.sendKeys('TITLE');\n * var textElement = element(by.model('text'));\n * textElement.clear();\n * textElement.sendKeys('TEXT');\n * expect(element(by.css('.title')).getText()).toEqual('TITLE');\n * expect(element(by.binding('text')).getText()).toEqual('TEXT');\n * expect(element(by.css('.footer')).getText()).toEqual('Fallback Footer');\n * });\n * \n *
\n */\nvar ngTranscludeMinErr = minErr('ngTransclude');\nvar ngTranscludeDirective = ['$compile', function($compile) {\n return {\n restrict: 'EAC',\n terminal: true,\n compile: function ngTranscludeCompile(tElement) {\n\n // Remove and cache any original content to act as a fallback\n var fallbackLinkFn = $compile(tElement.contents());\n tElement.empty();\n\n return function ngTranscludePostLink($scope, $element, $attrs, controller, $transclude) {\n\n if (!$transclude) {\n throw ngTranscludeMinErr('orphan',\n 'Illegal use of ngTransclude directive in the template! ' +\n 'No parent directive that requires a transclusion found. ' +\n 'Element: {0}',\n startingTag($element));\n }\n\n\n // If the attribute is of the form: `ng-transclude=\"ng-transclude\"` then treat it like the default\n if ($attrs.ngTransclude === $attrs.$attr.ngTransclude) {\n $attrs.ngTransclude = '';\n }\n var slotName = $attrs.ngTransclude || $attrs.ngTranscludeSlot;\n\n // If the slot is required and no transclusion content is provided then this call will throw an error\n $transclude(ngTranscludeCloneAttachFn, null, slotName);\n\n // If the slot is optional and no transclusion content is provided then use the fallback content\n if (slotName && !$transclude.isSlotFilled(slotName)) {\n useFallbackContent();\n }\n\n function ngTranscludeCloneAttachFn(clone, transcludedScope) {\n if (clone.length && notWhitespace(clone)) {\n $element.append(clone);\n } else {\n useFallbackContent();\n // There is nothing linked against the transcluded scope since no content was available,\n // so it should be safe to clean up the generated scope.\n transcludedScope.$destroy();\n }\n }\n\n function useFallbackContent() {\n // Since this is the fallback content rather than the transcluded content,\n // we link against the scope of this directive rather than the transcluded scope\n fallbackLinkFn($scope, function(clone) {\n $element.append(clone);\n });\n }\n\n function notWhitespace(nodes) {\n for (var i = 0, ii = nodes.length; i < ii; i++) {\n var node = nodes[i];\n if (node.nodeType !== NODE_TYPE_TEXT || node.nodeValue.trim()) {\n return true;\n }\n }\n }\n };\n }\n };\n}];\n\n/**\n * @ngdoc directive\n * @name script\n * @restrict E\n *\n * @description\n * Load the content of a `\n\n Load inlined template\n
\n \n \n it('should load template defined inside script tag', function() {\n element(by.css('#tpl-link')).click();\n expect(element(by.css('#tpl-content')).getText()).toMatch(/Content of the template/);\n });\n \n \n */\nvar scriptDirective = ['$templateCache', function($templateCache) {\n return {\n restrict: 'E',\n terminal: true,\n compile: function(element, attr) {\n if (attr.type === 'text/ng-template') {\n var templateUrl = attr.id,\n text = element[0].text;\n\n $templateCache.put(templateUrl, text);\n }\n }\n };\n}];\n\n/* exported selectDirective, optionDirective */\n\nvar noopNgModelController = { $setViewValue: noop, $render: noop };\n\n/**\n * @ngdoc type\n * @name select.SelectController\n * @description\n * The controller for the ` and IE barfs otherwise.\n self.unknownOption = jqLite(window.document.createElement('option'));\n\n // The empty option is an option with the value '' that te application developer can\n // provide inside the select. When the model changes to a value that doesn't match an option,\n // it is selected - so if an empty option is provided, no unknown option is generated.\n // However, the empty option is not removed when the model matches an option. It is always selectable\n // and indicates that a \"null\" selection has been made.\n self.hasEmptyOption = false;\n self.emptyOption = undefined;\n\n self.renderUnknownOption = function(val) {\n var unknownVal = self.generateUnknownOptionValue(val);\n self.unknownOption.val(unknownVal);\n $element.prepend(self.unknownOption);\n setOptionAsSelected(self.unknownOption);\n $element.val(unknownVal);\n };\n\n self.updateUnknownOption = function(val) {\n var unknownVal = self.generateUnknownOptionValue(val);\n self.unknownOption.val(unknownVal);\n setOptionAsSelected(self.unknownOption);\n $element.val(unknownVal);\n };\n\n self.generateUnknownOptionValue = function(val) {\n return '? ' + hashKey(val) + ' ?';\n };\n\n self.removeUnknownOption = function() {\n if (self.unknownOption.parent()) self.unknownOption.remove();\n };\n\n self.selectEmptyOption = function() {\n if (self.emptyOption) {\n $element.val('');\n setOptionAsSelected(self.emptyOption);\n }\n };\n\n self.unselectEmptyOption = function() {\n if (self.hasEmptyOption) {\n self.emptyOption.removeAttr('selected');\n }\n };\n\n $scope.$on('$destroy', function() {\n // disable unknown option so that we don't do work when the whole select is being destroyed\n self.renderUnknownOption = noop;\n });\n\n // Read the value of the select control, the implementation of this changes depending\n // upon whether the select can have multiple values and whether ngOptions is at work.\n self.readValue = function readSingleValue() {\n var val = $element.val();\n // ngValue added option values are stored in the selectValueMap, normal interpolations are not\n var realVal = val in self.selectValueMap ? self.selectValueMap[val] : val;\n\n if (self.hasOption(realVal)) {\n return realVal;\n }\n\n return null;\n };\n\n\n // Write the value to the select control, the implementation of this changes depending\n // upon whether the select can have multiple values and whether ngOptions is at work.\n self.writeValue = function writeSingleValue(value) {\n // Make sure to remove the selected attribute from the previously selected option\n // Otherwise, screen readers might get confused\n var currentlySelectedOption = $element[0].options[$element[0].selectedIndex];\n if (currentlySelectedOption) currentlySelectedOption.removeAttribute('selected');\n\n if (self.hasOption(value)) {\n self.removeUnknownOption();\n\n var hashedVal = hashKey(value);\n $element.val(hashedVal in self.selectValueMap ? hashedVal : value);\n\n // Set selected attribute and property on selected option for screen readers\n var selectedOption = $element[0].options[$element[0].selectedIndex];\n setOptionAsSelected(jqLite(selectedOption));\n } else {\n if (value == null && self.emptyOption) {\n self.removeUnknownOption();\n self.selectEmptyOption();\n } else if (self.unknownOption.parent().length) {\n self.updateUnknownOption(value);\n } else {\n self.renderUnknownOption(value);\n }\n }\n };\n\n\n // Tell the select control that an option, with the given value, has been added\n self.addOption = function(value, element) {\n // Skip comment nodes, as they only pollute the `optionsMap`\n if (element[0].nodeType === NODE_TYPE_COMMENT) return;\n\n assertNotHasOwnProperty(value, '\"option value\"');\n if (value === '') {\n self.hasEmptyOption = true;\n self.emptyOption = element;\n }\n var count = optionsMap.get(value) || 0;\n optionsMap.put(value, count + 1);\n // Only render at the end of a digest. This improves render performance when many options\n // are added during a digest and ensures all relevant options are correctly marked as selected\n scheduleRender();\n };\n\n // Tell the select control that an option, with the given value, has been removed\n self.removeOption = function(value) {\n var count = optionsMap.get(value);\n if (count) {\n if (count === 1) {\n optionsMap.remove(value);\n if (value === '') {\n self.hasEmptyOption = false;\n self.emptyOption = undefined;\n }\n } else {\n optionsMap.put(value, count - 1);\n }\n }\n };\n\n // Check whether the select control has an option matching the given value\n self.hasOption = function(value) {\n return !!optionsMap.get(value);\n };\n\n\n var renderScheduled = false;\n function scheduleRender() {\n if (renderScheduled) return;\n renderScheduled = true;\n $scope.$$postDigest(function() {\n renderScheduled = false;\n self.ngModelCtrl.$render();\n });\n }\n\n var updateScheduled = false;\n function scheduleViewValueUpdate(renderAfter) {\n if (updateScheduled) return;\n\n updateScheduled = true;\n\n $scope.$$postDigest(function() {\n if ($scope.$$destroyed) return;\n\n updateScheduled = false;\n self.ngModelCtrl.$setViewValue(self.readValue());\n if (renderAfter) self.ngModelCtrl.$render();\n });\n }\n\n\n self.registerOption = function(optionScope, optionElement, optionAttrs, interpolateValueFn, interpolateTextFn) {\n\n if (optionAttrs.$attr.ngValue) {\n // The value attribute is set by ngValue\n var oldVal, hashedVal = NaN;\n optionAttrs.$observe('value', function valueAttributeObserveAction(newVal) {\n\n var removal;\n var previouslySelected = optionElement.prop('selected');\n\n if (isDefined(hashedVal)) {\n self.removeOption(oldVal);\n delete self.selectValueMap[hashedVal];\n removal = true;\n }\n\n hashedVal = hashKey(newVal);\n oldVal = newVal;\n self.selectValueMap[hashedVal] = newVal;\n self.addOption(newVal, optionElement);\n // Set the attribute directly instead of using optionAttrs.$set - this stops the observer\n // from firing a second time. Other $observers on value will also get the result of the\n // ngValue expression, not the hashed value\n optionElement.attr('value', hashedVal);\n\n if (removal && previouslySelected) {\n scheduleViewValueUpdate();\n }\n\n });\n } else if (interpolateValueFn) {\n // The value attribute is interpolated\n optionAttrs.$observe('value', function valueAttributeObserveAction(newVal) {\n // This method is overwritten in ngOptions and has side-effects!\n self.readValue();\n\n var removal;\n var previouslySelected = optionElement.prop('selected');\n\n if (isDefined(oldVal)) {\n self.removeOption(oldVal);\n removal = true;\n }\n oldVal = newVal;\n self.addOption(newVal, optionElement);\n\n if (removal && previouslySelected) {\n scheduleViewValueUpdate();\n }\n });\n } else if (interpolateTextFn) {\n // The text content is interpolated\n optionScope.$watch(interpolateTextFn, function interpolateWatchAction(newVal, oldVal) {\n optionAttrs.$set('value', newVal);\n var previouslySelected = optionElement.prop('selected');\n if (oldVal !== newVal) {\n self.removeOption(oldVal);\n }\n self.addOption(newVal, optionElement);\n\n if (oldVal && previouslySelected) {\n scheduleViewValueUpdate();\n }\n });\n } else {\n // The value attribute is static\n self.addOption(optionAttrs.value, optionElement);\n }\n\n\n optionAttrs.$observe('disabled', function(newVal) {\n\n // Since model updates will also select disabled options (like ngOptions),\n // we only have to handle options becoming disabled, not enabled\n\n if (newVal === 'true' || newVal && optionElement.prop('selected')) {\n if (self.multiple) {\n scheduleViewValueUpdate(true);\n } else {\n self.ngModelCtrl.$setViewValue(null);\n self.ngModelCtrl.$render();\n }\n }\n });\n\n optionElement.on('$destroy', function() {\n var currentValue = self.readValue();\n var removeValue = optionAttrs.value;\n\n self.removeOption(removeValue);\n self.ngModelCtrl.$render();\n\n if (self.multiple && currentValue && currentValue.indexOf(removeValue) !== -1 ||\n currentValue === removeValue\n ) {\n // When multiple (selected) options are destroyed at the same time, we don't want\n // to run a model update for each of them. Instead, run a single update in the $$postDigest\n scheduleViewValueUpdate(true);\n }\n });\n };\n\n function setOptionAsSelected(optionEl) {\n optionEl.prop('selected', true); // needed for IE\n optionEl.attr('selected', true);\n }\n}];\n\n/**\n * @ngdoc directive\n * @name select\n * @restrict E\n *\n * @description\n * HTML `select` element with angular data-binding.\n *\n * The `select` directive is used together with {@link ngModel `ngModel`} to provide data-binding\n * between the scope and the `` menu is selected, the value of the selected option will be bound\n * to the model identified by the `ngModel` directive. With static or repeated options, this is\n * the content of the `value` attribute or the textContent of the `