From e9736977c14345b2457f1e71943eb7f20398604a Mon Sep 17 00:00:00 2001 From: Jeado Ko Date: Sun, 24 Nov 2013 00:10:12 +0900 Subject: [PATCH 1/6] =?UTF-8?q?=EB=B2=84=EC=A0=84=201.2.1=EB=A1=9C=20?= =?UTF-8?q?=ED=86=B5=ED=95=A9?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- docs/content-ko-back/api/index.ngdoc | 6 + docs/content-ko-back/api/ng.ngdoc | 5 + .../cookbook/advancedform.ngdoc | 123 +++ docs/content-ko-back/cookbook/buzz.ngdoc | 61 ++ .../cookbook/deeplinking.ngdoc | 143 +++ docs/content-ko-back/cookbook/form.ngdoc | 110 +++ .../content-ko-back/cookbook/helloworld.ngdoc | 36 + docs/content-ko-back/cookbook/index.ngdoc | 52 + docs/content-ko-back/cookbook/mvc.ngdoc | 124 +++ docs/content-ko-back/guide/bootstrap.ngdoc | 97 ++ docs/content-ko-back/guide/compiler.ngdoc | 141 +++ docs/content-ko-back/guide/concepts.ngdoc | 467 +++++++++ .../guide/dev_guide.e2e-testing.ngdoc | 178 ++++ .../content-ko-back/guide/dev_guide.mvc.ngdoc | 22 + ...v_guide.mvc.understanding_controller.ngdoc | 280 ++++++ .../dev_guide.mvc.understanding_model.ngdoc | 66 ++ .../dev_guide.mvc.understanding_view.ngdoc | 20 + .../guide/dev_guide.services.$location.ngdoc | 643 ++++++++++++ ...dev_guide.services.creating_services.ngdoc | 104 ++ ...guide.services.injecting_controllers.ngdoc | 118 +++ ...guide.services.managing_dependencies.ngdoc | 114 +++ .../guide/dev_guide.services.ngdoc | 20 + .../dev_guide.services.testing_services.ngdoc | 62 ++ ...uide.services.understanding_services.ngdoc | 36 + .../dev_guide.templates.css-styling.ngdoc | 22 + .../dev_guide.templates.databinding.ngdoc | 39 + ...e.templates.filters.creating_filters.ngdoc | 58 ++ .../guide/dev_guide.templates.filters.ngdoc | 22 + ...uide.templates.filters.using_filters.ngdoc | 39 + .../guide/dev_guide.templates.ngdoc | 41 + .../guide/dev_guide.unit-testing.ngdoc | 296 ++++++ docs/content-ko-back/guide/di.ngdoc | 232 +++++ docs/content-ko-back/guide/directive.ngdoc | 695 +++++++++++++ docs/content-ko-back/guide/expression.ngdoc | 178 ++++ docs/content-ko-back/guide/forms.ngdoc | 324 +++++++ docs/content-ko-back/guide/i18n.ngdoc | 124 +++ docs/content-ko-back/guide/ie.ngdoc | 147 +++ docs/content-ko-back/guide/index.ngdoc | 10 + docs/content-ko-back/guide/introduction.ngdoc | 42 + docs/content-ko-back/guide/module.ngdoc | 257 +++++ docs/content-ko-back/guide/overview.ngdoc | 207 ++++ docs/content-ko-back/guide/scope.ngdoc | 331 +++++++ docs/content-ko-back/guide/type.ngdoc | 3 + docs/content-ko-back/misc/contribute.ngdoc | 268 +++++ docs/content-ko-back/misc/downloading.ngdoc | 51 + docs/content-ko-back/misc/faq.ngdoc | 215 ++++ docs/content-ko-back/misc/started.ngdoc | 33 + docs/content-ko-back/tutorial/index.ngdoc | 84 ++ docs/content-ko-back/tutorial/step_00.ngdoc | 214 ++++ docs/content-ko-back/tutorial/step_01.ngdoc | 55 ++ docs/content-ko-back/tutorial/step_02.ngdoc | 205 ++++ docs/content-ko-back/tutorial/step_03.ngdoc | 201 ++++ docs/content-ko-back/tutorial/step_04.ngdoc | 187 ++++ docs/content-ko-back/tutorial/step_05.ngdoc | 235 +++++ docs/content-ko-back/tutorial/step_06.ngdoc | 111 +++ docs/content-ko-back/tutorial/step_07.ngdoc | 262 +++++ docs/content-ko-back/tutorial/step_08.ngdoc | 194 ++++ docs/content-ko-back/tutorial/step_09.ngdoc | 139 +++ docs/content-ko-back/tutorial/step_10.ngdoc | 141 +++ docs/content-ko-back/tutorial/step_11.ngdoc | 228 +++++ docs/content-ko-back/tutorial/the_end.ngdoc | 21 + docs/content-ko-back/wordlists.md | 41 + docs/content-ko/api/index.ngdoc | 295 ++++++ docs/content-ko/api/ng.ngdoc | 8 + docs/content-ko/cookbook/advancedform.ngdoc | 122 +++ docs/content-ko/cookbook/buzz.ngdoc | 63 ++ docs/content-ko/cookbook/deeplinking.ngdoc | 151 +++ docs/content-ko/cookbook/form.ngdoc | 114 +++ docs/content-ko/cookbook/helloworld.ngdoc | 39 + docs/content-ko/cookbook/index.ngdoc | 58 ++ docs/content-ko/cookbook/mvc.ngdoc | 128 +++ docs/content-ko/error/animate/notcsel.ngdoc | 6 + docs/content-ko/error/cacheFactory/iid.ngdoc | 8 + docs/content-ko/error/compile/ctreq.ngdoc | 49 + docs/content-ko/error/compile/iscp.ngdoc | 25 + docs/content-ko/error/compile/multidir.ngdoc | 17 + .../error/compile/nodomevents.ngdoc | 20 + docs/content-ko/error/compile/nonassign.ngdoc | 41 + docs/content-ko/error/compile/selmulti.ngdoc | 20 + docs/content-ko/error/compile/tpload.ngdoc | 11 + docs/content-ko/error/compile/tplrt.ngdoc | 39 + docs/content-ko/error/compile/uterdir.ngdoc | 34 + docs/content-ko/error/controller/noscp.ngdoc | 21 + docs/content-ko/error/httpBackend/noxhr.ngdoc | 9 + docs/content-ko/error/index.ngdoc | 13 + docs/content-ko/error/injector/cdep.ngdoc | 26 + docs/content-ko/error/injector/itkn.ngdoc | 26 + docs/content-ko/error/injector/modulerr.ngdoc | 11 + docs/content-ko/error/injector/nomod.ngdoc | 26 + docs/content-ko/error/injector/pget.ngdoc | 26 + docs/content-ko/error/injector/unpr.ngdoc | 26 + .../content-ko/error/interpolate/interr.ngdoc | 7 + .../error/interpolate/noconcat.ngdoc | 12 + docs/content-ko/error/jqLite/nosel.ngdoc | 11 + docs/content-ko/error/jqLite/offargs.ngdoc | 7 + docs/content-ko/error/jqLite/onargs.ngdoc | 8 + docs/content-ko/error/location/ihshprfx.ngdoc | 17 + docs/content-ko/error/location/ipthprfx.ngdoc | 8 + docs/content-ko/error/location/isrcharg.ngdoc | 9 + docs/content-ko/error/ng/areq.ngdoc | 8 + docs/content-ko/error/ng/badname.ngdoc | 8 + docs/content-ko/error/ng/btstrpd.ngdoc | 29 + docs/content-ko/error/ng/cpi.ngdoc | 10 + docs/content-ko/error/ng/cpws.ngdoc | 10 + docs/content-ko/error/ngModel/nonassign.ngdoc | 27 + docs/content-ko/error/ngOptions/iexp.ngdoc | 13 + .../content-ko/error/ngPattern/noregexp.ngdoc | 7 + docs/content-ko/error/ngRepeat/dupes.ngdoc | 22 + docs/content-ko/error/ngRepeat/iexp.ngdoc | 12 + docs/content-ko/error/ngRepeat/iidexp.ngdoc | 25 + .../error/ngTransclude/orphan.ngdoc | 12 + docs/content-ko/error/parse/isecdom.ngdoc | 16 + docs/content-ko/error/parse/isecfld.ngdoc | 18 + docs/content-ko/error/parse/isecfn.ngdoc | 10 + docs/content-ko/error/parse/isecwindow.ngdoc | 16 + docs/content-ko/error/parse/lexerr.ngdoc | 10 + docs/content-ko/error/parse/syntax.ngdoc | 9 + docs/content-ko/error/parse/ueoe.ngdoc | 9 + docs/content-ko/error/resource/badargs.ngdoc | 9 + docs/content-ko/error/resource/badcfg.ngdoc | 11 + .../content-ko/error/resource/badmember.ngdoc | 27 + docs/content-ko/error/resource/badname.ngdoc | 8 + docs/content-ko/error/rootScope/infdig.ngdoc | 17 + docs/content-ko/error/rootScope/inprog.ngdoc | 74 ++ docs/content-ko/error/sanitize/badparse.ngdoc | 11 + docs/content-ko/error/sce/icontext.ngdoc | 8 + docs/content-ko/error/sce/iequirks.ngdoc | 15 + docs/content-ko/error/sce/imatcher.ngdoc | 9 + docs/content-ko/error/sce/insecurl.ngdoc | 26 + docs/content-ko/error/sce/itype.ngdoc | 8 + docs/content-ko/error/sce/iwcard.ngdoc | 9 + docs/content-ko/error/sce/unsafe.ngdoc | 15 + docs/content-ko/guide/animations.ngdoc | 289 ++++++ docs/content-ko/guide/bootstrap.ngdoc | 130 +++ docs/content-ko/guide/compiler.ngdoc | 377 ++++++++ docs/content-ko/guide/concepts.ngdoc | 384 ++++++++ docs/content-ko/guide/controller.ngdoc | 340 +++++++ docs/content-ko/guide/databinding.ngdoc | 38 + .../guide/dev_guide.e2e-testing.ngdoc | 312 ++++++ .../guide/dev_guide.services.$location.ngdoc | 659 +++++++++++++ ...dev_guide.services.creating_services.ngdoc | 104 ++ ...guide.services.injecting_controllers.ngdoc | 120 +++ ...guide.services.managing_dependencies.ngdoc | 114 +++ .../content-ko/guide/dev_guide.services.ngdoc | 20 + .../dev_guide.services.testing_services.ngdoc | 62 ++ ...uide.services.understanding_services.ngdoc | 60 ++ .../dev_guide.templates.css-styling.ngdoc | 31 + .../guide/dev_guide.unit-testing.ngdoc | 341 +++++++ docs/content-ko/guide/di.ngdoc | 241 +++++ docs/content-ko/guide/directive.ngdoc | 915 ++++++++++++++++++ docs/content-ko/guide/expression.ngdoc | 148 +++ docs/content-ko/guide/filter.ngdoc | 123 +++ docs/content-ko/guide/forms.ngdoc | 324 +++++++ docs/content-ko/guide/i18n.ngdoc | 124 +++ docs/content-ko/guide/ie.ngdoc | 187 ++++ docs/content-ko/guide/index.ngdoc | 183 ++++ docs/content-ko/guide/introduction.ngdoc | 108 +++ docs/content-ko/guide/migration.ngdoc | 651 +++++++++++++ docs/content-ko/guide/module.ngdoc | 275 ++++++ docs/content-ko/guide/providers.ngdoc | 425 ++++++++ docs/content-ko/guide/scope.ngdoc | 401 ++++++++ docs/content-ko/guide/templates.ngdoc | 57 ++ docs/content-ko/misc/contribute.ngdoc | 176 ++++ docs/content-ko/misc/downloading.ngdoc | 86 ++ docs/content-ko/misc/faq.ngdoc | 220 +++++ docs/content-ko/misc/started.ngdoc | 39 + docs/content-ko/notes/empty.tmp | 0 docs/content-ko/tutorial/index.ngdoc | 118 +++ docs/content-ko/tutorial/step_00.ngdoc | 206 ++++ docs/content-ko/tutorial/step_01.ngdoc | 55 ++ docs/content-ko/tutorial/step_02.ngdoc | 244 +++++ docs/content-ko/tutorial/step_03.ngdoc | 204 ++++ docs/content-ko/tutorial/step_04.ngdoc | 191 ++++ docs/content-ko/tutorial/step_05.ngdoc | 268 +++++ docs/content-ko/tutorial/step_06.ngdoc | 111 +++ docs/content-ko/tutorial/step_07.ngdoc | 308 ++++++ docs/content-ko/tutorial/step_08.ngdoc | 195 ++++ docs/content-ko/tutorial/step_09.ngdoc | 141 +++ docs/content-ko/tutorial/step_10.ngdoc | 142 +++ docs/content-ko/tutorial/step_11.ngdoc | 224 +++++ docs/content-ko/tutorial/step_12.ngdoc | 418 ++++++++ docs/content-ko/tutorial/the_end.ngdoc | 21 + 182 files changed, 21919 insertions(+) create mode 100644 docs/content-ko-back/api/index.ngdoc create mode 100644 docs/content-ko-back/api/ng.ngdoc create mode 100644 docs/content-ko-back/cookbook/advancedform.ngdoc create mode 100644 docs/content-ko-back/cookbook/buzz.ngdoc create mode 100644 docs/content-ko-back/cookbook/deeplinking.ngdoc create mode 100644 docs/content-ko-back/cookbook/form.ngdoc create mode 100644 docs/content-ko-back/cookbook/helloworld.ngdoc create mode 100644 docs/content-ko-back/cookbook/index.ngdoc create mode 100644 docs/content-ko-back/cookbook/mvc.ngdoc create mode 100644 docs/content-ko-back/guide/bootstrap.ngdoc create mode 100644 docs/content-ko-back/guide/compiler.ngdoc create mode 100644 docs/content-ko-back/guide/concepts.ngdoc create mode 100644 docs/content-ko-back/guide/dev_guide.e2e-testing.ngdoc create mode 100644 docs/content-ko-back/guide/dev_guide.mvc.ngdoc create mode 100644 docs/content-ko-back/guide/dev_guide.mvc.understanding_controller.ngdoc create mode 100644 docs/content-ko-back/guide/dev_guide.mvc.understanding_model.ngdoc create mode 100644 docs/content-ko-back/guide/dev_guide.mvc.understanding_view.ngdoc create mode 100644 docs/content-ko-back/guide/dev_guide.services.$location.ngdoc create mode 100644 docs/content-ko-back/guide/dev_guide.services.creating_services.ngdoc create mode 100644 docs/content-ko-back/guide/dev_guide.services.injecting_controllers.ngdoc create mode 100644 docs/content-ko-back/guide/dev_guide.services.managing_dependencies.ngdoc create mode 100644 docs/content-ko-back/guide/dev_guide.services.ngdoc create mode 100644 docs/content-ko-back/guide/dev_guide.services.testing_services.ngdoc create mode 100644 docs/content-ko-back/guide/dev_guide.services.understanding_services.ngdoc create mode 100644 docs/content-ko-back/guide/dev_guide.templates.css-styling.ngdoc create mode 100644 docs/content-ko-back/guide/dev_guide.templates.databinding.ngdoc create mode 100644 docs/content-ko-back/guide/dev_guide.templates.filters.creating_filters.ngdoc create mode 100644 docs/content-ko-back/guide/dev_guide.templates.filters.ngdoc create mode 100644 docs/content-ko-back/guide/dev_guide.templates.filters.using_filters.ngdoc create mode 100644 docs/content-ko-back/guide/dev_guide.templates.ngdoc create mode 100644 docs/content-ko-back/guide/dev_guide.unit-testing.ngdoc create mode 100644 docs/content-ko-back/guide/di.ngdoc create mode 100644 docs/content-ko-back/guide/directive.ngdoc create mode 100644 docs/content-ko-back/guide/expression.ngdoc create mode 100644 docs/content-ko-back/guide/forms.ngdoc create mode 100644 docs/content-ko-back/guide/i18n.ngdoc create mode 100644 docs/content-ko-back/guide/ie.ngdoc create mode 100644 docs/content-ko-back/guide/index.ngdoc create mode 100644 docs/content-ko-back/guide/introduction.ngdoc create mode 100644 docs/content-ko-back/guide/module.ngdoc create mode 100644 docs/content-ko-back/guide/overview.ngdoc create mode 100644 docs/content-ko-back/guide/scope.ngdoc create mode 100644 docs/content-ko-back/guide/type.ngdoc create mode 100644 docs/content-ko-back/misc/contribute.ngdoc create mode 100644 docs/content-ko-back/misc/downloading.ngdoc create mode 100644 docs/content-ko-back/misc/faq.ngdoc create mode 100644 docs/content-ko-back/misc/started.ngdoc create mode 100644 docs/content-ko-back/tutorial/index.ngdoc create mode 100644 docs/content-ko-back/tutorial/step_00.ngdoc create mode 100644 docs/content-ko-back/tutorial/step_01.ngdoc create mode 100644 docs/content-ko-back/tutorial/step_02.ngdoc create mode 100644 docs/content-ko-back/tutorial/step_03.ngdoc create mode 100644 docs/content-ko-back/tutorial/step_04.ngdoc create mode 100644 docs/content-ko-back/tutorial/step_05.ngdoc create mode 100644 docs/content-ko-back/tutorial/step_06.ngdoc create mode 100644 docs/content-ko-back/tutorial/step_07.ngdoc create mode 100644 docs/content-ko-back/tutorial/step_08.ngdoc create mode 100644 docs/content-ko-back/tutorial/step_09.ngdoc create mode 100644 docs/content-ko-back/tutorial/step_10.ngdoc create mode 100644 docs/content-ko-back/tutorial/step_11.ngdoc create mode 100644 docs/content-ko-back/tutorial/the_end.ngdoc create mode 100644 docs/content-ko-back/wordlists.md create mode 100644 docs/content-ko/api/index.ngdoc create mode 100644 docs/content-ko/api/ng.ngdoc create mode 100644 docs/content-ko/cookbook/advancedform.ngdoc create mode 100644 docs/content-ko/cookbook/buzz.ngdoc create mode 100644 docs/content-ko/cookbook/deeplinking.ngdoc create mode 100644 docs/content-ko/cookbook/form.ngdoc create mode 100644 docs/content-ko/cookbook/helloworld.ngdoc create mode 100644 docs/content-ko/cookbook/index.ngdoc create mode 100644 docs/content-ko/cookbook/mvc.ngdoc create mode 100644 docs/content-ko/error/animate/notcsel.ngdoc create mode 100644 docs/content-ko/error/cacheFactory/iid.ngdoc create mode 100644 docs/content-ko/error/compile/ctreq.ngdoc create mode 100644 docs/content-ko/error/compile/iscp.ngdoc create mode 100644 docs/content-ko/error/compile/multidir.ngdoc create mode 100644 docs/content-ko/error/compile/nodomevents.ngdoc create mode 100644 docs/content-ko/error/compile/nonassign.ngdoc create mode 100644 docs/content-ko/error/compile/selmulti.ngdoc create mode 100644 docs/content-ko/error/compile/tpload.ngdoc create mode 100644 docs/content-ko/error/compile/tplrt.ngdoc create mode 100644 docs/content-ko/error/compile/uterdir.ngdoc create mode 100644 docs/content-ko/error/controller/noscp.ngdoc create mode 100644 docs/content-ko/error/httpBackend/noxhr.ngdoc create mode 100644 docs/content-ko/error/index.ngdoc create mode 100644 docs/content-ko/error/injector/cdep.ngdoc create mode 100644 docs/content-ko/error/injector/itkn.ngdoc create mode 100644 docs/content-ko/error/injector/modulerr.ngdoc create mode 100644 docs/content-ko/error/injector/nomod.ngdoc create mode 100644 docs/content-ko/error/injector/pget.ngdoc create mode 100644 docs/content-ko/error/injector/unpr.ngdoc create mode 100644 docs/content-ko/error/interpolate/interr.ngdoc create mode 100644 docs/content-ko/error/interpolate/noconcat.ngdoc create mode 100644 docs/content-ko/error/jqLite/nosel.ngdoc create mode 100644 docs/content-ko/error/jqLite/offargs.ngdoc create mode 100644 docs/content-ko/error/jqLite/onargs.ngdoc create mode 100644 docs/content-ko/error/location/ihshprfx.ngdoc create mode 100644 docs/content-ko/error/location/ipthprfx.ngdoc create mode 100644 docs/content-ko/error/location/isrcharg.ngdoc create mode 100644 docs/content-ko/error/ng/areq.ngdoc create mode 100644 docs/content-ko/error/ng/badname.ngdoc create mode 100644 docs/content-ko/error/ng/btstrpd.ngdoc create mode 100644 docs/content-ko/error/ng/cpi.ngdoc create mode 100644 docs/content-ko/error/ng/cpws.ngdoc create mode 100644 docs/content-ko/error/ngModel/nonassign.ngdoc create mode 100644 docs/content-ko/error/ngOptions/iexp.ngdoc create mode 100644 docs/content-ko/error/ngPattern/noregexp.ngdoc create mode 100644 docs/content-ko/error/ngRepeat/dupes.ngdoc create mode 100644 docs/content-ko/error/ngRepeat/iexp.ngdoc create mode 100644 docs/content-ko/error/ngRepeat/iidexp.ngdoc create mode 100644 docs/content-ko/error/ngTransclude/orphan.ngdoc create mode 100644 docs/content-ko/error/parse/isecdom.ngdoc create mode 100644 docs/content-ko/error/parse/isecfld.ngdoc create mode 100644 docs/content-ko/error/parse/isecfn.ngdoc create mode 100644 docs/content-ko/error/parse/isecwindow.ngdoc create mode 100644 docs/content-ko/error/parse/lexerr.ngdoc create mode 100644 docs/content-ko/error/parse/syntax.ngdoc create mode 100644 docs/content-ko/error/parse/ueoe.ngdoc create mode 100644 docs/content-ko/error/resource/badargs.ngdoc create mode 100644 docs/content-ko/error/resource/badcfg.ngdoc create mode 100644 docs/content-ko/error/resource/badmember.ngdoc create mode 100644 docs/content-ko/error/resource/badname.ngdoc create mode 100644 docs/content-ko/error/rootScope/infdig.ngdoc create mode 100644 docs/content-ko/error/rootScope/inprog.ngdoc create mode 100644 docs/content-ko/error/sanitize/badparse.ngdoc create mode 100644 docs/content-ko/error/sce/icontext.ngdoc create mode 100644 docs/content-ko/error/sce/iequirks.ngdoc create mode 100644 docs/content-ko/error/sce/imatcher.ngdoc create mode 100644 docs/content-ko/error/sce/insecurl.ngdoc create mode 100644 docs/content-ko/error/sce/itype.ngdoc create mode 100644 docs/content-ko/error/sce/iwcard.ngdoc create mode 100644 docs/content-ko/error/sce/unsafe.ngdoc create mode 100644 docs/content-ko/guide/animations.ngdoc create mode 100644 docs/content-ko/guide/bootstrap.ngdoc create mode 100644 docs/content-ko/guide/compiler.ngdoc create mode 100644 docs/content-ko/guide/concepts.ngdoc create mode 100644 docs/content-ko/guide/controller.ngdoc create mode 100644 docs/content-ko/guide/databinding.ngdoc create mode 100644 docs/content-ko/guide/dev_guide.e2e-testing.ngdoc create mode 100644 docs/content-ko/guide/dev_guide.services.$location.ngdoc create mode 100644 docs/content-ko/guide/dev_guide.services.creating_services.ngdoc create mode 100644 docs/content-ko/guide/dev_guide.services.injecting_controllers.ngdoc create mode 100644 docs/content-ko/guide/dev_guide.services.managing_dependencies.ngdoc create mode 100644 docs/content-ko/guide/dev_guide.services.ngdoc create mode 100644 docs/content-ko/guide/dev_guide.services.testing_services.ngdoc create mode 100644 docs/content-ko/guide/dev_guide.services.understanding_services.ngdoc create mode 100644 docs/content-ko/guide/dev_guide.templates.css-styling.ngdoc create mode 100644 docs/content-ko/guide/dev_guide.unit-testing.ngdoc create mode 100644 docs/content-ko/guide/di.ngdoc create mode 100644 docs/content-ko/guide/directive.ngdoc create mode 100644 docs/content-ko/guide/expression.ngdoc create mode 100644 docs/content-ko/guide/filter.ngdoc create mode 100644 docs/content-ko/guide/forms.ngdoc create mode 100644 docs/content-ko/guide/i18n.ngdoc create mode 100644 docs/content-ko/guide/ie.ngdoc create mode 100644 docs/content-ko/guide/index.ngdoc create mode 100644 docs/content-ko/guide/introduction.ngdoc create mode 100644 docs/content-ko/guide/migration.ngdoc create mode 100644 docs/content-ko/guide/module.ngdoc create mode 100644 docs/content-ko/guide/providers.ngdoc create mode 100644 docs/content-ko/guide/scope.ngdoc create mode 100644 docs/content-ko/guide/templates.ngdoc create mode 100644 docs/content-ko/misc/contribute.ngdoc create mode 100644 docs/content-ko/misc/downloading.ngdoc create mode 100644 docs/content-ko/misc/faq.ngdoc create mode 100644 docs/content-ko/misc/started.ngdoc create mode 100644 docs/content-ko/notes/empty.tmp create mode 100644 docs/content-ko/tutorial/index.ngdoc create mode 100644 docs/content-ko/tutorial/step_00.ngdoc create mode 100644 docs/content-ko/tutorial/step_01.ngdoc create mode 100644 docs/content-ko/tutorial/step_02.ngdoc create mode 100644 docs/content-ko/tutorial/step_03.ngdoc create mode 100644 docs/content-ko/tutorial/step_04.ngdoc create mode 100644 docs/content-ko/tutorial/step_05.ngdoc create mode 100644 docs/content-ko/tutorial/step_06.ngdoc create mode 100644 docs/content-ko/tutorial/step_07.ngdoc create mode 100644 docs/content-ko/tutorial/step_08.ngdoc create mode 100644 docs/content-ko/tutorial/step_09.ngdoc create mode 100644 docs/content-ko/tutorial/step_10.ngdoc create mode 100644 docs/content-ko/tutorial/step_11.ngdoc create mode 100644 docs/content-ko/tutorial/step_12.ngdoc create mode 100644 docs/content-ko/tutorial/the_end.ngdoc diff --git a/docs/content-ko-back/api/index.ngdoc b/docs/content-ko-back/api/index.ngdoc new file mode 100644 index 000000000000..6dcc0bc47754 --- /dev/null +++ b/docs/content-ko-back/api/index.ngdoc @@ -0,0 +1,6 @@ +@ngdoc overview +@name API 레퍼런스(Reference) +@description + +특정 기능에 대한 더 많은 정보가 필요하시면, API 레퍼런스를 사용하십시오. AngularJS 개념을 잡기위해 {@link guide/ Developer Guide}를 확인하십시오. +AngularJS가 처음이신 분들에게는 {@link tutorial/ Tutorial}를 추천드립니다. \ No newline at end of file diff --git a/docs/content-ko-back/api/ng.ngdoc b/docs/content-ko-back/api/ng.ngdoc new file mode 100644 index 000000000000..30bb6fd314e9 --- /dev/null +++ b/docs/content-ko-back/api/ng.ngdoc @@ -0,0 +1,5 @@ +@ngdoc overview +@name ng +@description + +'ng'는 주요 angular 서비스(service)의 모든 것을 담고 있는 angular 모듈(module)입니다. \ No newline at end of file diff --git a/docs/content-ko-back/cookbook/advancedform.ngdoc b/docs/content-ko-back/cookbook/advancedform.ngdoc new file mode 100644 index 000000000000..f9b5751e6459 --- /dev/null +++ b/docs/content-ko-back/cookbook/advancedform.ngdoc @@ -0,0 +1,123 @@ +@ngdoc overview +@name Cookbook: 향상된 폼(Advanced Form) +@description + +이제 저희는 되돌리기, 변경된 부분 찾기, 잘못된 폼양식 제출과 같은 기본 기능을 포함한 기본 폼 양식 예제를 확장시키려 합니다. + + + + +
+ +
+ +
+

+ +
+
+ , + +

+ + + [ add ] +
+ + + [ X ] +
+ + +
+ +
+ Debug View: +
form={{form}}
+
+
+ + it('should enable save button', function() { + expect(element(':button:contains(Save)').attr('disabled')).toBeTruthy(); + input('form.name').enter(''); + expect(element(':button:contains(Save)').attr('disabled')).toBeTruthy(); + input('form.name').enter('change'); + expect(element(':button:contains(Save)').attr('disabled')).toBeFalsy(); + element(':button:contains(Save)').click(); + expect(element(':button:contains(Save)').attr('disabled')).toBeTruthy(); + }); + it('should enable cancel button', function() { + expect(element(':button:contains(Cancel)').attr('disabled')).toBeTruthy(); + input('form.name').enter('change'); + expect(element(':button:contains(Cancel)').attr('disabled')).toBeFalsy(); + element(':button:contains(Cancel)').click(); + expect(element(':button:contains(Cancel)').attr('disabled')).toBeTruthy(); + expect(element(':input[ng\\:model="form.name"]').val()).toEqual('John Smith'); + }); + +
+ + +# 알아두어야 할 사항들 + +* 취소(Cancel)과 저장(save) 버튼은 - 취소나 저장 할게 있을 때 - 양식안에 변경사항이 생길 때만 사용가능 상태가 됩니다. +* 저장(save) 버튼은 폼에 에러가 없을 경우에만 사용가능 상태가 됩니다. +* 저장(save)은 폼의 내부 모델(model)을 업데이트합니다. +* 디버그 뷰(Debug View)는 두가지 모델을 보여쥡니다. 하나는 사용자 폼을, 다른 하나는 본래의 카피마스터(copy mater)를 제공합니다. \ No newline at end of file diff --git a/docs/content-ko-back/cookbook/buzz.ngdoc b/docs/content-ko-back/cookbook/buzz.ngdoc new file mode 100644 index 000000000000..bab60cb9d2e6 --- /dev/null +++ b/docs/content-ko-back/cookbook/buzz.ngdoc @@ -0,0 +1,61 @@ +@ngdoc overview +@name Cookbook: 리소스(Resources) - Buzz +@description + +외부 리소스는 템플릿의 도움을 받아 구현되는 JSON데이터를 제공하는 URL들입니다. Angular는 그 URL들에게 이름을 부여하고, 그들에게 행동(behavior)를 추가하여 +사용될 수 있도록 하는 리소스 팩토리(resource factory)을 가지고 있습니다. 예를 들어 당신은 Buzz 활동(activity)과 코멘트(comments)를 검색하는 +{@link http://code.google.com/apis/buzz/v1/getting_started.html#background-operations| Google BuzzAPI}를 사용할 수 있습니다. + + + + + +
+ + +
+
+

+ + {{item.actor.name}} + + Expand replies: {{item.links.replies[0].count}} + +

+ {{item.object.content | html}} +
+ + {{reply.actor.name}}: + {{reply.content | html}} +
+
+
+
+ + xit('fetch buzz and expand', function() { + element(':button:contains(fetch)').click(); + expect(repeater('div.buzz').count()).toBeGreaterThan(0); + element('.buzz a:contains(Expand replies):first').click(); + expect(repeater('div.reply').count()).toBeGreaterThan(0); + }); + +
diff --git a/docs/content-ko-back/cookbook/deeplinking.ngdoc b/docs/content-ko-back/cookbook/deeplinking.ngdoc new file mode 100644 index 000000000000..34077f1abbdd --- /dev/null +++ b/docs/content-ko-back/cookbook/deeplinking.ngdoc @@ -0,0 +1,143 @@ +@ngdoc overview +@name Cookbook: Deep Linking +@description + +Deep linking URL안에 어플리케이션의 상태를 표현 할 수 있도록 합니다. 그래서 북마크로 쓰일수도 있고, 어플리케이션은 URL로부터 같은 상태를 받아 저장을 할 수 +있습니다. + +Angular는 어떤 특별한 방법으로 당신이 북마크를 다루도록 강요하지는 않습니다. 다만, 아래와 같이 기술된 것과 같은 일반적인 사례를 아주 쉽게 구현하게 하는 +서비스를 가지고 있습니다. + +# 가정(Assumptions) + +당신의 어플리케이션은 어플리케이션을 붓스트랩(bootstrap)하는 단일 HTML페이지로 구성되어 있습니다. 당신은 크롬(chrome)으로서 이 페이지를 사용할 것입니다. +당신의 어플리케이션은 사용자가 방문할 수 있는 여러개의 화면 (또는 뷰)로 나누어집니다. 예를 들어, 홈, 셋팅, 디테일 화면 등등으로 말입니다. 이런 각각의 스크린을 +위해서 북마크 할수도 있고, 나중에 복구를 할 수도 있도록 하기 위해 우리는 URL를 부여하고 싶습니다. 이런 화면의 각각은 화면의 행동(behavior)를 정의해놓은 +컨트롤러로 구성될 것 입니다. 일반적인 경우 우리가 일부를 참조하게 될 작은 HTML일부로 구성될 것입니다. 화면은 여러 조각으로 구성될 수 있으나, 단일구성이 일반적입니다. +이 예제는 화면구성의 경계를 파란 라인(line)을 사용하여 보일 수 있도록 만듭니다. + + +일부는 뷰 템플릿으로, 일부는 컨트롤러(controller)로 가게하는 URL지도를 보여주는 라우팅테이블(routing table)을 만들 수 있습니다. + +# 예제 + +이 예제에서는 두개의 화면으로 구성된 간단한 앱을 구현합니다. + +* 환영(welcome): url `welcome`는 사용자 연락처 정보를 보여줍니다. +* 셋팅(setting): url `settings`는 사용자 연락처 정보를 수정하는 화면을 보여줍니다. + + + + angular.module('deepLinking', ['ngSanitize']) + .config(function($routeProvider) { + $routeProvider. + when("/welcome", {templateUrl:'welcome.html', controller:WelcomeCntl}). + when("/settings", {templateUrl:'settings.html', controller:SettingsCntl}); + }); + + AppCntl.$inject = ['$scope', '$route'] + function AppCntl($scope, $route) { + $scope.$route = $route; + + // initialize the model to something useful + $scope.person = { + name:'anonymous', + contacts:[{type:'email', url:'anonymous@example.com'}] + }; + } + + function WelcomeCntl($scope) { + $scope.greet = function() { + alert("Hello " + $scope.person.name); + }; + } + + function SettingsCntl($scope, $location) { + $scope.cancel = function() { + $scope.form = angular.copy($scope.person); + }; + + $scope.save = function() { + angular.copy($scope.form, $scope.person); + $location.path('/welcome'); + }; + + $scope.cancel(); + } + + + [ng-view] { + border: 1px solid blue; + margin: 0; + padding:1em; + } + + .partial-info { + background-color: blue; + color: white; + padding: 3px; + } + + +
+

Your App Chrome

+ [ Welcome | Settings ] +
+ + Partial: {{$route.current.template}} + +
+ Your app footer +
+
+ + + + +
+ + + [ X ] +
+
+ [ add ] +
+ + + +
+ + Hello {{person.name}}, +
+ Your contact information: +
{{contact.type}}: + +
+
+
+ + it('should navigate to URL', function() { + element('a:contains(Welcome)').click(); + expect(element('[ng-view]').text()).toMatch(/Hello anonymous/); + element('a:contains(Settings)').click(); + input('form.name').enter('yourname'); + element(':button:contains(Save)').click(); + element('a:contains(Welcome)').click(); + expect(element('[ng-view]').text()).toMatch(/Hello yourname/); + }); + +
+ + + +# 알아두어야 할 사항들 + +* 라우트는 `AppCntl`클래스에 정의됩니다. 컨트롤러의 초기화는 적정 URL 라우트와 {@link api/ng.$route $route}서비스를 초기화 시킵니다. +* {@link api/ng.$route $route}서비스는 URL이 변경될 때마다 지정한 컨트롤러를 초기화하고, 그 URL를 바라보게 됩니다. +* {@link api/ng.directive:ngView ngView} 위젯(widget)은 URL이 변경될 때마다 뷰를 불러옵니다. 이는 또한 뷰 스콥(view scope)을 새로 인스턴스화된 +컨트롤러에 적용 시킵니다.. +* URL을 변경하는 것만으로 컨트롤러와 뷰를 변경하기에 충분합니다. 이는 URL을 프로그램적으로 변경하든, 사용자가 변경하든 동인한 작동을 합니다. \ No newline at end of file diff --git a/docs/content-ko-back/cookbook/form.ngdoc b/docs/content-ko-back/cookbook/form.ngdoc new file mode 100644 index 000000000000..8f4f567e8e62 --- /dev/null +++ b/docs/content-ko-back/cookbook/form.ngdoc @@ -0,0 +1,110 @@ +@ngdoc overview +@name Cookbook: 폼양식(Form) +@description + +웹 어플리케이션(web application)의 주 목적은 데이터를 제공하고 수집하는데 있습니다. 이런 이유에서 Angular는 데이터를 제공하고 수집하는 두 일들을 신경쓸 +필요가 없게 만들려고 노력하고 있습니다. 이 예제는 사용자가 데이터를 입력하도록 하는 간단한 폼양식을 만들수 있도록 보여줍니다. + + + + + +
+ +
+

+ +
+
+ , + +

+ + + [ add ] +
+ + + [ X ] +
+
+ Debug View: +
user={{user | json}}
+
+ +
+ + it('should show debug', function() { + expect(binding('user')).toMatch(/John Smith/); + }); + it('should add contact', function() { + using('.example').element('a:contains(add)').click(); + using('.example div:last').input('contact.value').enter('you@example.org'); + expect(binding('user')).toMatch(/\(234\) 555\-1212/); + expect(binding('user')).toMatch(/you@example.org/); + }); + + it('should remove contact', function() { + using('.example').element('a:contains(X)').click(); + expect(binding('user')).not().toMatch(/\(234\) 555\-1212/); + }); + + it('should validate zip', function() { + expect(using('.example'). + element(':input[ng\\:model="user.address.zip"]'). + prop('className')).not().toMatch(/ng-invalid/); + using('.example').input('user.address.zip').enter('abc'); + expect(using('.example'). + element(':input[ng\\:model="user.address.zip"]'). + prop('className')).toMatch(/ng-invalid/); + }); + + it('should validate state', function() { + expect(using('.example').element(':input[ng\\:model="user.address.state"]').prop('className')) + .not().toMatch(/ng-invalid/); + using('.example').input('user.address.state').enter('XXX'); + expect(using('.example').element(':input[ng\\:model="user.address.state"]').prop('className')) + .toMatch(/ng-invalid/); + }); + +
+ + +# 알아두어야 할 사항들 + +* 사용자 데이터 모델은 초기화 됩니다 {@link api/ng.directive:ngController 컨트롤러(controller)} 그리고 초기값과 함께 {@link api/ng.$rootScope.Scope 스콥(scope)} +에서 접근 가능하게 됩니다. +* 디버그 목적으로 어떻게 진행되고 있는지 좀 더 잘 이해할 수 있도록 모델의 디버그 뷰를 추가하였습니다. +* {@link api/ng.directive:input input 지시자(directives)}는 단순히 모델을 참조하는 데이터결속체(data-bound) 입니다. +* 입력값 유효화하기 ( 빈칸으로 남겨두도록 하거나 또는 zip필드(field)에 숫자가 입력되지 않도록 하십시오) +* 어플리케이션 안에서는 모델을 단순히 읽고 쓸 수 있으며, 폼양식은 (자동으로) 업데이트 될 것입니다. +* 'add'링크를 클릭하면 user.contacts 배열(array)에 새로운 아이템을 추가하게 되고 뷰에 반영되게 됩니다. \ No newline at end of file diff --git a/docs/content-ko-back/cookbook/helloworld.ngdoc b/docs/content-ko-back/cookbook/helloworld.ngdoc new file mode 100644 index 000000000000..ee02d23e6582 --- /dev/null +++ b/docs/content-ko-back/cookbook/helloworld.ngdoc @@ -0,0 +1,36 @@ +@ngdoc overview +@name Cookbook: Hello World +@description + + + + +
+ Your name: +
+ Hello {{name}}! +
+
+ + it('should change the binding when user enters text', function() { + expect(binding('name')).toEqual('World'); + input('name').enter('angular'); + expect(binding('name')).toEqual('angular'); + }); + +
+ +# 알아두어야 할 사항들 + +소스와 노트를 모두 훑어 보십시오. + +* Angular환경을 {@link guide/bootstrap 부트스트랩(bootstraps)}하는 스크립트 태그(script tag) +* 인사문구에 바인딩되는 {@link api/ng.directive:input input 폼약식 컨트롤(form control)} 문자. +* 리스너를 등록하거나 변경 이벤트들을 발생할 필요가 없습니다. +* 루트(root){@link api/ng.$rootScope.Scope scope}에 있는 `name`변수의 내부적 존재. +* 인사문구에 이름변수를 결속시키는 이중 꺾인 괄호 `{{markup}}`. +* 인사문구의 input 필드(field)에 어떤 변화든 반응하는 {@link guide/dev_guide.templates.databinding 데이터바인딩(data binding)} 개념. \ No newline at end of file diff --git a/docs/content-ko-back/cookbook/index.ngdoc b/docs/content-ko-back/cookbook/index.ngdoc new file mode 100644 index 000000000000..43ed213eee58 --- /dev/null +++ b/docs/content-ko-back/cookbook/index.ngdoc @@ -0,0 +1,52 @@ +@ngdoc overview +@name Cookbook +@description + +Angular cookbook에 오신 것을 환영합니다. 이제 Angular의 일반적인 사용을 예를 이용하여 보여드리겠습니다. +Welcome to the Angular cookbook. Here we will show you typical uses of Angular by example. + + +# Hello World + +{@link helloworld Hello World}: 클래식한 Hello World!를 보여드리는 가능한 가장 간단한 어플리케이션. + + +# 기본 폼 양식(Basic Form) + +{@link form Basic Form}: 사용자가 수정을 할 수 있도록 폼양식을 보여주는 것은 웹 어플리케이션의 가장 기본이다. Angular는 양방향 데이터 바인딩을 이용하여 +폼양식을 쉽게 만듭니다. + + +# 진보된 폼양식(Advanced Form) + +{@link advancedform Advanced Form}: 폼양식 예제를 다음 단계로 이끌고, 수정사항 인식, 폼 되돌리기, 그리고 변수에 에러(error)가 존재할 경우 제출을 +불가능하게 하는 등의 고급 기능을 제공하기. + + +# 모델 뷰 컨트롤러(MVC- Model View Controller) +# Model View Controller + +{@link mvc MVC}: 틱-택-토(Tic-Tac-Toe): MVC는 보여주는 것(HTML view)으로부터 행동(behavior - Javascript controller)를 구분하는 오랜시간 +효용성이 검증된 디자인 패턴입니다. 이 두의 구분은 당신의 프로젝트의 보존성과 테스트가능성에 대해 도움을 줍니다. + + +# 다중 페이지 앱과 딥 링킹(deep linking) + +{@link deeplinking Deep Linking}: AJAX 어플리케이션은 처음 로딩한 페이지를 떠나지 않습니다. 대신, 단일 페이지의 DOM을 변경합니다. 전체 페이지 +재로딩(reload)를 제거하는 것은 AJAX 앱을 반응하도록 합니다. 그러나 이는 단일 URL의 앱이 어플리케이션 내의 특정 화면으로 이메일링크를 보내지 못하도록 막는 +문제를 만듭니다. // 검토!! + +딥링킹은 페이지 재로딩을 하지 않고 URL 앵커(anchor)를 변경함으로서 이를 해결합니다. 그러므로 앱내의 특정 화면에서 링크를 발송 할 수 있도록 가능하게 합니다. + + +# 서비스(services) + +{@link api/ng Services}: 서비스는 컨트롤러 전역으로 접근 가능한 어플리케이션 내의 장수(long lived) 오브젝트 입니다. 유용한 서비스 모음은 Angular와 +함께 미리 번들화 되어있습니다. 그러나 당신은 당신만의 서비스를 추가하고 싶을 것입니다. 서비스는 의존 주입(dependency injection)를 이용하여 초기화 됩니다. +이는 초기화의 순서를 해결합니다. 그리고 글로벌 상태(global state)의 위험으로부터 당신을 보호 합니다 (장수 오브젝트를 구현하는 일반적인 방법입니다) + + +# 외부 리소스(External Resources) + +{@link buzz Resources}: 웹 어플리케이션은 데이터 업데이트와 데이터 확보를 위ㅐ서 외부 서비스와 교신을 해야만 합니다. 리소스는 Angular 데이터 바인딩으로 +특별히 연결되는 외부 URL의 추상화 입니다. \ No newline at end of file diff --git a/docs/content-ko-back/cookbook/mvc.ngdoc b/docs/content-ko-back/cookbook/mvc.ngdoc new file mode 100644 index 000000000000..2b256f08010b --- /dev/null +++ b/docs/content-ko-back/cookbook/mvc.ngdoc @@ -0,0 +1,124 @@ +@ngdoc overview +@name Cookbook: MVC +@description + +MVC는 깔끔하고, 행동(behavior, controller)와 뷰(HTML 템플릿)를 테스트 가능하도록 구분할 수 있게 한다. 컨트롤러(controller)는 그러 뷰의 +스콥(scope)에 접목된 자바스크립트 클래스이다. 이는 컨트롤러와 뷰가 모델을 공유할 수 있도록 쉽게 만들어줍니다. + +모델은 스콥오브젝트(($scope)로부터 참조되는 기초요소와 오브젝트 세트 입니다. +이는 컨트롤러를 쉽게 인스턴트화 할 수 있고, 뷰 없이 테스트를 할 수 있기 때문에 독립 상태에서 모델이 컨트롤러를 아주 쉽게 테스트하도록 만들어줍니다. 이는 +컨트롤러와 뷰 사이에 어떠한 연결도 없기 때문입니다. + + + + + + +

Tic-Tac-Toe

+
+ Next Player: {{nextMove}} +
Player {{winner}} has won!
+ + + + +
{{cell}}
+ +
+
+ + it('should play a game', function() { + piece(1, 1); + expect(binding('nextMove')).toEqual('O'); + piece(3, 1); + expect(binding('nextMove')).toEqual('X'); + piece(1, 2); + piece(3, 2); + piece(1, 3); + expect(element('.winner').text()).toEqual('Player X has won!'); + }); + + function piece(row, col) { + element('.board tr:nth-child('+row+') td:nth-child('+col+')').click(); + } + +
+ + +# 알아두어야 할 사항들 + +* 컨트롤러는 자바스크립트로 정의 되어있고, 렌더링로직(rendering logic)을 참조하지 않습니다.. +* 컨트롤러는 Angular에 의해 인스턴트화 되었고, 뷰에 주입되었습니다. +* 컨트롤러는 독립상태(뷰 없이) 인스턴트화 되었지만, 여전히 실행 가능할 것 입니다. 이는 테스트가 가능하도록 합니다. +* HTML 뷰는 모델의 형상화 입니다. 위의 예제에서 모델은 보드 변수(board variable)에 저장됩니다. +* 모든 컨트롤러의 프로퍼티(properties - board, nextMove와 같은)는 뷰에서 접근 가능합니다. +* 모델을 변경하는 것은 뷰를 변경합니다. +* 뷰는 어떤 컨트롤러 함수든 호출 할 수 있습니다. +* 예제에서 `setUrl()` 와 `readUrl()`함수는 브라우저(browser)의 뒤로가기 버튼이 게임 단계를 되돌릴 수 있도록 하기 위해서 URL의 해쉬(hash)로 또는 +해쉬로 부터 게임 상태를 복사합니다. 딥 링킹을 확인하십시오. 이 예제는 필요할 때 `readUrl()`를 발현하도록 리스너(listener)를 설정하기 위해서 +{@link api/ng.$rootScope.Scope#$watch $watch()}를 호출 합니다. \ No newline at end of file diff --git a/docs/content-ko-back/guide/bootstrap.ngdoc b/docs/content-ko-back/guide/bootstrap.ngdoc new file mode 100644 index 000000000000..14def020d89d --- /dev/null +++ b/docs/content-ko-back/guide/bootstrap.ngdoc @@ -0,0 +1,97 @@ +@ngdoc overview +@name Developer Guide: 부트스트랩(Bootstrap) +@description + +# 개요 + +이 페이지는 Angular의 초기화 과정을 설명하고, 필요할 경우 수동으로 초기화하는 방법에 대해서 알려준다. + + +# Angular ` + + + + + + +# 수동 초기화 + +만약 초기화 과정에서 보다 효율적으로 제어할 필요가 있다면 수동으로 부트스트랩하는 방법을 사용할 수 있다. +스크립트 로더를 사용하거나 Angular가 페이지를 컴파일하기 전에 수행해야 할 작업이 있는 경우가 그렇다. + + +아래 Angular를 수동으로 초기화하는 예제가 있다. 이것은 {@link api/ng.directive:ngApp ng-app} 지시자를 +사용하는 것과 동일한 예제이다. + +
+
+
+  
+    Hello {{'World'}}!
+    
+    
+  
+
+
+ +코드는 다음 순서를 따라야 한다: + + 1. 페이지와 모든 코드가 로드된 다음 일반적으로 문서의 루트인 HTML 템플릿의 루트를 찾아라. + + 2. 템플릿을 양방향 바인딩 어플리케이션으로 실행 가능하도록 {@link compiler 컴파일} 하기 위해 {@link api/angular.bootstrap} 을 + 호출해라. diff --git a/docs/content-ko-back/guide/compiler.ngdoc b/docs/content-ko-back/guide/compiler.ngdoc new file mode 100644 index 000000000000..9915107b4db4 --- /dev/null +++ b/docs/content-ko-back/guide/compiler.ngdoc @@ -0,0 +1,141 @@ +@ngdoc overview +@name Developer Guide: HTML Compiler +@description + +# Overview + +Angular's {@link api/ng.$compile HTML compiler} allows the developer to teach the +browser new HTML syntax. The compiler allows you to attach behavior to any HTML element or attribute +and even create new HTML element or attributes with custom behavior. Angular calls these behavior +extensions {@link api/ng.$compileProvider#directive directives}. + +HTML has a lot of constructs for formatting the HTML for static documents in a declarative fashion. +For example if something needs to be centered, there is no need to provide instructions to the +browser how the window size needs to be divided in half so that center is found, and that this +center needs to be aligned with the text's center. Simply add `align="center"` attribute to any +element to achieve the desired behavior. Such is the power of declarative language. + +But the declarative language is also limited, since it does not allow you to teach the browser new +syntax. For example there is no easy way to get the browser to align the text at 1/3 the position +instead of 1/2. What is needed is a way to teach browser new HTML syntax. + +Angular comes pre-bundled with common directives which are useful for building any app. We also +expect that you will create directives that are specific to your app. These extension become a +Domain Specific Language for building your application. + +All of this compilation takes place in the web browser; no server side or pre-compilation step is +involved. + + +# Compiler + +Compiler is an angular service which traverses the DOM looking for attributes. The compilation +process happens into two phases. + + 1. **Compile:** traverse the DOM and collect all of the directives. The result is a linking + function. + + 2. **Link:** combine the directives with a scope and produce a live view. Any changes in the + scope model are reflected in the view, and any user interactions with the view are reflected + in the scope model. This makes the scope model the single source of truth. + +Some directives such {@link api/ng.directive:ngRepeat +`ng-repeat`} clone DOM elements once for each item in collection. Having a compile and link phase +improves performance since the cloned template only needs to be compiled once, and then linked +once for each clone instance. + + +# Directive + +A directive is a behavior which should be triggered when specific HTML constructs are encountered in +the compilation process. The directives can be placed in element names, attributes, class names, as +well as comments. Here are some equivalent examples of invoking the {@link +api/ng.directive:ngBind `ng-bind`} directive. + +
+  
+  
+  
+  
+
+ +A directive is just a function which executes when the compiler encounters it in the DOM. See {@link +api/ng.$compileProvider#directive directive API} for in-depth documentation on how +to write directives. + +Here is a directive which makes any element draggable. Notice the `draggable` attribute on the +`` element. + + + + angular.module('drag', []). + directive('draggable', function($document) { + var startX=0, startY=0, x = 0, y = 0; + return function(scope, element, attr) { + element.css({ + position: 'relative', + border: '1px solid red', + backgroundColor: 'lightgrey', + cursor: 'pointer' + }); + element.bind('mousedown', function(event) { + startX = event.screenX - x; + startY = event.screenY - y; + $document.bind('mousemove', mousemove); + $document.bind('mouseup', mouseup); + }); + + function mousemove(event) { + y = event.screenY - startY; + x = event.screenX - startX; + element.css({ + top: y + 'px', + left: x + 'px' + }); + } + + function mouseup() { + $document.unbind('mousemove', mousemove); + $document.unbind('mouseup', mouseup); + } + } + }); + + + Drag ME + + + + +The presence of the `draggable` attribute on any element gives the element new behavior. The beauty of +this approach is that we have taught the browser a new trick. We have extended the vocabulary of +what the browser understands in a way which is natural to anyone who is familiar with HTML +principles. + + +# Understanding View + +There are many templating systems out there. Most of them consume a static string template and +combine it with data, resulting in a new string. The resulting text is then `innerHTML`ed into +an element. + + + +This means that any changes to the data need to be re-merged with the template and then +`innerHTML`ed into the DOM. Some of the issues with this approach are: reading user input and merging it with data, +clobbering user input by overwriting it, managing the whole update process, and lack of behavior +expressiveness. + +Angular is different. The Angular compiler consumes the DOM with directives, not string templates. +The result is a linking function, which when combined with a scope model results in a live view. The +view and scope model bindings are transparent. No action from the developer is needed to update +the view. And because no `innerHTML` is used there are no issues of clobbering user input. +Furthermore, Angular directives can contain not just text bindings, but behavioral constructs as +well. + + + +The Angular approach produces a stable DOM. This means that the DOM element instance bound to a model +item instance does not change for the lifetime of the binding. This means that the code can get +hold of the elements and register event handlers and know that the reference will not be destroyed +by template data merge. diff --git a/docs/content-ko-back/guide/concepts.ngdoc b/docs/content-ko-back/guide/concepts.ngdoc new file mode 100644 index 000000000000..d3e4e1bea6b9 --- /dev/null +++ b/docs/content-ko-back/guide/concepts.ngdoc @@ -0,0 +1,467 @@ +@ngdoc overview +@name Conceptual Overview +@description + +# Overview + +This document gives a quick overview of the main angular components and how they work together. +These are: + + * {@link concepts#startup startup} - bring up hello world + * {@link concepts#runtime runtime} - overview of angular runtime + * {@link concepts#scope scope} - the glue between the view and the controller + * {@link concepts#controller controller} - application behavior + * {@link concepts#model model} - your application data + * {@link concepts#view view} - what the user sees + * {@link concepts#directives directives} - extend HTML vocabulary + * {@link concepts#filters filters} - format the data in user locale + * {@link concepts#injector injector} - assembles your application + * {@link concepts#module module} - configures the injector + * {@link concepts#angular_namespace `$`} - angular namespace + + +# Startup + +This is how we get the ball rolling (refer to the diagram and example below): + + + + 1. The browser loads the HTML and parses it into a DOM + 2. The browser loads `angular.js` script + 3. Angular waits for `DOMContentLoaded` event + 4. Angular looks for {@link api/ng.directive:ngApp ng-app} + {@link guide/directive directive}, which designates the application boundary + 5. The {@link guide/module Module} specified in {@link + api/ng.directive:ngApp ng-app} (if any) is used to configure + the {@link api/AUTO.$injector $injector} + 6. The {@link api/AUTO.$injector $injector} is used to create the {@link + api/ng.$compile $compile} service as well as {@link + api/ng.$rootScope $rootScope} + 7. The {@link api/ng.$compile $compile} service is used to compile the DOM and link + it with {@link api/ng.$rootScope $rootScope} + 8. The {@link api/ng.directive:ngInit ng-init} {@link + guide/directive directive} assigns `World` to the `name` property on the {@link guide/scope + scope} + 9. The `{{name}}` {@link api/ng.$interpolate interpolates} the expression to + `Hello World!` + +
+
+ + +

Hello {{name}}!

+
+
+ + + +# Runtime + + + +The diagram and the example below describe how Angular interacts with the browser's event loop. + + 1. The browser's event-loop waits for an event to arrive. An event is a user interactions, timer event, + or network event (response from a server). + 2. The event's callback gets executed. This enters the JavaScript context. The callback can + modify the DOM structure. + 3. Once the callback executes, the browser leaves the JavaScript context and + re-renders the view based on DOM changes. + +Angular modifies the normal JavaScript flow by providing its own event processing loop. This +splits the JavaScript into classical and Angular execution context. Only operations which are +applied in Angular execution context will benefit from Angular data-binding, exception handling, +property watching, etc... You can also use $apply() to enter Angular execution context from JavaScript. Keep in +mind that in most places (controllers, services) $apply has already been called for you by the +directive which is handling the event. An explicit call to $apply is needed only when +implementing custom event callbacks, or when working with a third-party library callbacks. + + 1. Enter Angular execution context by calling {@link guide/scope scope}`.`{@link + api/ng.$rootScope.Scope#$apply $apply}`(stimulusFn)`. Where `stimulusFn` is + the work you wish to do in Angular execution context. + 2. Angular executes the `stimulusFn()`, which typically modifies application state. + 3. Angular enters the {@link api/ng.$rootScope.Scope#$digest $digest} loop. The + loop is made up of two smaller loops which process {@link + api/ng.$rootScope.Scope#$evalAsync $evalAsync} queue and the {@link + api/ng.$rootScope.Scope#$watch $watch} list. The {@link + api/ng.$rootScope.Scope#$digest $digest} loop keeps iterating until the model + stabilizes, which means that the {@link api/ng.$rootScope.Scope#$evalAsync + $evalAsync} queue is empty and the {@link api/ng.$rootScope.Scope#$watch + $watch} list does not detect any changes. + 4. The {@link api/ng.$rootScope.Scope#$evalAsync $evalAsync} queue is used to + schedule work which needs to occur outside of current stack frame, but before the browser's + view render. This is usually done with `setTimeout(0)`, but the `setTimeout(0)` approach + suffers from slowness and may cause view flickering since the browser renders the view after + each event. + 5. The {@link api/ng.$rootScope.Scope#$watch $watch} list is a set of expressions + which may have changed since last iteration. If a change is detected then the `$watch` + function is called which typically updates the DOM with the new value. + 6. Once the Angular {@link api/ng.$rootScope.Scope#$digest $digest} loop finishes + the execution leaves the Angular and JavaScript context. This is followed by the browser + re-rendering the DOM to reflect any changes. + + +Here is the explanation of how the `Hello wold` example achieves the data-binding effect when the +user enters text into the text field. + + 1. During the compilation phase: + 1. the {@link api/ng.directive:ngModel ng-model} and {@link + api/ng.directive:input input} {@link guide/directive + directive} set up a `keydown` listener on the `` control. + 2. the {@link api/ng.$interpolate {{name}} } interpolation + sets up a {@link api/ng.$rootScope.Scope#$watch $watch} to be notified of + `name` changes. + 2. During the runtime phase: + 1. Pressing an '`X`' key causes the browser to emit a `keydown` event on the input control. + 2. The {@link api/ng.directive:input input} directive + captures the change to the input's value and calls {@link + api/ng.$rootScope.Scope#$apply $apply}`("name = 'X';")` to update the + application model inside the Angular execution context. + 3. Angular applies the `name = 'X';` to the model. + 4. The {@link api/ng.$rootScope.Scope#$digest $digest} loop begins + 5. The {@link api/ng.$rootScope.Scope#$watch $watch} list detects a change + on the `name` property and notifies the {@link api/ng.$interpolate + {{name}} } interpolation, which in turn updates the DOM. + 6. Angular exits the execution context, which in turn exits the `keydown` event and with it + the JavaScript execution context. + 7. The browser re-renders the view with update text. + +
+
+ + + +

Hello {{name}}!

+
+
+ + +#Scope + +The {@link guide/scope scope} is responsible for detecting changes to the model section and +provides the execution context for expressions. The scopes are nested in a hierarchical structure +which closely follow the DOM structure. (See individual directive documentation to see which +directives cause a creation of new scopes.) + +The following example demonstrates how `name` {@link guide/expression expression} will evaluate +into different value depending on which scope it is evaluated in. The example is followed by +a diagram depicting the scope boundaries. + +
+
+
+ + +
+ Hello {{name}}! +
+
+
    +
  1. {{name}}
  2. +
+
+
+ + function GreetCtrl($scope) { + $scope.name = 'World'; + } + + function ListCtrl($scope) { + $scope.names = ['Igor', 'Misko', 'Vojta']; + } + + + .show-scope .doc-example-live.ng-scope, + .show-scope .doc-example-live .ng-scope { + border: 1px solid red; + margin: 3px; + } + +
+
+ + + + + +# Controller + + + +A controller is the code behind the view. Its job is to construct the model and publish it to the +view along with callback methods. The view is a projection of the scope onto the template (the +HTML). The scope is the glue which marshals the model to the view and forwards the events to the +controller. + +The separation of the controller and the view is important because: + + * The controller is written in JavaScript. JavaScript is imperative. Imperative is a good fit + for specifying application behavior. The controller should not contain any rendering + information (DOM references or HTML fragments). + * The view template is written in HTML. HTML is declarative. Declarative is a good fit for + specifying UI. The View should not contain any behavior. + * Since the controller is unaware of the view, there could be many views for the same + controller. This is important for re-skinning, device specific views (i.e. mobile vs desktop), + and testability. + +
+
+ + +
+ Hello {{name}}! + +
+
+ + function MyCtrl($scope) { + $scope.action = function() { + $scope.name = 'OK'; + } + + $scope.name = 'World'; + } + +
+ + + +# Model + + + +The model is the data which is used merged with the template to produce the view. To be able to +render the model into the view, the model has to be able to be referenced from the scope. Unlike many +other frameworks Angular makes no restrictions or requirements on the model. There are no classes +to inherit from or special accessor methods for accessing or changing the model. The model can be +primitive, object hash, or a full object Type. In short the model is a plain JavaScript object. + + +
+
+ + + +# View + + + +The view is what the user sees. The view begins its life as a template, is merged with the +model and finally rendered into the browser DOM. Angular takes a very different approach to +rendering the view compared to most other templating systems. + + * **Others** - Most templating systems begin as an HTML string with special templating markup. + Often the template markup breaks the HTML syntax which means that the template can not be + edited by an HTML editor. The template string is then parsed by the template engine, and + merged with the data. The result of the merge is an HTML string. The HTML string is then + written to the browser using the `.innerHTML`, which causes the browser to render the HTML. + When the model changes the whole process needs to be repeated. The granularity of the template + is the granularity of the DOM updates. The key here is that the templating system manipulates + strings. + * **Angular** - Angular is different, since its templating system works on DOM objects not on + strings. The template is still written in an HTML string, but it is HTML (not HTML with + template sprinkled in.) The browser parses the HTML into the DOM, and the DOM becomes the input to + the template engine known as the {@link api/ng.$compile compiler}. The compiler + looks for {@link guide/directive directives} which in turn set up {@link + api/ng.$rootScope.Scope#$watch watches} on the model. The result is a + continuously updating view which does not need template model re-merging. Your model becomes + the single source-of-truth for your view. + +
+
+ + + +
+
+
+
list={{list}}

+
    +
  1. + {{item}} +
  2. +
+
+
+
+ + + +# Directives + +A directive is a behavior or DOM transformation which is triggered by the presence of a custom attribute, +element name, or a class name. A directive allows you to extend the HTML vocabulary in a +declarative fashion. Following is an example which enables data-binding for the `contenteditable` +in HTML. + + + + angular.module('directive', []).directive('contenteditable', function() { + return { + require: 'ngModel', + link: function(scope, elm, attrs, ctrl) { + // view -> model + elm.bind('blur', function() { + scope.$apply(function() { + ctrl.$setViewValue(elm.html()); + }); + }); + + // model -> view + ctrl.$render = function(value) { + elm.html(value); + }; + + // load init value from DOM + ctrl.$setViewValue(elm.html()); + } + }; + }); + + +
Edit Me
+
model = {{content}}
+
+ + div[contentEditable] { + cursor: pointer; + background-color: #D0D0D0; + margin-bottom: 1em; + padding: 1em; + } + +
+ + +# Filters + +{@link api/ng.$filter Filters} perform data transformation. Typically +they are used in conjunction with the locale to format the data in locale specific output. +They follow the spirit of UNIX filters and use similar syntax `|` (pipe). + + + +
+ Number formatting: {{ 1234567890 | number }}
+ array filtering + {{ list | filter:predicate | json }} +
+
+
+ + + + +# Modules and the Injector + + + +The {@link api/AUTO.$injector injector} is a service locator. There is a single +{@link api/AUTO.$injector injector} per Angular {@link +api/ng.directive:ngApp application}. The {@link +api/AUTO.$injector injector} provides a way to look up an object instance by its +name. The injector keeps an internal cache of all objects so that repeated calls to get the same +object name result in the same instance. If the object does not exist, then the {@link +api/AUTO.$injector injector} asks the instance factory to create a new instance. + +A {@link api/angular.Module module} is a way to configure the injector's instance factory, known +as a {@link api/AUTO.$provide provider}. + +
+
+  // Create a module
+  var myModule = angular.module('myModule', [])
+
+  // Configure the injector
+  myModule.factory('serviceA', function() {
+    return {
+      // instead of {}, put your object creation here
+    };
+  });
+
+  // create an injector and configure it from 'myModule'
+  var $injector = angular.injector(['myModule']);
+
+  // retrieve an object from the injector by name
+  var serviceA = $injector.get('serviceA');
+
+  // always true because of instance cache
+  $injector.get('serviceA') === $injector.get('serviceA');
+
+ + +But the real magic of the {@link api/AUTO.$injector injector} is that it can be +used to {@link api/AUTO.$injector#invoke call} methods and {@link +api/AUTO.$injector#instantiate instantiate} types. This subtle feature is what +allows the methods and types to ask for their dependencies instead of having to look for them. + +
+  // You write functions such as this one.
+  function doSomething(serviceA, serviceB) {
+    // do something here.
+  }
+
+  // Angular provides the injector for your application
+  var $injector = ...;
+
+  ///////////////////////////////////////////////
+  // the old-school way of getting dependencies.
+  var serviceA = $injector.get('serviceA');
+  var serviceB = $injector.get('serviceB');
+
+  // now call the function
+  doSomething(serviceA, serviceB);
+
+  ///////////////////////////////////////////////
+  // the cool way of getting dependencies.
+  // the $injector will supply the arguments to the function automatically
+  $injector.invoke(doSomething); // This is how the framework calls your functions
+
+ +Notice that the only thing you needed to write was the function, and list the dependencies in the +function arguments. When angular calls the function, it will use the {@link +api/AUTO.$injector#invoke call} which will automatically fill the function +arguments. + +Examine the `ClockCtrl` bellow, and notice how it lists the dependencies in the constructor. When the +{@link api/ng.directive:ngController ng-controller} instantiates +the controller it automatically provides the dependencies. There is no need to create +dependencies, look for dependencies, or even get a reference to the injector. + + + +
+ Current time is: {{ time.now }} +
+
+ + angular.module('timeExampleModule', []). + // Declare new object called time, + // which will be available for injection + factory('time', function($timeout) { + var time = {}; + + (function tick() { + time.now = new Date().toString(); + $timeout(tick, 1000); + })(); + return time; + }); + + // Notice that you can simply ask for time + // and it will be provided. No need to look for it. + function ClockCtrl($scope, time) { + $scope.time = time; + } + +
+ + + +# Angular Namespace + +To prevent accidental name collision, Angular prefixes names of objects which could potentially +collide with `$`. Please do not use the `$` prefix in your code as it may accidentally collide +with Angular code. diff --git a/docs/content-ko-back/guide/dev_guide.e2e-testing.ngdoc b/docs/content-ko-back/guide/dev_guide.e2e-testing.ngdoc new file mode 100644 index 000000000000..99f9322888ca --- /dev/null +++ b/docs/content-ko-back/guide/dev_guide.e2e-testing.ngdoc @@ -0,0 +1,178 @@ +@workInProgress +@ngdoc overview +@name Developer Guide: E2E Testing +@description + +As applications grow in size and complexity, it becomes unrealistic to rely on manual testing to +verify the correctness of new features, catch bugs and notice regressions. + +To solve this problem, we have built an Angular Scenario Runner which simulates user interactions +that will help you verify the health of your Angular application. + +# Overview +You will write scenario tests in JavaScript, which describe how your application should behave, +given a certain interaction in a specific state. A scenario is comprised of one or more `it` blocks +(you can think of these as the requirements of your application), which in turn are made of +**commands** and **expectations**. Commands tell the Runner to do something with the application +(such as navigate to a page or click on a button), and expectations tell the Runner to assert +something about the state (such as the value of a field or the current URL). If any expectation +fails, the runner marks the `it` as "failed" and continues on to the next one. Scenarios may also +have **beforeEach** and **afterEach** blocks, which will be run before (or after) each `it` block, +regardless of whether they pass or fail. + + + +In addition to the above elements, scenarios may also contain helper functions to avoid duplicating +code in the `it` blocks. + +Here is an example of a simple scenario: +
+describe('Buzz Client', function() {
+it('should filter results', function() {
+  input('user').enter('jacksparrow');
+  element(':button').click();
+  expect(repeater('ul li').count()).toEqual(10);
+  input('filterText').enter('Bees');
+  expect(repeater('ul li').count()).toEqual(1);
+});
+});
+
+This scenario describes the requirements of a Buzz Client, specifically, that it should be able to +filter the stream of the user. It starts by entering a value in the 'user' input field, clicking +the only button on the page, and then it verifies that there are 10 items listed. It then enters +'Bees' in the 'filterText' input field and verifies that the list is reduced to a single item. + +The API section below lists the available commands and expectations for the Runner. + +# API +Source: {@link https://github.com/angular/angular.js/blob/master/src/ngScenario/dsl.js} + +## pause() +Pauses the execution of the tests until you call `resume()` in the console (or click the resume +link in the Runner UI). + +## sleep(seconds) +Pauses the execution of the tests for the specified number of `seconds`. + +## browser().navigateTo(url) +Loads the `url` into the test frame. + +## browser().navigateTo(url, fn) +Loads the URL returned by `fn` into the testing frame. The given `url` is only used for the test +output. Use this when the destination URL is dynamic (that is, the destination is unknown when you +write the test). + +## browser().reload() +Refreshes the currently loaded page in the test frame. + +## browser().window().href() +Returns the window.location.href of the currently loaded page in the test frame. + +## browser().window().path() +Returns the window.location.pathname of the currently loaded page in the test frame. + +## browser().window().search() +Returns the window.location.search of the currently loaded page in the test frame. + +## browser().window().hash() +Returns the window.location.hash (without `#`) of the currently loaded page in the test frame. + +## browser().location().url() +Returns the {@link api/ng.$location $location.url()} of the currently loaded page in +the test frame. + +## browser().location().path() +Returns the {@link api/ng.$location $location.path()} of the currently loaded page in +the test frame. + +## browser().location().search() +Returns the {@link api/ng.$location $location.search()} of the currently loaded page +in the test frame. + +## browser().location().hash() +Returns the {@link api/ng.$location $location.hash()} of the currently loaded page in +the test frame. + +## expect(future).{matcher} +Asserts the value of the given `future` satisfies the `matcher`. All API statements return a +`future` object, which get a `value` assigned after they are executed. Matchers are defined using +`angular.scenario.matcher`, and they use the value of futures to run the expectation. For example: +`expect(browser().location().href()).toEqual('http://www.google.com')` + +## expect(future).not().{matcher} +Asserts the value of the given `future` satisfies the negation of the `matcher`. + +## using(selector, label) +Scopes the next DSL element selection. + +## binding(name) +Returns the value of the first binding matching the given `name`. + +## input(name).enter(value) +Enters the given `value` in the text field with the given `name`. + +## input(name).check() +Checks/unchecks the checkbox with the given `name`. + +## input(name).select(value) +Selects the given `value` in the radio button with the given `name`. + +## input(name).val() +Returns the current value of an input field with the given `name`. + +## repeater(selector, label).count() +Returns the number of rows in the repeater matching the given jQuery `selector`. The `label` is +used for test output. + +## repeater(selector, label).row(index) +Returns an array with the bindings in the row at the given `index` in the repeater matching the +given jQuery `selector`. The `label` is used for test output. + +## repeater(selector, label).column(binding) +Returns an array with the values in the column with the given `binding` in the repeater matching +the given jQuery `selector`. The `label` is used for test output. + +## select(name).option(value) +Picks the option with the given `value` on the select with the given `name`. + +## select(name).option(value1, value2...) +Picks the options with the given `values` on the multi select with the given `name`. + +## element(selector, label).count() +Returns the number of elements that match the given jQuery `selector`. The `label` is used for test +output. + +## element(selector, label).click() +Clicks on the element matching the given jQuery `selector`. The `label` is used for test output. + +## element(selector, label).query(fn) +Executes the function `fn(selectedElements, done)`, where selectedElements are the elements that +match the given jQuery `selector` and `done` is a function that is called at the end of the `fn` +function. The `label` is used for test output. + +## element(selector, label).{method}() +Returns the result of calling `method` on the element matching the given jQuery `selector`, where +`method` can be any of the following jQuery methods: `val`, `text`, `html`, `height`, +`innerHeight`, `outerHeight`, `width`, `innerWidth`, `outerWidth`, `position`, `scrollLeft`, +`scrollTop`, `offset`. The `label` is used for test output. + +## element(selector, label).{method}(value) +Executes the `method` passing in `value` on the element matching the given jQuery `selector`, where +`method` can be any of the following jQuery methods: `val`, `text`, `html`, `height`, +`innerHeight`, `outerHeight`, `width`, `innerWidth`, `outerWidth`, `position`, `scrollLeft`, +`scrollTop`, `offset`. The `label` is used for test output. + +## element(selector, label).{method}(key) +Returns the result of calling `method` passing in `key` on the element matching the given jQuery +`selector`, where `method` can be any of the following jQuery methods: `attr`, `prop`, `css`. The +`label` is used for test output. + +## element(selector, label).{method}(key, value) +Executes the `method` passing in `key` and `value` on the element matching the given jQuery +`selector`, where `method` can be any of the following jQuery methods: `attr`, `prop`, `css`. The +`label` is used for test output. + +JavaScript is a dynamically typed language which comes with great power of expression, but it also +come with almost no-help from the compiler. For this reason we feel very strongly that any code +written in JavaScript needs to come with a strong set of tests. We have built many features into +angular which makes testing your angular applications easy. So there is no excuse for not testing. diff --git a/docs/content-ko-back/guide/dev_guide.mvc.ngdoc b/docs/content-ko-back/guide/dev_guide.mvc.ngdoc new file mode 100644 index 000000000000..4522dc7bdce6 --- /dev/null +++ b/docs/content-ko-back/guide/dev_guide.mvc.ngdoc @@ -0,0 +1,22 @@ +@ngdoc overview +@name Developer Guide: Angular의 MVC +@description + +모델-뷰-컨트롤러(MVC) 는 처음 등장한 이래 수년동안 여러가지 다른 의미로 받아들여졌지만, Angular 는 +클라이언트 측 웹 어플리케이션을 구축하는 방법에 전통적인 {@link http://en.wikipedia.org/wiki/Model–view–controller MVC} 소프트웨어 +설계 패턴 뒤에 숨어 있는 기본 원칙을 포함한다. + +MVC 패턴을 요약하면: + +* 어플리케이션을 서로 다른 프리젠테이션, 데이터, 그리고 논리 컴포넌트로 분리한다. +* 컴포넌트간에 느슨한 결합을 권장한다. + +MVC는 {@link dev_guide.services 서비스} 및 {@link di 의존성 주입} 과 함께 Angular 어플리케이션을 +더 구조화하고, 유지관리가 쉽게 하고, 그리고 더 검증 가능하도록 해준다. + +다음의 토픽들은 Angular가 웹 어플리케이션을 개발하는 방식에 MVC 패턴을 통합하는 방법을 설명한다. + +* {@link dev_guide.mvc.understanding_model 모델 컴포넌트 이해하기} +* {@link dev_guide.mvc.understanding_controller 컨트롤러 컴포넌트 이해하기} +* {@link dev_guide.mvc.understanding_view 뷰 컴포넌트 이해하기} + diff --git a/docs/content-ko-back/guide/dev_guide.mvc.understanding_controller.ngdoc b/docs/content-ko-back/guide/dev_guide.mvc.understanding_controller.ngdoc new file mode 100644 index 000000000000..b77170a2bded --- /dev/null +++ b/docs/content-ko-back/guide/dev_guide.mvc.understanding_controller.ngdoc @@ -0,0 +1,280 @@ +@ngdoc overview +@name Developer Guide: Angular의 MVC: 컨트롤러 컴포넌트 이해하기 +@description + +Angular에서 컨트롤러는 루프 스코프를 제외한 Angular 스코프의 인스턴스를 확장하기 위해 사용되는 +자바스크립트 함수(타입/클래스)이다. 직접 또는 Angular가 {@link api/ng.$rootScope.Scope#$new scope.$new} API를 통해 +새로운 하위 스코프 객체를 생성할 때 컨트롤러에 메소드 인자로 전달하는 옵션이 하나 있다. +이것은 Angular에게 컨트롤러를 새로운 스코프에 연결하고 그것의 행위(behavior)를 확장하라고 알려준다. + +다음과 같은 경우에 컨트롤러를 사용한다: + +- 스코프 객체의 초기 상태를 설정하기 위해 +- 스코프 객체에 행위를 추가하기 위해 + +# 스코프 객체의 초기 상태 설정 + +보통 어플리케이션을 만들때는 Angular 스코프에 대한 초기 상태를 설정해야 한다. + +Angular는 새로운 초기 스코프 상태가 준비된 새로운 Angular 스코프 객체에 컨트롤러 생성자 함수를 +apply(자바스크립트의 `Function#apply`라는 의미) 한다. 이것은 Angular가 (`new` 연산자로 컨트롤러 생성자를 호출함으로써) +컨트롤러 타입의 인스턴스를 생성하지는 않는다는 의미이다. 생성자는 항상 기존의 스코프 객체에서 apply 된다. + +모델 프로퍼티를 생성함으로써 스코프의 초기 상태를 설정한다. 예를 들면: + +
+function GreetingCtrl($scope) {
+ $scope.greeting = 'Hola!';
+}
+
+ +`GreetingCtrl` 컨트롤러는 템플릿에서 참조할 수 있는 `greeting` 모델을 생성한다. + +**중요**: 문서상의 많은 예제들을 보면 전역 스코프 상에 함수를 생성하고 있다. 이것은 데모를 보여주기 위함일 뿐이며 +실제 어플리케이션에서는 다음의 예제처럼 어플리케이션에 대한 Angular 모듈의 `.controller` 메소드를 +사용해야 한다. + +
+var myApp = angular.module('myApp',[]);
+
+myApp.controller('GreetingCtrl', ['$scope', function(scope) {
+  scope.greeting = 'Hola!';
+}]);
+
+ +또한 Angular가 제공하는 `$scope` 서비스가 컨트롤러에 종속적임을 명시적으로 지정하기 위해 +배열 구문을 사용하는 것을 주목해라. + +# 스코프 객체에 행위 추가하기 + +Angular 스코프 객체의 행위는 템플릿/뷰에서 사용하도록 스코프의 메소드 프로퍼티 형태로 되어 있다. +이러한 행위는 어플리케이션의 모델과 상호작용하여 그것을 수정한다. + +이 가이드의 {@link dev_guide.mvc.understanding_model 모델} 섹션에서 설명하고 있는 바와 같이 +그 스코프에 할당된 모든 객체(또는 원시데이터)는 모델 프로퍼티가 된다. 그 스코프에 할당된 +모든 함수는 템플릿/뷰에서 사용 가능하고 Angular 표현식과 `ng` 이벤트 핸들러 지시지를 통해 +호출할 수 있다. (예. {@link api/ng.directive:ngClick ngClick}) + +# 컨트롤러 올바르게 사용하기 + +일반적으로 컨트롤러는 너무 많은 작업을 수행해서는 안된다. 하나의 뷰에 대해 필요한 비지니스 로직만을 +포함해야 한다. + +컨트롤러를 가볍게 유지하는 가장 일반적인 방법은 컨트롤러에 속하지 않은 작업을 서비스 안으로 캡슐화하고 +의존성 주입을 통해 컨트롤러에서 이 서비스를 사용하는 것이다. 이것은 이 가이드의 {@link di 의존성 주입} +{@link dev_guide.services 서비스} 섹션에서 설명하고 있다. + +컨트롤러를 사용하지 말아야 할 경우: + +- 모든 종류의 DOM 조작 — 컨트롤러는 비지니스 로직만을 포함해야 한다. DOM 조작—어플리케이션의 프리젠테이션 로직—은 +알다시피 테스트하기가 어렵다. 컨트롤러 안에 프리젠테이션 로직을 넣는 것은 비지니스 로직의 테스트 용이성에 +크게 영향을 끼친다. Angular는 자동으로 DOM을 조작하기 위해 {@link dev_guide.templates.databinding 데이터바인딩}을 +제공한다. 만약 수동으로 DOM 조작을 해야만 한다면 {@link guide/directive 지시자}에 프리젠테이션 로직을 캡슐화해라. +- 입력 서식 — 대신에 {@link forms Angular 폼 컨트롤}을 사용해라. +- 출력 필터링 — 대신에 {@link dev_guide.templates.filters Angular 필터}를 사용해라. +- 컨트롤러 간에 공유하고 있는 상태 코드를 운영하는 것 — 대신에 {@link dev_guide.services Angular 서비스}를 사용해라. +- 다른 컴포넌트를 인스턴스화하거나 생명주기를 관리하는 것 (예를 들어 서비스 인스턴스를 생성하는 것) + + +# 컨트롤러를 Angular 스코프 객체와 연결하기 + +컨트롤러를 스코프 객체에 {@link api/ng.$rootScope.Scope#$new scope.$new} api를 통해 명시적으로 연결할 수도 있고 +암시적으로 {@link api/ng.directive:ngController ngController 지시자}나 {@link api/ng.$route $route 서비스}를 통해 +연결할 수도 있다. + + +## 컨트롤러 생성자와 메소드 예제 + +Angular에서 컨트롤러 컴포넌트가 어떻게 작동을 하는지 설명하기 위해 다음의 컴포넌트를 사용하여 +작은 앱을 만들어 보자. + +- 두개의 버튼과 간단한 메시지가 있는 {@link dev_guide.templates 템플릿} +- `spice`라는 이름의 문자열을 포함하고 있는 모델 +- `spice`의 값을 설정하는 두개의 함수 컨트롤러 + +`spice` 모델에 바인딩되는 템플릿 메시지의 기본값을 문자열 "very"로 설정한다. 버튼을 클릭하는 것에 따라 +`spice` 모델은 `chili` 또는 `jalapeño`로 설정되고 메시지는 데이터 바인딩에 의해 자동으로 업데이트된다. + + +## 흥미로운 컨트롤러 예제 + +
+
+ 
+ 
+ 

The food is {{spice}} spicy!

+ + +function SpicyCtrl($scope) { + $scope.spice = 'very'; + $scope.chiliSpicy = function() { + $scope.spice = 'chili'; + } + $scope.jalapenoSpicy = function() { + $scope.spice = 'jalapeño'; + } +} + + +
+ +위 예제에서 주목할 점은 다음과 같다: + +- `ngController` 지시자는 해당 템플릿에 대한 스코프를 (암시적으로) 생성하고 그 스코프는 +`SpicyCtrl` 컨트롤러에 의해 확장(관리)된다. +- `SpicyCtrl`은 평범한 자바스크립트 함수일뿐이다. (선택적인) 명명 규칙에 따라 이름은 대문자로 시작하고 +"Ctrl" 또는 "Controller"로 끝난다. +- `$scope`에 프로퍼티를 할당하여 모델을 생성하거나 업데이트한다. +- 컨트롤러 메소드는 스코프에 직접 할당함으로써 생성할 수 있다.(`chiliSpicy` 메소드) +- 두개의 컨트롤러 메소드 모두 템플릿에서 사용 가능하다.(`body` 요소와 그 하위 요소에서) +- 주의: Angular의 이전 버전(1.0 RC 이전)은 $scope 메소드 대신에 `this`를 사용할 수 있다. 하지만 더이상은 +그렇지 않다. 스코프에 정의된 메소드 안에서는 `this`와 $scope를 바꾸어 사용 가능하다(Angular가 $scope를 +`this`로 설정한다.) 하지만 컨트롤러 생성자 안에서는 그렇지 않다. +- 주의: Angular의 이전 버전(1.0 RC 이전)에서는 자동으로 스코프에 프로토타입 메소드를 추가했다. +하지만 더이상은 그렇지 않다; 필요한 모든 메소드는 스코프에 수동으로 추가해야만 한다. + + +이전 예제를 수정한 다음의 예제에서 보듯이 컨트롤러 메소드는 인자를 받을수도 있다. + +## 컨트롤러 메소드의 인자 예제 + +
+
+ 
+ 
+ 
+ 

The food is {{spice}} spicy!

+ + +function SpicyCtrl($scope) { + $scope.spice = 'very'; + $scope.spicy = function(spice) { + $scope.spice = spice; + } +} +
+ +이제 `SpicyCtrl` 컨트롤러가 `spice`라는 하나의 인자를 받는 `spicy` 메소드 하나만을 정의하고 있다는 것을 +주목하자. 템플릿은 이 컨트롤러 메소드를 참조하며 첫번째 버튼에 바인딩되어 있는 문자열 상수 +`'chili'`를 전달하고 두번째 버튼에 (입력 박스에 바인딩된) 모델 프로퍼티인 `spice` 를 전달한다. + + +## 컨트롤러 상속 예제 + +Angular에서 컨트롤러의 상속은 {@link api/ng.$rootScope.Scope 스코프}를 기반으로 한다. 예제를 보자: + +
+
+ 

Good {{timeOfDay}}, {{name}}!

+
+

Good {{timeOfDay}}, {{name}}!

+

Good {{timeOfDay}}, {{name}}!

+
+ + +function MainCtrl($scope) { + $scope.timeOfDay = 'morning'; + $scope.name = 'Nikki'; +} + +function ChildCtrl($scope) { + $scope.name = 'Mattie'; +} + +function BabyCtrl($scope) { + $scope.timeOfDay = 'evening'; + $scope.name = 'Gingerbreak Baby'; +} +
+ +템플릿에 세개의 `ngController` 지시자를 중첩시킨 방법을 주목하자. 이러한 템플릿 구조는 아래와 같은 +4개의 스코프를 생성할 것이다. + +- 루트 스코프 +- `timeOfDay` 와 `name` 모델을 포함하고 있는 `MainCtrl` 스코프 +- 이전 스코프의 `name` 모델을 덮어쓰고 `timeOfDay` 모델을 상속하고 있는 `ChildCtrl` 스코프 +- `MainCtrl`에서 정의한 `timeOfDay` 모델과 `ChildCtrl`에서 정의한 `name` 모델 둘 다 덮어쓴 +`BabyCtrl` 스코프 + +컨트롤러간의 상속은 모델과 같은 방식으로 작동한다. 그래서 이전 예제의 모든 모델을 문자열 값을 반환하는 +컨트롤러 메소드로 교체할 수 있다. + +중요: 두 컨트롤러 사이의 표준 프로토타입 상속은 우리가 예상하는대로 되지 않는다. 앞에서 언급한 바와 같이 +컨트롤러는 Angular에 의해 직접 인스턴스화되지 않고 스코프 객체에 apply 되기 때문이다. + + +## 컨트롤러 테스트하기 + +컨트롤러를 테스트하는 많은 방법이 있지만 가장 좋은 방법 중 하나는 아래에서 보는 것과 같이 +`$rootScope`와 `$controller`의 주입을 포함시키는 것이다. + +컨트롤러 함수: +
+function myController($scope) {
+   $scope.spices = [{"name":"pasilla", "spiciness":"mild"},
+                  {"name":"jalapeno", "spiceiness":"hot hot hot!"},
+                  {"name":"habanero", "spiceness":"LAVA HOT!!"}];
+
+   $scope.spice = "habanero";
+}
+
+ +컨트롤러 테스트: +
+describe('myController function', function() {
+
+  describe('myController', function() {
+    var scope;
+
+    beforeEach(inject(function($rootScope, $controller) {
+      scope = $rootScope.$new();
+      var ctrl = $controller(myController, {$scope: scope});
+    }));
+
+    it('should create "spices" model with 3 spices', function() {
+      expect(scope.spices.length).toBe(3);
+    });
+
+    it('should set the default value of spice', function() {
+      expect(scope.spice).toBe('habanero');
+    });
+  });
+});
+
+ + +만약 중첩된 컨트롤러를 테스트해야만 한다면 DOM에 존재하는 테스트에서 같은 스코프 계층 구조를 +생성해야 한다. + +
+describe('state', function() {
+    var mainScope, childScope, babyScope;
+
+    beforeEach(inject(function($rootScope, $controller) {
+        mainScope = $rootScope.$new();
+        var mainCtrl = $controller(MainCtrl, {$scope: mainScope});
+        childScope = mainScope.$new();
+        var childCtrl = $controller(ChildCtrl, {$scope: childScope});
+        babyScope = childCtrl.$new();
+        var babyCtrl = $controller(BabyCtrl, {$scope: babyScope});
+    }));
+
+    it('should have over and selected', function() {
+        expect(mainScope.timeOfDay).toBe('morning');
+        expect(mainScope.name).toBe('Nikki');
+        expect(childScope.timeOfDay).toBe('morning');
+        expect(childScope.name).toBe('Mattie');
+        expect(babyScope.timeOfDay).toBe('evening');
+        expect(babyScope.name).toBe('Gingerbreak Baby');
+    });
+});
+
+ + +## 관련 토픽 + +* {@link dev_guide.mvc Angular의 MVC} +* {@link dev_guide.mvc.understanding_model 모델 컴포넌트 이해하기} +* {@link dev_guide.mvc.understanding_view 뷰 컴포넌트 이해하기} + + diff --git a/docs/content-ko-back/guide/dev_guide.mvc.understanding_model.ngdoc b/docs/content-ko-back/guide/dev_guide.mvc.understanding_model.ngdoc new file mode 100644 index 000000000000..0d6b515f0385 --- /dev/null +++ b/docs/content-ko-back/guide/dev_guide.mvc.understanding_model.ngdoc @@ -0,0 +1,66 @@ +@ngdoc overview +@name Developer Guide: Angular의 MVC: 모델 컴포넌트 이해하기 +@description + +Angular 문서에서 논의된 문맥에 따르면 _모델_ 은 하나의 엔티티(예를 들어, phones라는 배열을 값으로 +가지는 "phones"라고 불리는 모델) 또는 어플리케이션에 대한 전체 데이터 모델(모든 엔티티)을 나타내는 +단일 객체를 참조할 수 있다. + +Angular에서 모델은 {@link scope 스코프} 객체의 프로퍼티로써 접근 가능한 모든 데이터를 말한다. +프로퍼티의 이름은 모델의 식별자이고 그 값은 (배열이나 원시데이터를 포함한) 어떤 자바스크립트 객체여도 된다. + +Angular에서 모델이 될 수 있는 자바스크립트 객체에 대한 유일한 요건은 그 객체가 해당 스코프 객체의 프로퍼티로 +Angular 스코프에 의해 참조되어야 한다는 것이다. 이 프로퍼티의 참조는 명시적 또는 암시적으로 생성할 수 있다. + +다음과 같은 방법으로 자바스크립트 객체를 참조하는 스코프 프로퍼티를 명시적으로 생성하여 모델을 만들 수 있다: + +* 자바스크립트 코드에서 스코프 객체에 프로퍼티를 직접 할당한다; 이것은 거의 대부분 컨트롤러에서 이루어진다: + + function MyCtrl($scope) { + // create property 'foo' on the MyCtrl's scope + // and assign it an initial value 'bar' + $scope.foo = 'bar'; + } + +* 템플릿에 할당 연산자로 {@link expression Angular 표현식} 을 사용한다: + + + +* 템플릿에 {@link api/ng.directive:ngInit ngInit 지시자} 를 사용한다. (개인/예제 앱에서는 상관 없지만, +실제 어플리케이션에서는 권장하지 않는다): + + + +Angular는 아래의 템플릿 구문을 처리할 때 (스코프 프로퍼티를 생성하고 적절한 값을 할당함으로써) +암시적으로 모델을 생성한다: + +* input, select, textarea 그리고 다른 폼 요소들: + + + + 위 코드는 현재 스코프에 "query"라는 모델을 생성하고 "fluffy cloud"라는 값을 설정한다. + +* {@link api/ng.directive:ngRepeat ngRepeater} 의 반복자 선언: + +

+ + 위 코드는 "phones"라는 배열의 각 항목별로 하위 스코프를 생성하고 이 각각의 스코프에 "phone" 객체(모델)를 +생성한 후 그 값을 배열의 "phone"의 값으로 설정한다. + +Angular에서는 다음과 같은 경우에 모델 생성에 실패한다: + +* 그 객체를 참조하는 프로퍼티를 포함하는 Angular 스코프가 없는 경우. + +* 그 객체를 참조하는 프로퍼티를 포함한 모든 Angular 스코프가 부실하여 가비지 컬렉션(garbage collection)의 +대상이 되는 경우. + +아래 그림은 간단한 템플릿으로부터 암시적으로 생성된 간단한 데이터 모델을 보여준다: + + + + +## 관련 토픽 + +* {@link dev_guide.mvc Angular의 MVC} +* {@link dev_guide.mvc.understanding_controller 컨트롤러 컴포넌트 이해하기} +* {@link dev_guide.mvc.understanding_view 뷰 컴포넌트 이해하기} diff --git a/docs/content-ko-back/guide/dev_guide.mvc.understanding_view.ngdoc b/docs/content-ko-back/guide/dev_guide.mvc.understanding_view.ngdoc new file mode 100644 index 000000000000..2e8732b02850 --- /dev/null +++ b/docs/content-ko-back/guide/dev_guide.mvc.understanding_view.ngdoc @@ -0,0 +1,20 @@ +@ngdoc overview +@name Developer Guide: Angular의 MVC: 뷰 컴포넌트 이해하기 +@description + +Angular에서 뷰는 Angular가 템플릿, 컨트롤러 그리고 모델의 정보를 기반으로 DOM을 변환한 후 +브라우저에서 그 DOM을 로드하여 렌더링한 것이다. + + + +Angular가 구현한 MVC에서 뷰는 모델과 컨트롤러 모두에 대해 알고 있다. 뷰는 어떤 모델에서 +양방향 데이터 바인딩이 발생하는지 알고 있으며 {@link api/ng.directive:ngController ngController} 와 +{@link api/ng.directive:ngView ngView} 와 같은 Angular 지시자나 `{{someControllerFunction()}}` 이런 형태의 바인딩을 통해 +컨트롤러에 대해 알고 있다. 이런 방법으로 뷰는 연결되어 있는 컨트롤러 함수에서 함수들을 호출할 수 있다. + + +## 관련 토픽 + +* {@link dev_guide.mvc About Angular의 MVC} +* {@link dev_guide.mvc.understanding_model 모델 컴포넌트 이해하기} +* {@link dev_guide.mvc.understanding_controller 컨트롤러 컴포넌트 이해하기} diff --git a/docs/content-ko-back/guide/dev_guide.services.$location.ngdoc b/docs/content-ko-back/guide/dev_guide.services.$location.ngdoc new file mode 100644 index 000000000000..7a607299dee5 --- /dev/null +++ b/docs/content-ko-back/guide/dev_guide.services.$location.ngdoc @@ -0,0 +1,643 @@ +@ngdoc overview +@name Developer Guide: Angular Services: Using $location +@description + +# What does it do? + +The `$location` service parses the URL in the browser address bar (based on the {@link +https://developer.mozilla.org/en/window.location window.location}) and makes the URL available to +your application. Changes to the URL in the address bar are reflected into $location service and +changes to $location are reflected into the browser address bar. + +**The $location service:** + +- Exposes the current URL in the browser address bar, so you can + - Watch and observe the URL. + - Change the URL. +- Synchronizes the URL with the browser when the user + - Changes the address bar. + - Clicks the back or forward button (or clicks a History link). + - Clicks on a link. +- Represents the URL object as a set of methods (protocol, host, port, path, search, hash). + + +## Comparing $location to window.location + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
window.location$location service
purposeallow read/write access to the current browser locationsame
APIexposes "raw" object with properties that can be directly modifiedexposes jQuery-style getters and setters
integration with angular application life-cyclenoneknows about all internal life-cycle phases, integrates with $watch, ...
seamless integration with HTML5 APInoyes (with a fallback for legacy browsers)
aware of docroot/context from which the application is loadedno - window.location.path returns "/docroot/actual/path"yes - $location.path() returns "/actual/path"
+ +## When should I use $location? +Any time your application needs to react to a change in the current URL or if you want to change +the current URL in the browser. + +## What does it not do? +It does not cause a full page reload when the browser URL is changed. To reload the page after +changing the URL, use the lower-level API, `$window.location.href`. + +# General overview of the API + +The `$location` service can behave differently, depending on the configuration that was provided to +it when it was instantiated. The default configuration is suitable for many applications, for +others customizing the configuration can enable new features. + +Once the `$location` service is instantiated, you can interact with it via jQuery-style getter and +setter methods that allow you to get or change the current URL in the browser. + +## $location service configuration + +To configure the `$location` service, retrieve the +{@link api/ng.$locationProvider $locationProvider} and set the parameters as follows: + + +- **html5Mode(mode)**: {boolean}
+ `true` - see HTML5 mode
+ `false` - see Hashbang mode
+ default: `false` + +- **hashPrefix(prefix)**: {string}
+ prefix used for Hashbang URLs (used in Hashbang mode or in legacy browser in Html5 mode)
+ default: `'!'` + +### Example configuration +
+$locationProvider.html5Mode(true).hashPrefix('!');
+
+ +## Getter and setter methods + +`$location` service provides getter methods for read-only parts of the URL (absUrl, protocol, host, +port) and getter / setter methods for url, path, search, hash: +
+// get the current path
+$location.path();
+
+// change the path
+$location.path('/newValue')
+
+ +All of the setter methods return the same `$location` object to allow chaining. For example, to +change multiple segments in one go, chain setters like this: +
$location.path('/newValue').search({key: value});
+ +There is a special `replace` method which can be used to tell the $location service that the next +time the $location service is synced with the browser, the last history record should be replaced +instead of creating a new one. This is useful when you want to implement redirection, which would +otherwise break the back button (navigating back would retrigger the redirection). To change the +current URL without creating a new browser history record you can call: +
+  $location.path('/someNewPath');
+  $location.replace();
+  // or you can chain these as: $location.path('/someNewPath').replace();
+
+ +Note that the setters don't update `window.location` immediately. Instead, the `$location` service is +aware of the {@link api/ng.$rootScope.Scope scope} life-cycle and coalesces multiple `$location` +mutations into one "commit" to the `window.location` object during the scope `$digest` phase. Since +multiple changes to the $location's state will be pushed to the browser as a single change, it's +enough to call the `replace()` method just once to make the entire "commit" a replace operation +rather than an addition to the browser history. Once the browser is updated, the $location service +resets the flag set by `replace()` method and future mutations will create new history records, +unless `replace()` is called again. + +### Setters and character encoding +You can pass special characters to `$location` service and it will encode them according to rules +specified in {@link http://www.ietf.org/rfc/rfc3986.txt RFC 3986}. When you access the methods: + +- All values that are passed to `$location` setter methods, `path()`, `search()`, `hash()`, are +encoded. +- Getters (calls to methods without parameters) return decoded values for the following methods +`path()`, `search()`, `hash()`. +- When you call the `absUrl()` method, the returned value is a full url with its segments encoded. +- When you call the `url()` method, the returned value is path, search and hash, in the form +`/path?search=a&b=c#hash`. The segments are encoded as well. + + +# Hashbang and HTML5 Modes + +`$location` service has two configuration modes which control the format of the URL in the browser +address bar: **Hashbang mode** (the default) and the **HTML5 mode** which is based on using the +HTML5 {@link http://www.w3.org/TR/html5/history.html History API}. Applications use the same API in +both modes and the `$location` service will work with appropriate URL segments and browser APIs to +facilitate the browser URL change and history management. + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
Hashbang modeHTML5 mode
configurationthe default{ html5Mode: true }
URL formathashbang URLs in all browsersregular URLs in modern browser, hashbang URLs in old browser
<a href=""> link rewritingnoyes
requires server-side configurationnoyes
+ +## Hashbang mode (default mode) + +In this mode, `$location` uses Hashbang URLs in all browsers. + +### Example + +
+it('should show example', inject(
+  function($locationProvider) {
+    $locationProvider.html5Mode(false);
+    $locationProvider.hashPrefix = '!';
+  },
+  function($location) {
+    // open http://host.com/base/index.html#!/a
+    $location.absUrl() == 'http://host.com/base/index.html#!/a'
+    $location.path() == '/a'
+
+    $location.path('/foo')
+    $location.absUrl() == 'http://host.com/base/index.html#!/foo'
+
+    $location.search() == {}
+    $location.search({a: 'b', c: true});
+    $location.absUrl() == 'http://host.com/base/index.html#!/foo?a=b&c'
+
+    $location.path('/new').search('x=y');
+    $location.absUrl() == 'http://host.com/base/index.html#!/new?x=y'
+  }
+));
+
+ +### Crawling your app + +To allow indexing of your AJAX application, you have to add special meta tag in the head section of +your document: +
+ +This will cause crawler bot to request links with `_escaped_fragment_` param so that your server +can recognize the crawler and serve a HTML snapshots. For more information about this technique, +see {@link http://code.google.com/web/ajaxcrawling/docs/specification.html Making AJAX Applications +Crawlable}. + +## HTML5 mode + +In HTML5 mode, the `$location` service getters and setters interact with the browser URL address +through the HTML5 history API, which allows for use of regular URL path and search segments, +instead of their hashbang equivalents. If the HTML5 History API is not supported by a browser, the +`$location` service will fall back to using the hashbang URLs automatically. This frees you from +having to worry about whether the browser displaying your app supports the history API or not; the +`$location` service transparently uses the best available option. + +- Opening a regular URL in a legacy browser -> redirects to a hashbang URL +- Opening hashbang URL in a modern browser -> rewrites to a regular URL + +### Example + +
+it('should show example', inject(
+  function($locationProvider) {
+    $locationProvider.html5Mode(true);
+    $locationProvider.hashPrefix = '!';
+  },
+  function($location) {
+    // in browser with HTML5 history support:
+    // open http://host.com/#!/a -> rewrite to http://host.com/a
+    // (replacing the http://host.com/#!/a history record)
+    $location.path() == '/a'
+
+    $location.path('/foo');
+    $location.absUrl() == 'http://host.com/foo'
+
+    $location.search() == {}
+    $location.search({a: 'b', c: true});
+    $location.absUrl() == 'http://host.com/foo?a=b&c'
+
+    $location.path('/new').search('x=y');
+    $location.url() == 'new?x=y'
+    $location.absUrl() == 'http://host.com/new?x=y'
+
+    // in browser without html5 history support:
+    // open http://host.com/new?x=y -> redirect to http://host.com/#!/new?x=y
+    // (again replacing the http://host.com/new?x=y history item)
+    $location.path() == '/new'
+    $location.search() == {x: 'y'}
+
+    $location.path('/foo/bar');
+    $location.path() == '/foo/bar'
+    $location.url() == '/foo/bar?x=y'
+    $location.absUrl() == 'http://host.com/#!/foo/bar?x=y'
+  }
+));
+
+ +### Fallback for legacy browsers + +For browsers that support the HTML5 history API, `$location` uses the HTML5 history API to write +path and search. If the history API is not supported by a browser, `$location` supplies a Hasbang +URL. This frees you from having to worry about whether the browser viewing your app supports the +history API or not; the `$location` service makes this transparent to you. + +### Html link rewriting + +When you use HTML5 history API mode, you will need different links in different browsers, but all you +have to do is specify regular URL links, such as: `link` + +When a user clicks on this link, + +- In a legacy browser, the URL changes to `/index.html#!/some?foo=bar` +- In a modern browser, the URL changes to `/some?foo=bar` + + +In cases like the following, links are not rewritten; instead, the browser will perform a full page +reload to the original link. + +- Links that contain `target` element
+ Example: `link` +- Absolute links that go to a different domain
+ Example: `link` +- Links starting with '/' that lead to a different base path when base is defined
+ Example: `link` + + +### Server side + +Using this mode requires URL rewriting on server side, basically you have to rewrite all your links +to entry point of your application (e.g. index.html) + +### Crawling your app + +If you want your AJAX application to be indexed by web crawlers, you will need to add the following +meta tag to the HEAD section of your document: +
+ +This statement causes a crawler to request links with an empty `_escaped_fragment_` parameter so that +your server can recognize the crawler and serve it HTML snapshots. For more information about this +technique, see {@link http://code.google.com/web/ajaxcrawling/docs/specification.html Making AJAX +Applications Crawlable}. + +### Relative links + +Be sure to check all relative links, images, scripts etc. You must either specify the url base in +the head of your main html file (``) or you must use absolute urls +(starting with `/`) everywhere because relative urls will be resolved to absolute urls using the +initial absolute url of the document, which is often different from the root of the application. + +Running Angular apps with the History API enabled from document root is strongly encouraged as it +takes care of all relative link issues. + +### Sending links among different browsers + +Because of rewriting capability in HTML5 mode, your users will be able to open regular url links in +legacy browsers and hashbang links in modern browser: + +- Modern browser will rewrite hashbang URLs to regular URLs. +- Older browsers will redirect regular URLs to hashbang URLs. + +### Example + +Here you can see two `$location` instances, both in **Html5 mode**, but on different browsers, so +that you can see the differences. These `$location` services are connected to a fake browsers. Each +input represents address bar of the browser. + +Note that when you type hashbang url into first browser (or vice versa) it doesn't rewrite / +redirect to regular / hashbang url, as this conversion happens only during parsing the initial URL += on page reload. + +In this examples we use `` + + + +
+
+

Browser with History API

+


+ $location.protocol() = {{$location.protocol()}}
+ $location.host() = {{$location.host()}}
+ $location.port() = {{$location.port()}}
+ $location.path() = {{$location.path()}}
+ $location.search() = {{$location.search()}}
+ $location.hash() = {{$location.hash()}}
+ /base/first?a=b | + sec/ond?flag#hash | + external +
+ +
+

Browser without History API

+


+ $location.protocol() = {{$location.protocol()}}
+ $location.host() = {{$location.host()}}
+ $location.port() = {{$location.port()}}
+ $location.path() = {{$location.path()}}
+ $location.search() = {{$location.search()}}
+ $location.hash() = {{$location.hash()}}
+ /base/first?a=b | + sec/ond?flag#hash | + external +
+
+ + + +
+
+ + +# Caveats + +## Page reload navigation + +The `$location` service allows you to change only the URL; it does not allow you to reload the +page. When you need to change the URL and reload the page or navigate to a different page, please +use a lower level API, {@link api/ng.$window $window.location.href}. + +## Using $location outside of the scope life-cycle + +`$location` knows about Angular's {@link api/ng.$rootScope.Scope scope} life-cycle. When a URL changes in +the browser it updates the `$location` and calls `$apply` so that all $watchers / $observers are +notified. +When you change the `$location` inside the `$digest` phase everything is ok; `$location` will +propagate this change into browser and will notify all the $watchers / $observers. +When you want to change the `$location` from outside Angular (for example, through a DOM Event or +during testing) - you must call `$apply` to propagate the changes. + +## $location.path() and ! or / prefixes + +A path should always begin with forward slash (`/`); the `$location.path()` setter will add the +forward slash if it is missing. + +Note that the `!` prefix in the hashbang mode is not part of `$location.path()`; it is actually +hashPrefix. + + +# Testing with the $location service + +When using `$location` service during testing, you are outside of the angular's {@link +api/ng.$rootScope.Scope scope} life-cycle. This means it's your responsibility to call `scope.$apply()`. + +
+describe('serviceUnderTest', function() {
+  beforeEach(module(function($provide) {
+    $provide.factory('serviceUnderTest', function($location){
+      // whatever it does...
+    });
+  });
+
+  it('should...', inject(function($location, $rootScope, serviceUnderTest) {
+    $location.path('/new/path');
+    $rootScope.$apply();
+
+    // test whatever the service should do...
+
+  }));
+});
+
+ + +# Migrating from earlier AngularJS releases + +In earlier releases of Angular, `$location` used `hashPath` or `hashSearch` to process path and +search methods. With this release, the `$location` service processes path and search methods and +then uses the information it obtains to compose hashbang URLs (such as +`http://server.com/#!/path?search=a`), when necessary. + +## Changes to your code + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
Navigation inside the appChange to
$location.href = value
$location.hash = value
$location.update(value)
$location.updateHash(value)
$location.path(path).search(search)
$location.hashPath = path$location.path(path)
$location.hashSearch = search$location.search(search)
Navigation outside the appUse lower level API
$location.href = value
$location.update(value)
$window.location.href = value
$location[protocol | host | port | path | search]$window.location[protocol | host | port | path | search]
Read accessChange to
$location.hashPath$location.path()
$location.hashSearch$location.search()
$location.href
$location.protocol
$location.host
$location.port
$location.hash
$location.absUrl()
$location.protocol()
$location.host()
$location.port()
$location.path() + $location.search()
$location.path
$location.search
$window.location.path
$window.location.search
+ +## Two-way binding to $location + +The Angular's compiler currently does not support two-way binding for methods (see {@link +https://github.com/angular/angular.js/issues/404 issue}). If you should require two-way binding +to the $location object (using {@link api/ng.directive:input.text +ngModel} directive on an input field), you will need to specify an extra model property +(e.g. `locationPath`) with two watchers which push $location updates in both directions. For +example: +
+
+
+
+
+// js - controller
+$scope.$watch('locationPath', function(path) {
+  $location.path(path);
+});
+
+$scope.$watch('$location.path()', function(path) {
+  scope.locationPath = path;
+});
+
+ + +# Related API + +* {@link api/ng.$location $location API} + + + diff --git a/docs/content-ko-back/guide/dev_guide.services.creating_services.ngdoc b/docs/content-ko-back/guide/dev_guide.services.creating_services.ngdoc new file mode 100644 index 000000000000..d5adc4babdff --- /dev/null +++ b/docs/content-ko-back/guide/dev_guide.services.creating_services.ngdoc @@ -0,0 +1,104 @@ +@ngdoc overview +@name Developer Guide: Angular Services: Creating Services +@description + +While Angular offers several useful services, for any nontrivial application you'll find it useful +to write your own custom services. To do this you begin by registering a service factory function +with a module either via the {@link api/angular.module Module#factory api} or directly +via the {@link api/AUTO.$provide $provide} api inside of module config function. + +All Angular services participate in {@link di dependency injection (DI)} by registering +themselves with Angular's DI system (injector) under a `name` (id) as well as by declaring +dependencies which need to be provided for the factory function of the registered service. The +ability to swap dependencies for mocks/stubs/dummies in tests allows for services to be highly +testable. + + +# Registering Services + +To register a service, you must have a module that this service will be part of. Afterwards, you +can register the service with the module either via the {@link api/angular.Module Module api} or +by using the {@link api/AUTO.$provide $provide} service in the module configuration +function.The following pseudo-code shows both approaches: + +Using the angular.Module api: +
+var myModule = angular.module('myModule', []);
+myModule.factory('serviceId', function() {
+  var shinyNewServiceInstance;
+  //factory function body that constructs shinyNewServiceInstance
+  return shinyNewServiceInstance;
+});
+
+ +Using the $provide service: +
+angular.module('myModule', [], function($provide) {
+  $provide.factory('serviceId', function() {
+    var shinyNewServiceInstance;
+    //factory function body that constructs shinyNewServiceInstance
+    return shinyNewServiceInstance;
+  });
+});
+
+ +Note that you are not registering a service instance, but rather a factory function that will +create this instance when called. + + +# Dependencies + +Services can not only be depended upon, but can also have their own dependencies. These can be specified +as arguments of the factory function. {@link di Read more} about dependency injection (DI) +in Angular and the use of array notation and the $inject property to make DI annotation +minification-proof. + +Following is an example of a very simple service. This service depends on the `$window` service +(which is passed as a parameter to the factory function) and is just a function. The service simply +stores all notifications; after the third one, the service displays all of the notifications by +window alert. + +
+angular.module('myModule', [], function($provide) {
+  $provide.factory('notify', ['$window', function(win) {
+    var msgs = [];
+    return function(msg) {
+      msgs.push(msg);
+      if (msgs.length == 3) {
+        win.alert(msgs.join("\n"));
+        msgs = [];
+      }
+    };
+  }]);
+});
+
+ + +# Instantiating Angular Services + +All services in Angular are instantiated lazily. This means that a service will be created +only when it is needed for instantiation of a service or an application component that depends on it. +In other words, Angular won't instantiate services unless they are requested directly or +indirectly by the application. + + +# Services as singletons + +Lastly, it is important to realize that all Angular services are application singletons. This means +that there is only one instance of a given service per injector. Since Angular is lethally allergic +to global state, it is possible to create multiple injectors, each with its own instance of a +given service, but that is rarely needed, except in tests where this property is crucially +important. + + + +## Related Topics + +* {@link dev_guide.services.understanding_services Understanding Angular Services} +* {@link dev_guide.services.managing_dependencies Managing Service Dependencies} +* {@link dev_guide.services.injecting_controllers Injecting Services Into Controllers } +* {@link dev_guide.services.testing_services Testing Angular Services} + +## Related API + +* {@link api/ng Angular Service API} diff --git a/docs/content-ko-back/guide/dev_guide.services.injecting_controllers.ngdoc b/docs/content-ko-back/guide/dev_guide.services.injecting_controllers.ngdoc new file mode 100644 index 000000000000..2da7c248cb7b --- /dev/null +++ b/docs/content-ko-back/guide/dev_guide.services.injecting_controllers.ngdoc @@ -0,0 +1,118 @@ +@ngdoc overview +@name Developer Guide: Angular Services: Injecting Services Into Controllers +@description + +Using services as dependencies for controllers is very similar to using services as dependencies +for another service. + +Since JavaScript is a dynamic language, DI can't figure out which services to inject by static +types (like in static typed languages). Therefore, you can specify the service name by using the +`$inject` property, which is an array containing strings with names of services to be injected. +The name must match the corresponding service ID registered with angular. The order of the service +IDs matters: the order of the services in the array will be used when calling the factory function +with injected parameters. The names of parameters in factory function don't matter, but by +convention they match the service IDs, which has added benefits discussed below. + +
+function myController($loc, $log) {
+this.firstMethod = function() {
+ // use $location service
+ $loc.setHash();
+};
+this.secondMethod = function() {
+ // use $log service
+ $log.info('...');
+};
+}
+// which services to inject ?
+myController.$inject = ['$location', '$log'];
+
+ + + + + +
+

Let's try this simple notify service, injected into the controller...

+ + +
+
+ + it('should test service', function() { + expect(element(':input[ng\\:model="message"]').val()).toEqual('test'); + }); + +
+ +## Implicit Dependency Injection + +A new feature of Angular DI allows it to determine the dependency from the name of the parameter. +Let's rewrite the above example to show the use of this implicit dependency injection of +`$window`, `$scope`, and our `notify` service: + + + + +
+

Let's try the notify service, that is implicitly injected into the controller...

+ + +
+
+
+ +However, if you plan to {@link http://en.wikipedia.org/wiki/Minification_(programming) minify} your +code, your variable names will get renamed in which case you will still need to explicitly specify +dependencies with the `$inject` property. + +## Related Topics + +{@link dev_guide.services.understanding_services Understanding Angular Services} +{@link dev_guide.services.creating_services Creating Angular Services} +{@link dev_guide.services.managing_dependencies Managing Service Dependencies} +{@link dev_guide.services.testing_services Testing Angular Services} + +## Related API + +{@link api/ng Angular Service API} diff --git a/docs/content-ko-back/guide/dev_guide.services.managing_dependencies.ngdoc b/docs/content-ko-back/guide/dev_guide.services.managing_dependencies.ngdoc new file mode 100644 index 000000000000..6a769ca06f3e --- /dev/null +++ b/docs/content-ko-back/guide/dev_guide.services.managing_dependencies.ngdoc @@ -0,0 +1,114 @@ +@ngdoc overview +@name Developer Guide: Angular Services: Managing Service Dependencies +@description + +Angular allows services to declare other services as dependencies needed for construction of their +instances. + +To declare dependencies, you specify them in the factory function signature and annotate the +function with the inject annotations either using by setting the `$inject` property, as an array of +string identifiers or using the array notation. Optionally the `$inject` property declaration can be +dropped (see "Inferring `$inject`" but note that that is currently an experimental feature). + +Using the array notation: + +
+function myModuleCfgFn($provide) {
+  $provide.factory('myService', ['dep1', 'dep2', function(dep1, dep2) {}]);
+}
+
+ + +Using the $inject property: + +
+function myModuleCfgFn($provide) {
+  var myServiceFactory = function(dep1, dep2) {};
+  myServiceFactory.$inject = ['dep1', 'dep2'];
+  $provide.factory('myService', myServiceFactory);
+}
+
+ + +Using DI inference (incompatible with minifiers): + +
+function myModuleCfgFn($provide) {
+  $provide.factory('myService', function(dep1, dep2) {});
+}
+
+ + +Here is an example of two services, one of which depends on the other and both +of which depend on other services that are provided by the Angular framework: + +
+/**
+ * batchLog service allows for messages to be queued in memory and flushed
+ * to the console.log every 50 seconds.
+ *
+ * @param {*} message Message to be logged.
+ */
+  function batchLogModule($provide){
+    $provide.factory('batchLog', ['$timeout', '$log', function($timeout, $log) {
+      var messageQueue = [];
+
+      function log() {
+        if (messageQueue.length) {
+          $log('batchLog messages: ', messageQueue);
+          messageQueue = [];
+        }
+        $timeout(log, 50000);
+      }
+
+      // start periodic checking
+      log();
+
+      return function(message) {
+        messageQueue.push(message);
+      }
+    }]);
+
+    /**
+     * routeTemplateMonitor monitors each $route change and logs the current
+     * template via the batchLog service.
+     */
+    $provide.factory('routeTemplateMonitor',
+                ['$route', 'batchLog', '$rootScope',
+         function($route,   batchLog,   $rootScope) {
+      $rootScope.$on('$routeChangeSuccess', function() {
+        batchLog($route.current ? $route.current.template : null);
+      });
+    }]);
+  }
+
+  // get the main service to kick of the application
+  angular.injector([batchLogModule]).get('routeTemplateMonitor');
+
+ +Things to notice in this example: + +* The `batchLog` service depends on the built-in {@link api/ng.$timeout $timeout} and +{@link api/ng.$log $log} services, and allows messages to be logged into the +`console.log` in batches. +* The `routeTemplateMonitor` service depends on the built-in {@link api/ng.$route +$route} service as well as our custom `batchLog` service. +* Both of our services use the factory function signature and array notation for inject annotations +to declare their dependencies. It is important that the order of the string identifiers in the array +is the same as the order of argument names in the signature of the factory function. Unless the +dependencies are inferred from the function signature, it is this array with IDs and their order +that the injector uses to determine which services and in which order to inject. + + +## Related Topics + +* {@link dev_guide.services.understanding_services Understanding Angular Services} +* {@link dev_guide.services.creating_services Creating Angular Services} +* {@link dev_guide.services.injecting_controllers Injecting Services Into Controllers } +* {@link dev_guide.services.testing_services Testing Angular Services} + + +## Related API + +* {@link api/ng Angular Service API} +* {@link api/angular.injector Angular Injector API} diff --git a/docs/content-ko-back/guide/dev_guide.services.ngdoc b/docs/content-ko-back/guide/dev_guide.services.ngdoc new file mode 100644 index 000000000000..725e01e3eaf4 --- /dev/null +++ b/docs/content-ko-back/guide/dev_guide.services.ngdoc @@ -0,0 +1,20 @@ +@ngdoc overview +@name Developer Guide: Angular Services +@description + +Services are a feature that Angular brings to client-side web apps from the server side, where +services have been commonly used for a long time. Services in Angular apps are substitutable +objects that are wired together using {@link di dependency injection (DI)}. + + +## Related Topics + +* {@link dev_guide.services.understanding_services Understanding Angular Services} +* {@link dev_guide.services.creating_services Creating Angular Services} +* {@link dev_guide.services.managing_dependencies Managing Service Dependencies} +* {@link dev_guide.services.injecting_controllers Injecting Services Into Controllers} +* {@link dev_guide.services.testing_services Testing Angular Services} + +## Related API + +* {@link api/ng Angular Service API} diff --git a/docs/content-ko-back/guide/dev_guide.services.testing_services.ngdoc b/docs/content-ko-back/guide/dev_guide.services.testing_services.ngdoc new file mode 100644 index 000000000000..6e0bbacebdc6 --- /dev/null +++ b/docs/content-ko-back/guide/dev_guide.services.testing_services.ngdoc @@ -0,0 +1,62 @@ +@ngdoc overview +@name Developer Guide: Angular Services: Testing Angular Services +@description + +The following is a unit test for the 'notify' service in the 'Dependencies' example in {@link +dev_guide.services.creating_services Creating Angular Services}. The unit test example uses Jasmine +spy (mock) instead of a real browser alert. + +
+var mock, notify;
+
+beforeEach(function() {
+  mock = {alert: jasmine.createSpy()};
+
+  module(function($provide) {
+    $provide.value('$window', mock);
+  });
+
+  inject(function($injector) {
+    notify = $injector.get('notify');
+  });
+});
+
+it('should not alert first two notifications', function() {
+  notify('one');
+  notify('two');
+
+  expect(mock.alert).not.toHaveBeenCalled();
+});
+
+it('should alert all after third notification', function() {
+  notify('one');
+  notify('two');
+  notify('three');
+
+  expect(mock.alert).toHaveBeenCalledWith("one\ntwo\nthree");
+});
+
+it('should clear messages after alert', function() {
+  notify('one');
+  notify('two');
+  notify('third');
+  notify('more');
+  notify('two');
+  notify('third');
+
+  expect(mock.alert.callCount).toEqual(2);
+  expect(mock.alert.mostRecentCall.args).toEqual(["more\ntwo\nthird"]);
+});
+
+ + +## Related Topics + +* {@link dev_guide.services.understanding_services Understanding Angular Services} +* {@link dev_guide.services.creating_services Creating Angular Services} +* {@link dev_guide.services.managing_dependencies Managing Service Dependencies} +* {@link dev_guide.services.injecting_controllers Injecting Services Into Controllers} + +## Related API + +* {@link api/ng Angular Service API} diff --git a/docs/content-ko-back/guide/dev_guide.services.understanding_services.ngdoc b/docs/content-ko-back/guide/dev_guide.services.understanding_services.ngdoc new file mode 100644 index 000000000000..339439a0df8a --- /dev/null +++ b/docs/content-ko-back/guide/dev_guide.services.understanding_services.ngdoc @@ -0,0 +1,36 @@ +@ngdoc overview +@name Developer Guide: Angular Services: Understanding Angular Services +@description + +Angular services are singletons that carry out specific tasks common to web apps, such as the +{@link api/ng.$http $http service} that provides low level access to the browser's +`XMLHttpRequest` object. + +To use an Angular service, you identify it as a dependency for the dependent (a controller, or +another service) that depends on the service. Angular's dependency injection subsystem takes care +of the rest. The Angular injector subsystem is in charge of service instantiation, resolution of +dependencies, and provision of dependencies to factory functions as requested. + +Angular injects dependencies using "constructor" injection (the service is passed in via a factory +function). Because JavaScript is a dynamically typed language, Angular's dependency injection +subsystem cannot use static types to identify service dependencies. For this reason a dependent +must explicitly define its dependencies by using the `$inject` property. For example: + + myController.$inject = ['$location']; + +The Angular web framework provides a set of services for common operations. Like other core Angular +variables and identifiers, the built-in services always start with `$` (such as `$http` mentioned +above). You can also create your own custom services. + + +## Related Topics + +* {@link di About Angular Dependency Injection} +* {@link dev_guide.services.creating_services Creating Angular Services} +* {@link dev_guide.services.managing_dependencies Managing Service Dependencies} +* {@link dev_guide.services.testing_services Testing Angular Services} + +## Related API + +* {@link api/ng Angular Service API} +* {@link api/angular.injector Injector API} diff --git a/docs/content-ko-back/guide/dev_guide.templates.css-styling.ngdoc b/docs/content-ko-back/guide/dev_guide.templates.css-styling.ngdoc new file mode 100644 index 000000000000..323191944ae2 --- /dev/null +++ b/docs/content-ko-back/guide/dev_guide.templates.css-styling.ngdoc @@ -0,0 +1,22 @@ +@ngdoc overview +@name Developer Guide: 템플릿: Angular에서 CSS 작업하기 +@description + +Angular는 아래의 CSS 클래스만을 설정한다. 유용한 스타일을 제공한는 것은 어플리케이션에 달려있다. + +# Angular에서 사용되는 CSS 클래스 + +* `ng-invalid`, `ng-valid` + - **사용법:** Angular는 해당 요소의 입력값이 유효성 검사를 통과하지 못한 경우 input 위젯 요소에 + 이 클래스를 적용한다. ({@link api/ng.directive:input input} 지시자(directive)를 살펴보자) + +* `ng-pristine`, `ng-dirty` + - **사용법:** Angular의 {@link api/ng.directive:input input} 지시자는 사용자가 입력한 적이 없는 + 새로운 input 위젯 요소에 `ng-pristine` 클래스를 적용한다. 해당 input 위젯 요소에 사용자가 + 한번 입력을 하고 나면 `ng-dirty` 클래스로 변경된다. + + +## 관련 토픽 + +* {@link dev_guide.templates Angular의 템플릿} +* {@link forms Angular의 폼} diff --git a/docs/content-ko-back/guide/dev_guide.templates.databinding.ngdoc b/docs/content-ko-back/guide/dev_guide.templates.databinding.ngdoc new file mode 100644 index 000000000000..9c811f432210 --- /dev/null +++ b/docs/content-ko-back/guide/dev_guide.templates.databinding.ngdoc @@ -0,0 +1,39 @@ +@ngdoc overview +@name Developer Guide: 템플릿: Angular의 데이터 바인딩 +@description + +Angular 웹 어플리케이션의 데이터 바인딩은 모델과 뷰 컴포넌트간에 자동으로 데이터 동기화가 이루어지게 한다. +Angular가 데이터 바인딩을 구현한 방법은 어플리케이션에서 모델을 "단일정보의 가치(single-source-of-truth)"라는 +관점으로 다룰 수 있게 한다. 뷰는 항상 모델을 투영한다. 모델이 변경되면 뷰가 그 변경사항을 반영하며, +그 반대도 마찬가지다. + +## 전형적인 템플릿 시스템의 데이터 바인딩 + + + +대부분의 템플릿 시스템은 데이터가 단방향으로만 바인딩된다: 그림에서 보는 바와 같이 템플릿과 +모델 컴포넌트가 하나의 뷰로 병합된다. 병합된 후에는 모델이 변경되거나 뷰에서 모델과 관련된 부분이 변경되어도 +뷰에 자동으로 반영되지는 않는다. 더군다나 사용자가 뷰에 대해 수행한 모든 변경사항이 모델에 반영되지는 않는다. +이것은 개발자가 뷰와 모델간에 그리고 모델과 뷰간에 지속적으로 동기화시키는 코드를 작성해야만 한다는 것을 +의미한다. + +## Angular 템플릿의 데이터 바인딩 + + + +그림에서 보듯이 Angular 템플릿이 작동하는 방식은 전형적인 템플릿 시스템과는 다르다. 다른 이유는 첫번째로 +템플릿(추가되는 모든 마크업이나 지시자와 더불어 컴파일되지 않은 HTML)이 브라우저에서 컴파일된다는 것이다. +그리고 두번째는 그러한 컴파일 단계에서 라이브 뷰가 만들어진다는 것이다. 라이브라고 부르는 이유는 뷰의 +모든 변경사항이 즉시 모델에 반영이 되며, 모델의 모든 변경사항 또한 뷰에 전파되기 때문이다. 이것은 모델이 +어플리케이션 상태에 대해 항상 단일정보의 가치(single-source-of-truth)를 갖을 수 있도록 하고, 개발자들에게는 +아주 간단한 프로그래밍 모델을 만들어 준다. + +뷰는 단지 모델을 투영하고만 있는 것이기 때문에 컨트롤러는 뷰와 완전히 분리되고 그것을 인식하지 못한다. +이것이 어떤 한 순간의 상태를 테스트할 수 있게 한다. 왜냐하면 컨트롤러를 뷰 그리고 관련된 DOM/브라우저의 +종속성 없이 별개로 테스트하기 쉽기 때문이다. + + +## 관련 토픽 + +* {@link scope Angular 스코프} +* {@link dev_guide.templates Angular 템플릿} diff --git a/docs/content-ko-back/guide/dev_guide.templates.filters.creating_filters.ngdoc b/docs/content-ko-back/guide/dev_guide.templates.filters.creating_filters.ngdoc new file mode 100644 index 000000000000..bb2da683536a --- /dev/null +++ b/docs/content-ko-back/guide/dev_guide.templates.filters.creating_filters.ngdoc @@ -0,0 +1,58 @@ +@ngdoc overview +@name Developer Guide: 템플릿: 필터: Angular에서 필터 생성하기 +@description + +자신만의 필터를 만드는 것은 매우 쉽다: 모듈에 (주입 가능한) 팩토리 함수로 새로운 필터를 등록하기만 +하면 된다. 이 팩토리 함수는 첫번째 인자로 입력값을 받는 새로운 필터 함수를 반환해야만 한다. 필터의 +모든 인자는 필터 함수에 인자를 추가하여 전달된다. + +다음 예제의 필터는 문자열의 순서를 뒤집는다. 또한, 조건부로 문자열을 대문자로 변환한다. + + + + + +
+
+ No filter: {{greeting}}
+ Reverse: {{greeting|reverse}}
+ Reverse + uppercase: {{greeting|reverse:true}}
+
+
+ + it('should reverse greeting', function() { + expect(binding('greeting|reverse')).toEqual('olleh'); + input('greeting').enter('ABC'); + expect(binding('greeting|reverse')).toEqual('CBA'); + }); + +
+ + +## 관련 토픽 + +* {@link dev_guide.templates.filters Angular의 필터 이해하기} +* {@link compiler Angular의 HTML 컴파일러} + +## 관련 API + +* {@link api/ng.$filter Angular의 필터 API} diff --git a/docs/content-ko-back/guide/dev_guide.templates.filters.ngdoc b/docs/content-ko-back/guide/dev_guide.templates.filters.ngdoc new file mode 100644 index 000000000000..35b741d410f4 --- /dev/null +++ b/docs/content-ko-back/guide/dev_guide.templates.filters.ngdoc @@ -0,0 +1,22 @@ +@ngdoc overview +@name Developer Guide: 템플릿: Angular의 필터 이해하기 +@description + +Angular의 필터는 데이터를 포맷팅(서식화)해서 사용자에게 보여준다. + +예를 들면 사용자에게 데이터를 보여주기 전에 지역에 따라 포맷팅을 해야만 하는 경우가 있을 수도 있다. +아래의 예처럼 필터 체인을 통해 표현식을 전달할 수 있다. + + name | uppercase + +위 표현식은 간단하게 name의 값을 {@link api/ng.filter:uppercase uppercase 필터}에게 전달한다. + + +## 관련 토픽 + +* {@link dev_guide.templates.filters.using_filters Angular에서 필터 사용하기} +* {@link dev_guide.templates.filters.creating_filters Angular에서 필터 생성하기} + +## 관련 API + +* {@link api/ng.$filter Angular의 필터 API} diff --git a/docs/content-ko-back/guide/dev_guide.templates.filters.using_filters.ngdoc b/docs/content-ko-back/guide/dev_guide.templates.filters.using_filters.ngdoc new file mode 100644 index 000000000000..9cc957a28a34 --- /dev/null +++ b/docs/content-ko-back/guide/dev_guide.templates.filters.using_filters.ngdoc @@ -0,0 +1,39 @@ +@ngdoc overview +@name Developer Guide: 템플릿: 필터: Angular에서 필터 사용하기 +@description + +필터는 특정 {@link api/ng.$rootScope.Scope}에 해당하는 계산의 일부가 될 수 있지만, 일반적으로는 +템플릿에 바인딩되는 표현식을 포맷팅(서식화)하기 위해 사용된다. + + {{ expression | filter }} + +필터는 보통 포맷팅하는 과정에서 데이터를 새로운 데이터 타입으로 변환한다. +필터는 연결될 수 있고 선택적으로 인자를 받을 수도 있다. + +아래와 같은 구문을 사용해서 필터를 연결할 수 있다. + + {{ expression | filter1 | filter2 }} + +콜론 구분자를 사용해서 필터에 인자를 전달할 수도 있다. 아래의 예는 123라는 숫자를 소수점 두자리까지 +표시해주고 있다. + + 123 | number:2 + +아래는 바인딩되는 표현식에 서로 다른 필터들을 적용하기 전과 적용한 후의 값을 보여주는 +몇가지 예제이다. + +* 필터가 없는 경우: `{{1234.5678}}` => `1234.5678` +* 숫자 filter: `{{1234.5678|number}}` => `1,234.57`. "," 과 소수점 두자리까지 반올림되는 것에 주의하자. +* 필터에 인자를 사용: `{{1234.5678|number:5}}` => `1,234.56780`. 필터는 선택적으로 바인딩에 콜론으로 +구분해서 인자를 받을 수 있다. 예를 들면, "number" 필터에 숫자로 받는 인자는 소수점 몇자리까지 +보여줄 것인지를 명시하는 것이다. + + +## 관련 토픽 + +* {@link dev_guide.templates.filters Angular의 필터 이해하기} +* {@link dev_guide.templates.filters.creating_filters Angular에서 필터 생성하기} + +## 관련 API + +* {@link api/ng.$filter Angular의 필터 API} diff --git a/docs/content-ko-back/guide/dev_guide.templates.ngdoc b/docs/content-ko-back/guide/dev_guide.templates.ngdoc new file mode 100644 index 000000000000..676a96d73a07 --- /dev/null +++ b/docs/content-ko-back/guide/dev_guide.templates.ngdoc @@ -0,0 +1,41 @@ +@ngdoc overview +@name Developer Guide: Angular 템플릿의 이해 +@description + +Angular 템플릿은, 모델과 컨트롤러에서의 정보를 유저가 브라우저를 통해서 볼 수 있게 뷰로 가공해주는, 선언적 명세서 입니다. +HTML, CSS, 그리고 angular 특유의 요소, 그리고 그 요소의 속성을 포함하는 정적인 DOM입니다. angular 요소와 그 속성들은 angular로 하여금 템플릿 DOM을 다이나믹 뷰 DOM으로 변환하게 합니다. + +다음과 같은 타입의 Angular 요소와 그 속성들을 템플릿에 사용할 수 있습니다: + +* {@link guide/directive 지시자(Directive)} - 기존의 DOM 요소 또는 재사용 DOM 컴포넌트를 보강하는 특성 또는 요소 - 위젯. +* {@link api/ng.$interpolate 마크업(Markup)} - angular에 내장되어있는 마크업으로 표현식을 요소에 연결시켜주는 중괄호 한쌍 '{{ }}' +* {@link dev_guide.templates.filters 필터(Filter)} - 사용자에게 데이터를 보여주기위해 변환을 해준다. +* {@link forms 폼 컨트롤(Form controls)} - 사용자 입력의 유효성 검사를 할 수 있다. + +Note: 덧붙여 말하자면 위에 있는 요소가 템플릿에 선언이 되면, JavaScript 코드로도 접근 할 수있다. + +다음 코드 스니펫은 표준 HTML 태그와 Angular {@link guide/directive 지시자(directives)} +그리고 {@link expression 표현식(expressions)}의 중괄호를 통한 바인딩을 한 간단한 Angular 템플릿을 보여준다: + +
+
+ 
+ 
+   
+   
+   
+   
+   
+ Hello
+ <span ng:bind="name">
+ <span ng_bind="name">
+ <span ng-bind="name">
+ <span data-ng-bind="name">
+ <span x-ng-bind="name">
+
+ + + it('should show off bindings', function() { + expect(element('div[ng-controller="Ctrl1"] span[ng-bind]').text()).toBe('angular'); + }); + + + +# String interpolation + +During the compilation process the {@link api/ng.$compile compiler} matches text and +attributes using the {@link api/ng.$interpolate $interpolate} service to see if they +contain embedded expressions. These expressions are registered as {@link +api/ng.$rootScope.Scope#$watch watches} and will update as part of normal {@link +api/ng.$rootScope.Scope#$digest digest} cycle. An example of interpolation is shown +here: + +
+Hello {{username}}!
+
+ +# Compilation process, and directive matching + +Compilation of HTML happens in three phases: + + 1. First the HTML is parsed into DOM using the standard browser API. This is important to + realize because the templates must be parsable HTML. This is in contrast to most templating + systems that operate on strings, rather than on DOM elements. + + 2. The compilation of the DOM is performed by the call to the {@link api/ng.$compile + $compile()} method. The method traverses the DOM and matches the directives. If a match is found + it is added to the list of directives associated with the given DOM element. Once all directives + for a given DOM element have been identified they are sorted by priority and their `compile()` + functions are executed. The directive compile function has a chance to modify the DOM structure + and is responsible for producing a `link()` function explained next. The {@link + api/ng.$compile $compile()} method returns a combined linking function, which is a + collection of all of the linking functions returned from the individual directive compile + functions. + + 3. Link the template with scope by calling the linking function returned from the previous step. + This in turn will call the linking function of the individual directives allowing them to + register any listeners on the elements and set up any {@link + api/ng.$rootScope.Scope#$watch watches} with the {@link + api/ng.$rootScope.Scope scope}. The result of this is a live binding between the + scope and the DOM. A change in the scope is reflected in the DOM. + +
+  var $compile = ...; // injected into your code
+  var scope = ...;
+
+  var html = '
'; + + // Step 1: parse HTML into DOM element + var template = angular.element(html); + + // Step 2: compile the template + var linkFn = $compile(template); + + // Step 3: link the compiled template with the scope. + linkFn(scope); +
+ +## Reasons behind the compile/link separation + +At this point you may wonder why the compile process is broken down to a compile and link phase. +To understand this, let's look at a real world example with a repeater: + +
+  Hello {{user}}, you have these actions:
+  
    +
  • + {{action.description}} +
  • +
+
+ +The short answer is that compile and link separation is needed any time a change in model causes +a change in DOM structure such as in repeaters. + +When the above example is compiled, the compiler visits every node and looks for directives. The +`{{user}}` is an example of an {@link api/ng.$interpolate interpolation} directive. {@link +api/ng.directive:ngRepeat ngRepeat} is another directive. But {@link +api/ng.directive:ngRepeat ngRepeat} has a dilemma. It needs to be +able to quickly stamp out new `li`s for every `action` in `user.actions`. This means that it needs +to save a clean copy of the `li` element for cloning purposes and as new `action`s are inserted, +the template `li` element needs to be cloned and inserted into `ul`. But cloning the `li` element +is not enough. It also needs to compile the `li` so that its directives such as +`{{action.descriptions}}` evaluate against the right {@link api/ng.$rootScope.Scope +scope}. A naive method would be to simply insert a copy of the `li` element and then compile it. +But compiling on every `li` element clone would be slow, since the compilation requires that we +traverse the DOM tree and look for directives and execute them. If we put the compilation inside a +repeater which needs to unroll 100 items we would quickly run into performance problems. + +The solution is to break the compilation process into two phases; the compile phase where all of +the directives are identified and sorted by priority, and a linking phase where any work which +links a specific instance of the {@link api/ng.$rootScope.Scope scope} and the specific +instance of an `li` is performed. + +{@link api/ng.directive:ngRepeat ngRepeat} works by preventing the +compilation process from descending into the `li` element. Instead the {@link +api/ng.directive:ngRepeat ngRepeat} directive compiles `li` +separately. The result of the `li` element compilation is a linking function which contains all +of the directives contained in the `li` element, ready to be attached to a specific clone of the `li` +element. At runtime the {@link api/ng.directive:ngRepeat ngRepeat} +watches the expression and as items are added to the array it clones the `li` element, creates a +new {@link api/ng.$rootScope.Scope scope} for the cloned `li` element and calls the +link function on the cloned `li`. + +Summary: + + * *compile function* - The compile function is relatively rare in directives, since most + directives are concerned with working with a specific DOM element instance rather than + transforming the template DOM element. Any operation which can be shared among the instance of + directives should be moved to the compile function for performance reasons. + + * *link function* - It is rare for the directive not to have a link function. A link function + allows the directive to register listeners to the specific cloned DOM element instance as well + as to copy content into the DOM from the scope. + + +# Writing directives (short version) + +In this example we will build a directive that displays the current time. + + + + +
+ Date format:
+ Current time is: +
+
+
+ + +# Writing directives (long version) + +An example skeleton of the directive is shown here, for the complete list see below. + +
+  var myModule = angular.module(...);
+
+  myModule.directive('directiveName', function factory(injectables) {
+    var directiveDefinitionObject = {
+      priority: 0,
+      template: '
', + templateUrl: 'directive.html', + replace: false, + transclude: false, + restrict: 'A', + scope: false, + compile: function compile(tElement, tAttrs, transclude) { + return { + pre: function preLink(scope, iElement, iAttrs, controller) { ... }, + post: function postLink(scope, iElement, iAttrs, controller) { ... } + } + }, + link: function postLink(scope, iElement, iAttrs) { ... } + }; + return directiveDefinitionObject; + }); +
+ +In most cases you will not need such fine control and so the above can be simplified. All of the +different parts of this skeleton are explained in following sections. In this section we are +interested only in some of this skeleton. + +The first step in simplyfing the code is to rely on the default values. Therefore the above can be +simplified as: + +
+  var myModule = angular.module(...);
+
+  myModule.directive('directiveName', function factory(injectables) {
+    var directiveDefinitionObject = {
+      compile: function compile(tElement, tAttrs) {
+        return function postLink(scope, iElement, iAttrs) { ... }
+      }
+    };
+    return directiveDefinitionObject;
+  });
+
+ +Most directives concern themselves only with instances, not with template transformations, allowing +further simplification: + +
+  var myModule = angular.module(...);
+
+  myModule.directive('directiveName', function factory(injectables) {
+    return function postLink(scope, iElement, iAttrs) { ... }
+  });
+
+ + +## Factory method + +The factory method is responsible for creating the directive. It is invoked only once, when the +{@link api/ng.$compile compiler} matches the directive for the first time. You can +perform any initialization work here. The method is invoked using the {@link +api/AUTO.$injector#invoke $injector.invoke} which +makes it injectable following all of the rules of injection annotation. + +## Directive Definition Object + +The directive definition object provides instructions to the {@link api/ng.$compile +compiler}. The attributes are: + + * `name` - Name of the current scope. Optional and defaults to the name at registration. + + * `priority` - When there are multiple directives defined on a single DOM element, sometimes it + is necessary to specify the order in which the directives are applied. The `priority` is used + to sort the directives before their `compile` functions get called. Higher `priority` goes + first. The order of directives within the same priority is undefined. + + * `terminal` - If set to true then the current `priority` will be the last set of directives + which will execute (any directives at the current priority will still execute + as the order of execution on same `priority` is undefined). + + * `scope` - If set to: + + * `true` - then a new scope will be created for this directive. If multiple directives on the + same element request a new scope, only one new scope is created. The new scope rule does not + apply for the root of the template since the root of the template always gets a new scope. + + * `{}` (object hash) - then a new 'isolate' scope is created. The 'isolate' scope differs from + normal scope in that it does not prototypically inherit from the parent scope. This is useful + when creating reusable components, which should not accidentally read or modify data in the + parent scope.
+ The 'isolate' scope takes an object hash which defines a set of local scope properties + derived from the parent scope. These local properties are useful for aliasing values for + templates. Locals definition is a hash of local scope property to its source: + + * `@` or `@attr` - bind a local scope property to the value of DOM attribute. The result is + always a string since DOM attributes are strings. If no `attr` name is specified then the + attribute name is assumed to be the same as the local name. + Given `` and widget definition + of `scope: { localName:'@myAttr' }`, then widget scope property `localName` will reflect + the interpolated value of `hello {{name}}`. As the `name` attribute changes so will the + `localName` property on the widget scope. The `name` is read from the parent scope (not + component scope). + + * `=` or `=attr` - set up bi-directional binding between a local scope property and the + parent scope property of name defined via the value of the `attr` attribute. If no `attr` + name is specified then the attribute name is assumed to be the same as the local name. + Given `` and widget definition of + `scope: { localModel:'=myAttr' }`, then widget scope property `localModel` will reflect the + value of `parentModel` on the parent scope. Any changes to `parentModel` will be reflected + in `localModel` and any changes in `localModel` will reflect in `parentModel`. + + * `&` or `&attr` - provides a way to execute an expression in the context of the parent scope. + If no `attr` name is specified then the attribute name is assumed to be the same as the + local name. Given `` and widget definition of + `scope: { localFn:'&myAttr' }`, then isolate scope property `localFn` will point to + a function wrapper for the `count = count + value` expression. Often it's desirable to + pass data from the isolated scope via an expression and to the parent scope, this can be + done by passing a map of local variable names and values into the expression wrapper fn. + For example, if the expression is `increment(amount)` then we can specify the amount value + by calling the `localFn` as `localFn({amount: 22})`. + + * `controller` - Controller constructor function. The controller is instantiated before the + pre-linking phase and it is shared with other directives if they request it by name (see + `require` attribute). This allows the directives to communicate with each other and augment + each other's behavior. The controller is injectable with the following locals: + + * `$scope` - Current scope associated with the element + * `$element` - Current element + * `$attrs` - Current attributes object for the element + * `$transclude` - A transclude linking function pre-bound to the correct transclusion scope: + `function(cloneLinkingFn)`. + + * `require` - Require another controller be passed into current directive linking function. The + `require` takes a name of the directive controller to pass in. If no such controller can be + found an error is raised. The name can be prefixed with: + + * `?` - Don't raise an error. This makes the require dependency optional. + * `^` - Look for the controller on parent elements as well. + + + * `restrict` - String of subset of `EACM` which restricts the directive to a specific directive + declaration style. If omitted directives are allowed on attributes only. + + * `E` - Element name: `` + * `A` - Attribute: `
` + * `C` - Class: `
` + * `M` - Comment: `` + + * `template` - replace the current element with the contents of the HTML. The replacement process + migrates all of the attributes / classes from the old element to the new one. See the + {@link guide/directive#Components Creating Components} section below for more information. + + * `templateUrl` - Same as `template` but the template is loaded from the specified URL. Because + the template loading is asynchronous the compilation/linking is suspended until the template + is loaded. + + * `replace` - if set to `true` then the template will replace the current element, rather than + append the template to the element. + + * `transclude` - compile the content of the element and make it available to the directive. + Typically used with {@link api/ng.directive:ngTransclude + ngTransclude}. The advantage of transclusion is that the linking function receives a + transclusion function which is pre-bound to the correct scope. In a typical setup the widget + creates an `isolate` scope, but the transclusion is not a child, but a sibling of the `isolate` + scope. This makes it possible for the widget to have private state, and the transclusion to + be bound to the parent (pre-`isolate`) scope. + + * `true` - transclude the content of the directive. + * `'element'` - transclude the whole element including any directives defined at lower priority. + + + * `compile`: This is the compile function described in the section below. + + * `link`: This is the link function described in the section below. This property is used only + if the `compile` property is not defined. + +## Compile function + +
+  function compile(tElement, tAttrs, transclude) { ... }
+
+ +The compile function deals with transforming the template DOM. Since most directives do not do +template transformation, it is not used often. Examples that require compile functions are +directives that transform template DOM, such as {@link +api/ng.directive:ngRepeat ngRepeat}, or load the contents +asynchronously, such as {@link api/ng.directive:ngView ngView}. The +compile function takes the following arguments. + + * `tElement` - template element - The element where the directive has been declared. It is + safe to do template transformation on the element and child elements only. + + * `tAttrs` - template attributes - Normalized list of attributes declared on this element shared + between all directive compile functions. See {@link + guide/directive#Attributes Attributes}. + + * `transclude` - A transclude linking function: `function(scope, cloneLinkingFn)`. + +NOTE: The template instance and the link instance may not be the same objects if the template has +been cloned. For this reason it is not safe in the compile function to do anything other than DOM +transformation that applies to all DOM clones. Specifically, DOM listener registration should be +done in a linking function rather than in a compile function. + +A compile function can have a return value which can be either a function or an object. + +* returning a function - is equivalent to registering the linking function via the `link` property + of the config object when the compile function is empty. + +* returning an object with function(s) registered via `pre` and `post` properties - allows you to + control when a linking function should be called during the linking phase. See info about + pre-linking and post-linking functions below. + + +## Linking function + +
+  function link(scope, iElement, iAttrs, controller) { ... }
+
+ +The link function is responsible for registering DOM listeners as well as updating the DOM. It is +executed after the template has been cloned. This is where most of the directive logic will be +put. + + * `scope` - {@link api/ng.$rootScope.Scope Scope} - The scope to be used by the + directive for registering {@link api/ng.$rootScope.Scope#$watch watches}. + + * `iElement` - instance element - The element where the directive is to be used. It is safe to + manipulate the children of the element only in `postLink` function since the children have + already been linked. + + * `iAttrs` - instance attributes - Normalized list of attributes declared on this element shared + between all directive linking functions. See {@link + guide/directive#Attributes Attributes}. + + * `controller` - a controller instance - A controller instance if at least one directive on the + element defines a controller. The controller is shared among all the directives, which allows + the directives to use the controllers as a communication channel. + + + +### Pre-linking function + +Executed before the child elements are linked. Not safe to do DOM transformation since the +compiler linking function will fail to locate the correct elements for linking. + +### Post-linking function + +Executed after the child elements are linked. It is safe to do DOM transformation in the post-linking function. + + +## Attributes + +The {@link api/ng.$compile.directive.Attributes Attributes} object - passed as a parameter in the +link() or compile() functions - is a way of accessing: + + * *normalized attribute names:* Since a directive such as 'ngBind' can be expressed in many ways + such as 'ng:bind', or 'x-ng-bind', the attributes object allows for normalized accessed to + the attributes. + + * *directive inter-communication:* All directives share the same instance of the attributes + object which allows the directives to use the attributes object as inter directive + communication. + + * *supports interpolation:* Interpolation attributes are assigned to the attribute object + allowing other directives to read the interpolated value. + + * *observing interpolated attributes:* Use `$observe` to observe the value changes of attributes + that contain interpolation (e.g. `src="{{bar}}"`). Not only is this very efficient but it's also + the only way to easily get the actual value because during the linking phase the interpolation + hasn't been evaluated yet and so the value is at this time set to `undefined`. + +
+function linkingFn(scope, elm, attrs, ctrl) {
+  // get the attribute value
+  console.log(attrs.ngModel);
+
+  // change the attribute
+  attrs.$set('ngModel', 'new value');
+
+  // observe changes to interpolated attribute
+  attrs.$observe('ngModel', function(value) {
+    console.log('ngModel has changed value to ' + value);
+  });
+}
+
+ + +# Understanding Transclusion and Scopes + +It is often desirable to have reusable components. Below is a pseudo code showing how a simplified +dialog component may work. + +
+  
+ + + Body goes here: {{username}} is {{title}}. + +
+
+ +Clicking on the "show" button will open the dialog. The dialog will have a title, which is +data bound to `username`, and it will also have a body which we would like to transclude +into the dialog. + +Here is an example of what the template definition for the `dialog` widget may look like. + +
+  
+

{{title}}

+
+ +
+
+ +This will not render properly, unless we do some scope magic. + +The first issue we have to solve is that the dialog box template expects `title` to be defined, but +the place of instantiation would like to bind to `username`. Furthermore the buttons expect the +`onOk` and `onCancel` functions to be present in the scope. This limits the usefulness of the +widget. To solve the mapping issue we use the `locals` to create local variables which the template +expects as follows: + +
+  scope: {
+    title: '@',             // the title uses the data-binding from the parent scope
+    onOk: '&',              // create a delegate onOk function
+    onCancel: '&',          // create a delegate onCancel function
+    visible: '='            // set up visible to accept data-binding
+  }
+
+ +Creating local properties on widget scope creates two problems: + + 1. isolation - if the user forgets to set `title` attribute of the dialog widget the dialog + template will bind to parent scope property. This is unpredictable and undesirable. + + 2. transclusion - the transcluded DOM can see the widget locals, which may overwrite the + properties which the transclusion needs for data-binding. In our example the `title` + property of the widget clobbers the `title` property of the transclusion. + + +To solve the issue of lack of isolation, the directive declares a new `isolated` scope. An +isolated scope does not prototypically inherit from the child scope, and therefore we don't have +to worry about accidentally clobbering any properties. + +However `isolated` scope creates a new problem: if a transcluded DOM is a child of the widget +isolated scope then it will not be able to bind to anything. For this reason the transcluded scope +is a child of the original scope, before the widget created an isolated scope for its local +variables. This makes the transcluded and widget isolated scope siblings. + +This may seem to be unexpected complexity, but it gives the widget user and developer the least +surprise. + +Therefore the final directive definition looks something like this: + +
+transclude: true,
+scope: {
+    title: '@',             // the title uses the data-binding from the parent scope
+    onOk: '&',              // create a delegate onOk function
+    onCancel: '&',          // create a delegate onCancel function
+    visible: '='            // set up visible to accept data-binding
+},
+restrict: 'E',
+replace: true
+
+ + +# Creating Components + +It is often desirable to replace a single directive with a more complex DOM structure. This +allows the directives to become a short hand for reusable components from which applications +can be built. + +Following is an example of building a reusable widget. + + + + + +
+ Title:
+ Text: +
+
{{text}}
+
+
+ + it('should bind and open / close', function() { + input('title').enter('TITLE'); + input('text').enter('TEXT'); + expect(element('.title').text()).toEqual('Details: TITLE...'); + expect(binding('text')).toEqual('TEXT'); + + expect(element('.zippy').prop('className')).toMatch(/closed/); + element('.zippy > .title').click(); + expect(element('.zippy').prop('className')).toMatch(/opened/); + }); + +
diff --git a/docs/content-ko-back/guide/expression.ngdoc b/docs/content-ko-back/guide/expression.ngdoc new file mode 100644 index 000000000000..59ab35606c6a --- /dev/null +++ b/docs/content-ko-back/guide/expression.ngdoc @@ -0,0 +1,178 @@ +@ngdoc overview +@name Developer Guide: 표현식(Expressions) +@description + +표현식은 `{{ 표현식 }}`처럼 대개 바인딩에 위치 되어지는 자바스크립트와 유사한 코드 조각이며, +{@link api/ng.$parse $parse} 서비스에 의해 처리된다. + +예를 들면, 아래 코드들은 모두 Angular에서 유효한 표현식이다: + + * `1+2` + * `3*10 | currency` + * `user.name` + + +## Angular 표현식 vs. 자바스크립트 표현식 + +Angular의 표현식을 자바스크립트의 표현식처럼 생각하기 쉽지만, Angular는 표현식을 해석하기 위해 +자바스크립트의 `eval()`을 사용하지 않기 때문에 완전히 같지는 않다. Angular의 표현식은 +자바스크립트의 표현식과 다음과 같은 차이점이 있다. + + * **속성의 해석:** 자바스크립트에서는 표현식이 전역 객체인 `window`에 대해서 해석되는 반면 + Angular에서는 모든 프로퍼티를 그 범위에 대해서 해석한다. + + * **관대함:** 표현식의 결과가 undefined나 null일 경우 자바스크립트에서는 'NullPointerExceptions'가 + 발생하지만 Angular에서는 발생하지 않는다. + + * **흐름 제어문이 없음:** Angular의 표현식에는 조건문, 반복문, 또는 예외처리를 사용할 수 없다. + + * **필터:** 표현식의 결과를 필터 체인을 통해 전달할 수 있다. 예를 들면 date 객체를 특정 지역의 + 사람들이 읽을 수 있는 형식으로 변환할 수 있다. + +반면에 임의로 자바스크립트 코드를 실행하고 싶다면, 컨트롤러 메소드를 만들어서 호출해야 한다. +또한 자바스크립트에서 Angular의 표현식을 해석(`eval()`)하고 싶다면, {@link api/ng.$rootScope.Scope#$eval `$eval()`} 메소드를 사용한다. + +## 예제 + + + 1+2={{1+2}} + + + it('should calculate expression in binding', function() { + expect(binding('1+2')).toEqual('3'); + }); + + + +여기에서 다른 표현식들을 해석해 볼 수 있다: + + + + +
+ Expression: + + +
    +
  • + [ X ] + {{expr}} => +
  • +
+
+
+ + it('should allow user expression testing', function() { + element('.expressions :button').click(); + var li = using('.expressions ul').repeater('li'); + expect(li.count()).toBe(1); + expect(li.row(0)).toEqual(["3*10|currency", "$30.00"]); + }); + +
+ + +# 프로퍼티의 해석 + +모든 프로퍼티의 해석은 한 범위 내에서 이루어진다. 자바스크립트에서는 전역 객체가 기본적으로 +window가 되지만, Angular의 표현식에서는 전역 객체인 `window`를 참조하려면 {@link api/ng.$window +`$window`}를 사용해야만 한다. 예를 들어, `window`에 정의된 `alert()`를 호출하고 싶을 경우에는 표현식에서 +`$window.alert()`를 사용한다. 이것은 의도적인 것으로 실수로 전역 상태에 접근하는 것을 방지하기 위함이다 +(일반적인 소스상의 미묘한 버그들). + + + + +
+ Name: + +
+
+ + it('should calculate expression in binding', function() { + var alertText; + this.addFutureAction('set mock', function($window, $document, done) { + $window.mockWindow = { + alert: function(text){ alertText = text; } + }; + done(); + }); + element(':button:contains(Greet)').click(); + expect(this.addFuture('alert text', function(done) { + done(null, alertText); + })).toBe('Hello World'); + }); + +
+ +## 관대함 + +표현식의 결과가 undefined나 null일 경우에 관대하게 처리된다. 자바스크립트에서는 `a.b.c`를 해석할 때 +`a`가 객체가 아닌 경우에는 예외로 처리한다. 범용 언어의 경우라면 적절하겠지만 표현식은 아래와 같이 보이는 +데이터 바인딩을 위해 주로 사용된다. + + {{a.b.c}} + +만약 `a`가 undefined라면 예외로 처리하는 것보다는 아무것도 보여주지 않는 것이 더 적절하다(아마 +우리는 서버의 응답을 기다릴 것이고 그것은 곧 정의가 될 것이다). 만약 표현식을 관대하게 해석하지 않는다면 +다음 예와 같은 혼란스러운 코드로 바인딩을 작성해야만 한다: `{{((a||{}).b||{}).c}}` + +마찬가지로 undefined나 null인 상태에서 `a.b.c()` 함수를 호출하면 간단히 undefined를 반환한다. + + +## 흐름 제어문이 없음 + +Angular의 표현식에서는 흐름 제어문을 사용할 수 없다. 그 이면에 숨겨진 이유는 어플리케이션의 로직은 +뷰가 아닌 컨트롤러에 있어야 한다는 Angular가 가지고 있는 철학의 핵심 때문이다. 만약 뷰의 표현식에 +조건문, 반복문, 또는 예외처리가 필요하다면 대신에 자바스크립트의 메소드에 위임한다. + + +## 필터 + +사용자에게 데이터를 보여줄 때는 로우 포맷에서 사용자 친화적인 포맷으로 데이터를 변환할 필요가 있다. +예를 들어 데이터 객체는 사용자에게 보여지기 전에 그 지역에 맞는 포맷으로 바꿔져야 할 것이다. +다음과 같이 필터의 체인을 통해 표현식을 넘겨줄 수 있다. + + name | uppercase + +위 표현식은 간단하게 name의 값을 {@link api/ng.filter:uppercase `uppercase`} 필터에 전달한다. + +다음과 같은 구문을 사용해서 필터를 연결한다: + + value | filter1 | filter2 + +콜론을 구분자로 사용해서 필터에 인자도 전달할 수 있다. 다음 예는 숫자 123을 소수점 이하 두자리로 +보여주는 것이다. + + 123 | number:2 + +# The $ + +아마 $ 접두어가 무엇을 의미하는지 궁금할지도 모른다. $는 단순히 다른 API 이름과 Angular API 이름을 +구분하기 위한 Angular가 사용하는 접두어일 뿐이다. 만약 Angular가 $를 사용하지 않았다면 `a.length()`는 +a나 Angular가 그런 프로퍼티를 정의하지 않았기 때문에 undefined를 반환할 것이다. + +표현식의 동작을 변경해야 하는 경우 Angular의 향후 버전에서 length 메소드가 추가되는 경우를 고려해 보자. +설상가상으로 개발자인 당신이 직접 length 프로퍼티를 만들게 되면 충돌이 발생할 것이다. 이러한 문제는 +Angular가 추가하는 동작으로 기존 객체를 확장시키기 때문에 발생한다. $가 붙은 접두어로 네임스페이스를 +확보함으로써 Angular 개발자와 Angular를 사용하는 개발자간에 충돌 없이 조화롭게 개발할 수 있는 것이다. diff --git a/docs/content-ko-back/guide/forms.ngdoc b/docs/content-ko-back/guide/forms.ngdoc new file mode 100644 index 000000000000..3d09346796a8 --- /dev/null +++ b/docs/content-ko-back/guide/forms.ngdoc @@ -0,0 +1,324 @@ +@ngdoc overview +@name Forms +@description + +Controls (`input`, `select`, `textarea`) are a way for user to enter data. +Form is a collection of controls for the purpose of grouping related controls together. + +Form and controls provide validation services, so that the user can be notified of invalid input. +This provides a better user experience, because the user gets instant feedback on how to correct the error. +Keep in mind that while client-side validation plays an important role in providing good user experience, it can easily be circumvented and thus can not be trusted. +Server-side validation is still necessary for a secure application. + + +# Simple form +The key directive in understanding two-way data-binding is {@link api/ng.directive:ngModel ngModel}. +The `ngModel` directive provides the two-way data-binding by synchronizing the model to the view, as well as view to the model. +In addition it provides an {@link api/ng.directive:ngModel.NgModelController API} for other directives to augment its behavior. + + + +
+
+ Name:
+ E-mail:
+ Gender: male + female
+ + +
+
form = {{user | json}}
+
master = {{master | json}}
+
+ + +
+
+ + +Note that `novalidate` is used to disable browser's native form validation. + + + +# Using CSS classes + +To allow styling of form as well as controls, `ngModel` add these CSS classes: + +- `ng-valid` +- `ng-invalid` +- `ng-pristine` +- `ng-dirty` + +The following example uses the CSS to display validity of each form control. +In the example both `user.name` and `user.email` are required, but are rendered with red background only when they are dirty. +This ensures that the user is not distracted with an error until after interacting with the control, and failing to satisfy its validity. + + + +
+
+ Name: +
+ E-mail:
+ Gender: male + female
+ + +
+
+ + + + +
+
+ + + +# Binding to form and control state + +A form is in instance of {@link api/ng.directive:form.FormController FormController}. +The form instance can optionally be published into the scope using the `name` attribute. +Similarly control is an instance of {@link api/ng.directive:ngModel.NgModelController NgModelController}. +The control instance can similarly be published into the form instance using the `name` attribute. +This implies that the internal state of both the form and the control is available for binding in the view using the standard binding primitives. + +This allows us to extend the above example with these features: + +- RESET button is enabled only if form has some changes +- SAVE button is enabled only if form has some changes and is valid +- custom error messages for `user.email` and `user.agree` + + + +
+
+ Name: +
+ E-mail: +
+
Invalid: + Tell us your email. + This is not a valid email. +
+ + Gender: male + female
+ + + I agree:
+
Please agree and sign.
+ + + +
+
+ + +
+
+ + + +# Custom Validation + +Angular provides basic implementation for most common html5 {@link api/ng.directive:input input} +types: ({@link api/ng.directive:input.text text}, {@link api/ng.directive:input.number number}, {@link api/ng.directive:input.url url}, {@link api/ng.directive:input.email email}, {@link api/ng.directive:input.radio radio}, {@link api/ng.directive:input.checkbox checkbox}), as well as some directives for validation (`required`, `pattern`, `minlength`, `maxlength`, `min`, `max`). + +Defining your own validator can be done by defining your own directive which adds a custom validation function to the `ngModel` {@link api/ng.directive:ngModel.NgModelController controller}. +To get a hold of the controller the directive specifies a dependency as shown in the example below. +The validation can occur in two places: + + * **Model to View update** - + Whenever the bound model changes, all functions in {@link api/ng.directive:ngModel.NgModelController#$formatters NgModelController#$formatters} array are pipe-lined, so that each of these functions has an opportunity to format the value and change validity state of the form control through {@link api/ng.directive:ngModel.NgModelController#$setValidity NgModelController#$setValidity}. + + * **View to Model update** - + In a similar way, whenever a user interacts with a control it calls {@link api/ng.directive:ngModel.NgModelController#$setViewValue NgModelController#$setViewValue}. +This in turn pipelines all functions in the {@link api/ng.directive:ngModel.NgModelController#$parsers NgModelController#$parsers} array, so that each of these functions has an opportunity to convert the value and change validity state of the form control through {@link api/ng.directive:ngModel.NgModelController#$setValidity NgModelController#$setValidity}. + +In the following example we create two directives. + + * The first one is `integer` and it validates whether the input is a valid integer. + For example `1.23` is an invalid value, since it contains a fraction. + Note that we unshift the array instead of pushing. + This is because we want to be first parser and consume the control string value, as we need to execute the validation function before a conversion to number occurs. + + * The second directive is a `smart-float`. + It parses both `1.2` and `1,2` into a valid float number `1.2`. + Note that we can't use input type `number` here as HTML5 browsers would not allow the user to type what it would consider an invalid number such as `1,2`. + + + + +
+
+
+ Size (integer 0 - 10): + {{size}}
+ This is not valid integer! + + The value must be in range 0 to 10! +
+ +
+ Length (float): + + {{length}}
+ + This is not a valid float number! +
+
+
+ + +
+
+ + +# Implementing custom form controls (using `ngModel`) +Angular implements all of the basic HTML form controls ({@link api/ng.directive:input input}, {@link api/ng.directive:select select}, {@link api/ng.directive:textarea textarea}), which should be sufficient for most cases. +However, if you need more flexibility, you can write your own form control as a directive. + +In order for custom control to work with `ngModel` and to achieve two-way data-binding it needs to: + + - implement `$render` method, which is responsible for rendering the data after it passed the {@link api/ng.directive:ngModel.NgModelController#$formatters NgModelController#$formatters}, + - call `$setViewValue` method, whenever the user interacts with the control and model needs to be updated. This is usually done inside a DOM Event listener. + +See {@link guide/directive $compileProvider.directive} for more info. + +The following example shows how to add two-way data-binding to contentEditable elements. + + + + + +
Some
+
model = {{content}}
+ + +
+
diff --git a/docs/content-ko-back/guide/i18n.ngdoc b/docs/content-ko-back/guide/i18n.ngdoc new file mode 100644 index 000000000000..946f16c071ea --- /dev/null +++ b/docs/content-ko-back/guide/i18n.ngdoc @@ -0,0 +1,124 @@ +@ngdoc overview +@name Developer Guide: i18n and l10n +@description + +# I18n and L10n in AngularJS + +**What is i18n and l10n?** + +Internationalization, abbreviated i18n, is the process of developing products in such a way that +they can be localized for languages and cultures easily. Localization, abbreviated l10n, is the +process of adapting applications and text to enable their usability in a particular cultural or +linguistic market. For application developers, internationalizing an application means abstracting +all of the strings and other locale-specific bits (such as date or currency formats) out of the +application. Localizing an application means providing translations and localized formats for the +abstracted bits. + +**What level of support for i18n/l10n is currently in Angular?** + +Currently, Angular supports i18n/l10n for {@link +http://docs.angularjs.org/#!/api/ng.filter:date datetime}, {@link +http://docs.angularjs.org/#!/api/ng.filter:number number} and {@link +http://docs.angularjs.org/#!/api/ng.filter:currency currency} filters. + +Additionally, Angular supports localizable pluralization support provided by the {@link +api/ng.directive:ngPluralize ngPluralize directive}. + +All localizable Angular components depend on locale-specific rule sets managed by the {@link +api/ng.$locale $locale service}. + +For readers who want to jump straight into examples, we have a few web pages that showcase how to +use Angular filters with various locale rule sets. You can find these examples either on {@link +https://github.com/angular/angular.js/tree/master/i18n/e2e Github} or in the i18n/e2e folder of +Angular development package. + +**What is a locale id?** + +A locale is a specific geographical, political, or cultural region. The most commonly used locale +ID consists of two parts: language code and country code. For example, en-US, en-AU, zh-CN are all +valid locale IDs that have both language codes and country codes. Because specifying a country code +in locale ID is optional, locale IDs such as en, zh, and sk are also valid. See the {@link +http://userguide.icu-project.org/locale ICU } website for more information about using locale IDs. + +**Supported locales in Angular** +Angular separates number and datetime format rule sets into different files, each file for a +particular locale. You can find a list of currently supported locales {@link +https://github.com/angular/angular.js/tree/master/i18n/locale here} +# Providing locale rules to Angular + +There are two approaches to providing locale rules to Angular: + +**1. Pre-bundled rule sets** + +You can pre-bundle the desired locale file with Angular by concatenating the content of the +locale-specific file to the end of `angular.js` or `angular.min.js` file. + +For example on *nix, to create a an angular.js file that contains localization rules for german +locale, you can do the following: + +`cat angular.js i18n/angular-locale_de-ge.js > angular_de-ge.js` + +When the application containing `angular_de-ge.js` script instead of the generic angular.js script +starts, Angular is automatically pre-configured with localization rules for the german locale. + +**2. Including locale js script in index.html page** + +You can also include the locale specific js file in the index.html page. For example, if one client +requires German locale, you would serve index_de-ge.html which will look something like this: + +
+
+ 
+….
+   
+   
+….
+ 
+
+
+ +**Comparison of the two approaches** +Both approaches described above requires you to prepare different index.html pages or js files for +each locale that your app may be localized into. You also need to configure your server to serve +the correct file that correspond to the desired locale. + +However, the second approach (Including locale js script in index.html page) is likely to be slower +because an extra script needs to be loaded. + + +# "Gotchas" + +**Currency symbol "gotcha"** + +Angular's {@link http://docs.angularjs.org/#!/api/ng.filter:currency currency filter} allows +you to use the default currency symbol from the {@link api/ng.$locale locale service}, +or you can provide the filter with a custom currency symbol. If your app will be used only in one +locale, it is fine to rely on the default currency symbol. However, if you anticipate that viewers +in other locales might use your app, you should provide your own currency symbol to make sure the +actual value is understood. + +For example, if you want to display account balance of 1000 dollars with the following binding +containing currency filter: `{{ 1000 | currency }}`, and your app is currently in en-US locale. +'$1000.00' will be shown. However, if someone in a different local (say, Japan) views your app, her +browser will specify the locale as ja, and the balance of '¥1000.00' will be shown instead. This +will really upset your client. + +In this case, you need to override the default currency symbol by providing the {@link +http://docs.angularjs.org/#!/api/ng.filter:currency currency filter} with a currency symbol as +a parameter when you configure the filter, for example, {{ 1000 | currency:"USD$"}}. This way, +Angular will always show a balance of 'USD$1000' and disregard any locale changes. + +**Translation length "gotcha"** + +Keep in mind that translated strings/datetime formats can vary greatly in length. For example, +`June 3, 1977` will be translated to Spanish as `3 de junio de 1977`. There are bound to be other +more extreme cases. Hence, when internationalizing your apps, you need to apply CSS rules +accordingly and do thorough testing to make sure UI components do not overlap. + + +**Timezones** + +Keep in mind that Angular datetime filter uses the time zone settings of the browser. So the same +application will show different time information depending on the time zone settings of the +computer that the application is running on. Neither Javascript nor Angular currently supports +displaying the date with a timezone specified by the developer. diff --git a/docs/content-ko-back/guide/ie.ngdoc b/docs/content-ko-back/guide/ie.ngdoc new file mode 100644 index 000000000000..24d133a706dc --- /dev/null +++ b/docs/content-ko-back/guide/ie.ngdoc @@ -0,0 +1,147 @@ +@ngdoc overview +@name 개발자 가이드: Internet Explorer 호환성 +@description + +# 개요 + +이 문서는 사용자정의 속성과 태그를 처리할 때 Internet Explorer(이하 IE)의 고유한 특성에 대해 설명합니다. IE8이나 이하 버전에서 Angular 애플리케이션을 사용할 계획이라면 이 문서를 읽어주시기 바랍니다. + +# 짧은 버전 + +Angular 어플리케이션을 IE에서 동작하게 하기 위해 다음을 확인해주시기 바랍니다: + + 1. 필요하다면 JSON.stringify를 polyfill 해야합니다. [JSON2](https://github.com/douglascrockford/JSON-js)이나 [JSON3](http://bestiejs.github.com/json3/)로 polyfill 할 수 있습니다. + + 2. ``같은 사용자정의 태그들을 사용하면 **안 됩니다**(대신 속성을 이용해서 `
`와 같이 사용하세요). + + 3. 사용자정의 태그들을 사용해야 한다면, 반드시 아래와 같이 작성해야 합니다. + +
+  
+    
+      
+    
+    
+      ...
+    
+  
+
+ +**중요한** 부분은: + + * `xmlns:ng` - *네임스페이스* - 사용하기로 한 각 사용자정의 태그마다 하나의 네임스페이스가 필요합니다. + + * `document.createElement(태그이름)` - *사용자정의 태그이름의 생성* - 이것은 구 버전 IE에서만의 이슈이기 때문에 이 부분을 조건적으로 사용해야 합니다. 각 태그가 네임스페이스를 가지고 있지 않거나 HTML에 정의되어 있지 않을 때 미리 선언해야 합니다. + + +# 긴 버전 + +IE에서는 표준 HTML 태그 이름이 아닌 태그 이름을 사용하는데에 문제가 있습니다. 이 문제는 두 분류로 나누어 지는데 각 분류마다 해결 방안이 있습니다. + + * 태그 이름이 `my:`라는 접두사로 시작한다면 이것은 XML 네임스페이스를 고려한 것이고, ``의 선언과 같은 네임스페이스의 선언이 있어야 합니다. + + * 태그가 `:`를 가지고 있지 않지만 표준 HTML 태그가 아니라면 `document.createElement('my-tag')`를 사용하여 미리 선언해야 합니다. + + * CSS 셀렉터를 이용하여 사용자정의 태그에 스타일을 적용할 계획이라면 XML 네임스페이스에 관계없이 `document.createElement('my-tag')`를 사용하여 꼭 미리 선언해야 합니다. + + +## 좋은 소식 + +좋은 소식은 이런 제약조건들이 엘리먼트 태그이름에만 적용되고 엘리먼트 속성이름에는 적용되지 않는다는 것입니다. 따라서 IE에서 이런 특별한 처리가 필요하지 않습니다: `
`. + + +## 이것을 하지 않으면 무슨 일이 일어날까요? + +`mytag`라는 정의 되지 않은 태그를 사용한다고 하면(`my:tag`나 `my-tag`를 사용해도 결과는 같습니다): + +
+  
+    
+      some text
+    
+  
+
+ +이것은 아래의 DOM과 같이 분석되어야 합니다. + +
+#document
+  +- HTML
+     +- BODY
+        +- mytag
+           +- #text: some text
+
+ +`BODY`엘리먼트가 `mytag`라는 자식 엘리먼트를 가지고 다음에는 `some text`라는 문자를 가질 것이라 예상했을 것입니다. + +하지만 IE에서는(위의 수정사항들이 포함되어 있지 않은 경우): + +
+#document
+  +- HTML
+     +- BODY
+        +- mytag
+        +- #text: some text
+        +- /mytag
+
+ +IE에서는 `BODY`엘리먼트가 세 개의 자식을 가질 것입니다. + + 1. 셀프클로징 `mytag`. 셀프클로징의 예로 `
`을 들 수 있습니다. 뒤에 따르는 `/`는 선택사항이고 `
some text
`는 `some text`를 자식으로 두는 `
`이 아닌 세 개의 형제로 브라우저는 여길 것입니다.(`
`태그는 어떠한 자식도 허용하지 않습니다) + + 2. 텍스트 노드 `some text`. 이것은 위 `mytag`의 형제가 아닌 자식이 되었어야 합니다. + + 3. 잘못된 셀프클로징 `/mytag`. 게다가 이 닫힌 엘리먼트는 DOM의 구조만 나타냈기 때문에 DOM의 일부가 되지 않습니다. + + +## 사용자정의 태그이름의 CSS 스타일링 + +사용자정의 엘리먼트에 CSS 셀렉터가 동작하게 하기 위해 XML 네임스페이스에 관계없이 사용자정의 태그이름은 `document.createElement('my-tag')`와 같이 미리 선언되어야 합니다. + +
+  
+    
+      
+      
+    
+    
+      
+      
+      ...
+    
+  
+
+ + + diff --git a/docs/content-ko-back/guide/index.ngdoc b/docs/content-ko-back/guide/index.ngdoc new file mode 100644 index 000000000000..d392cf0a9205 --- /dev/null +++ b/docs/content-ko-back/guide/index.ngdoc @@ -0,0 +1,10 @@ +@ngdoc overview +@name 개발자 가이드 +@description + +angular 개발자 문서에 오신것을 환영합니다. angular를 이용하여 웹앱을 개발한 법을 배우기 위해 오셨다면 제대로 찾아 오셨습니다. + +angular를 전혀 모르거나 잘 모르면 아래의 문서들을 확인하고나서 다시 개발자 문서를 보면 좋을 것입니다. + +* {@link misc/started Getting Started} +* {@link tutorial/index Angular Tutorial} diff --git a/docs/content-ko-back/guide/introduction.ngdoc b/docs/content-ko-back/guide/introduction.ngdoc new file mode 100644 index 000000000000..dfd9e21a85ba --- /dev/null +++ b/docs/content-ko-back/guide/introduction.ngdoc @@ -0,0 +1,42 @@ +@ngdoc overview +@name Developer Guide: Introduction +@description + +Angular is pure client-side technology, written entirely in JavaScript. It works with the +long-established technologies of the web (HTML, CSS, and JavaScript) to make the development of +web apps easier and faster than ever before. + +One important way that Angular simplifies web development is by increasing the level of abstraction +between the developer and most low-level web app development tasks. Angular automatically takes +care of many of these tasks, including: + + * DOM Manipulation + * Setting Up Listeners and Notifiers + * Input Validation + +Because Angular handles much of the work involved in these tasks, developers can concentrate more +on application logic and less on repetitive, error-prone, lower-level coding. + +At the same time that Angular simplifies the development of web apps, it brings relatively +sophisticated techniques to the client-side, including: + + * Separation of data, application logic, and presentation components + * Data Binding between data and presentation components + * Services (common web app operations, implemented as substitutable objects) + * Dependency Injection (used primarily for wiring together services) + * An extensible HTML compiler (written entirely in JavaScript) + * Ease of Testing + +These techniques have been for the most part absent from the client-side for far too long. + +## Single-page / Round-trip Applications + +You can use Angular to develop both single-page and round-trip apps, but Angular is designed +primarily for developing single-page apps. Angular supports browser history, forward and back +buttons, and bookmarking in single-page apps. + +You normally wouldn't want to load Angular with every page change, as would be the case with using +Angular in a round-trip app. However, it would make sense to do so if you were adding a subset of +Angular's features (for example, templates to leverage angular's data-binding feature) to an +existing round-trip app. You might follow this course of action if you were migrating an older app +to a single-page Angular app. diff --git a/docs/content-ko-back/guide/module.ngdoc b/docs/content-ko-back/guide/module.ngdoc new file mode 100644 index 000000000000..a157daf8833c --- /dev/null +++ b/docs/content-ko-back/guide/module.ngdoc @@ -0,0 +1,257 @@ +@ngdoc overview +@name Developer Guide: Modules +@description + +# What is a Module? + +Most applications have a main method which instantiates, wires, and bootstraps the application. +Angular apps don't have a main method. Instead modules declaratively specify how an application +should be bootstrapped. There are several advantages to this approach: + + * The process is more declarative which is easier to understand + * In unit-testing there is no need to load all modules, which may aid in writing unit-tests. + * Additional modules can be loaded in scenario tests, which can override some of the + configuration and help end-to-end test the application + * Third party code can be packaged as reusable modules. + * The modules can be loaded in any/parallel order (due to delayed nature of module execution). + + +# The Basics + +Ok, I'm in a hurry. How do I get a Hello World module working? + +Important things to notice: + + * {@link api/angular.Module Module} API + * Notice the reference to the `myApp` module in the ``, it is what + bootstraps the app using your module. + + + + +
+ {{ 'World' | greet }} +
+
+
+ + + +# Recommended Setup + +While the example above is simple, it will not scale to large applications. Instead we recommend +that you break your application to multiple modules like this: + + * A service module, for service declaration + * A directive module, for directive declaration + * A filter module, for filter declaration + * And an application level module which depends on the above modules, and which has + initialization code. + +The reason for this breakup is that in your tests, it is often necessary to ignore the +initialization code, which tends to be difficult to test. By putting it into a separate module it +can be easily ignored in tests. The tests can also be more focused by only loading the modules +that are relevant to tests. + +The above is only a suggestion, so feel free to tailor it to your needs. + + + + +
+ {{ greeting }}! +
+
+
+ + + +# Module Loading & Dependencies + +A module is a collection of configuration and run blocks which get applied to the application +during the bootstrap process. In its simplest form the module consist of collection of two kinds +of blocks: + + 1. **Configuration blocks** - get executed during the provider registrations and configuration + phase. Only providers and constants can be injected into configuration blocks. This is to + prevent accidental instantiation of services before they have been fully configured. + 2. **Run blocks** - get executed after the injector is created and are used to kickstart the + application. Only instances and constants can be injected into run blocks. This is to prevent + further system configuration during application run time. + +
+angular.module('myModule', []).
+  config(function(injectables) { // provider-injector
+    // This is an example of config block.
+    // You can have as many of these as you want.
+    // You can only inject Providers (not instances)
+    // into the config blocks.
+  }).
+  run(function(injectables) { // instance-injector
+    // This is an example of a run block.
+    // You can have as many of these as you want.
+    // You can only inject instances (not Providers)
+    // into the run blocks
+  });
+
+ +## Configuration Blocks + +There are some convenience methods on the module which are equivalent to the config block. For +example: + +
+angular.module('myModule', []).
+  value('a', 123).
+  factory('a', function() { return 123; }).
+  directive('directiveName', ...).
+  filter('filterName', ...);
+
+// is same as
+
+angular.module('myModule', []).
+  config(function($provide, $compileProvider, $filterProvider) {
+    $provide.value('a', 123);
+    $provide.factory('a', function() { return 123; });
+    $compileProvider.directive('directiveName', ...);
+    $filterProvider.register('filterName', ...);
+  });
+
+ +The configuration blocks get applied in the order in which they are registered. The only exception +to it are constant definitions, which are placed at the beginning of all configuration blocks. + +## Run Blocks + +Run blocks are the closest thing in Angular to the main method. A run block is the code which +needs to run to kickstart the application. It is executed after all of the service have been +configured and the injector has been created. Run blocks typically contain code which is hard +to unit-test, and for this reason should be declared in isolated modules, so that they can be +ignored in the unit-tests. + +## Dependencies + +Modules can list other modules as their dependencies. Depending on a module implies that required +module needs to be loaded before the requiring module is loaded. In other words the configuration +blocks of the required modules execute before the configuration blocks or the requiring module. +The same is true for the run blocks. Each module can only be loaded once, even if multiple other +modules require it. + +## Asynchronous Loading + +Modules are a way of managing $injector configuration, and have nothing to do with loading of +scripts into a VM. There are existing projects which deal with script loading, which may be used +with Angular. Because modules do nothing at load time they can be loaded into the VM in any order +and thus script loaders can take advantage of this property and parallelize the loading process. + + +# Unit Testing + +In its simplest form a unit test is a way of instantiating a subset of the application in test and +then applying a stimulus to it. It is important to realize that each module can only be loaded +once per injector. Typically an app has only one injector. But in tests, each test has its own +injector, which means that the modules are loaded multiple times per VM. Properly structured +modules can help with unit testing, as in this example: + +In all of these examples we are going to assume this module definition: +
+  angular.module('greetMod', []).
+
+    factory('alert', function($window) {
+      return function(text) {
+        $window.alert(text);
+      }
+    }).
+
+    value('salutation', 'Hello').
+
+    factory('greet', function(alert, salutation) {
+      return function(name) {
+        alert(salutation + ' ' + name + '!');
+      }
+    });
+
+ +Let's write some tests: +
+describe('myApp', function() {
+  // load the relevant application modules then load a special
+  // test module which overrides the $window with a mock version,
+  // so that calling window.alert() will not block the test
+  // runner with a real alert box. This is an example of overriding
+  // configuration information in tests.
+  beforeEach(module('greetMod', function($provide) {
+    $provide.value('$window', {
+      alert: jasmine.createSpy('alert')
+    });
+  }));
+
+  // The inject() will create the injector and inject the greet and
+  // $window into the tests. The test need not concern itself with
+  // wiring of the application, only with testing it.
+  it('should alert on $window', inject(function(greet, $window) {
+    greet('World');
+    expect($window.alert).toHaveBeenCalledWith('Hello World!');
+  }));
+
+  // this is another way of overriding configuration in the
+  // tests using an inline module and inject methods.
+  it('should alert using the alert service', function() {
+    var alertSpy = jasmine.createSpy('alert');
+    module(function($provide) {
+      $provide.value('alert', alertSpy);
+    });
+    inject(function(greet) {
+      greet('World');
+      expect(alertSpy).toHaveBeenCalledWith('Hello World!');
+    });
+  });
+});
+
diff --git a/docs/content-ko-back/guide/overview.ngdoc b/docs/content-ko-back/guide/overview.ngdoc new file mode 100644 index 000000000000..6dc3b2b31074 --- /dev/null +++ b/docs/content-ko-back/guide/overview.ngdoc @@ -0,0 +1,207 @@ +@ngdoc overview +@name Developer Guide: Overview +@description + + +# What Is Angular? + +AngularJS is a structural framework for dynamic web apps. It lets you use HTML as your template +language and lets you extend HTML's syntax to express your application's components clearly and +succinctly. Out of the box, it eliminates much of the code you currently write through data +binding and dependency injection. And it all happens in JavaScript within the browser making it an +ideal partner with any server technology. + +Angular is what HTML would have been had it been designed for applications. HTML is a great +declarative language for static documents. It does not contain much in the way of creating +applications, and as a result building web applications is an exercise in *what do I have to do, so +that I trick the browser in to doing what I want.* + +The impedance mismatch between dynamic applications and static documents is often solved as: + + * **library** - a collection of functions which are useful when writing web apps. Your code is + in charge and it calls into the library when it sees fit. E.g., `jQuery`. + * **frameworks** - a particular implementation of a web application, where your code fills in + the details. The framework is in charge and it calls into your code when it needs something + app specific. E.g., `knockout`, `sproutcore`, etc. + + +Angular takes another approach. It attempts to minimize the impedance mismatch between document +centric HTML and what an application needs by creating new HTML constructs. Angular teaches the +browser new syntax through a construct we call directives. Examples include: + + * Data binding as in `{{}}`. + * DOM control structures for repeating/hiding DOM fragments. + * Support for forms and form validation. + * Attaching code-behind to DOM elements. + * Grouping of HTML into reusable components. + + + +## End-to-end solution + +Angular tries to be an end-to-end solution, when building a web application. This means it is +not a single piece in an overall puzzle of building a web application, but an end-to-end solution. +This makes Angular opinionated about how a CRUD application should be built. But while it is +opinionated, it also tries to make sure that its opinion is just a starting point, which you can +easily change. Angular comes with the following out-of-the-box: + + * Everything you need to build a CRUD app in a cohesive set: data-binding, basic templating + directives, form validation, routing, deep-linking, reusable components, dependency injection. + * Testability story: unit-testing, end-to-end testing, mocks, test harnesses. + * Seed application with directory layout and test scripts as a starting point. + + +## Angular Sweet Spot + +Angular simplifies application development by presenting a higher level of abstraction to the +developer. Like any abstraction, it comes at a cost of flexibility. In other words not every app +is a good fit for Angular. Angular was built for the CRUD application in mind. Luckily CRUD +applications represent at least 90% of the web applications. But to understand what Angular is +good at one also has to understand when an app is not a good fit for Angular. + +Games, and GUI editors are examples of very intensive and tricky DOM manipulation. These kinds of +apps are different from CRUD apps, and as a result are not a good fit for Angular. In these cases +using something closer to bare metal such as `jQuery` may be a better fit. + + +# An Introductory Angular Example + +Below is a typical CRUD application which contains a form. The form values are validated, and +are used to compute the total, which is formatted to a particular locale. These are some common +concepts which the application developer may face: + + * attaching data-model to the UI. + * writing, reading and validating user input. + * computing new values based on the model. + * formatting output in a user specific locale. + + + + function InvoiceCntl($scope) { + $scope.qty = 1; + $scope.cost = 19.95; + } + + +
+ Invoice: +
+
+ + + + + + +
QuantityCost
+
+ Total: {{qty * cost | currency}} +
+
+ + it('should show of angular binding', function() { + expect(binding('qty * cost')).toEqual('$19.95'); + input('qty').enter('2'); + input('cost').enter('5.00'); + expect(binding('qty * cost')).toEqual('$10.00'); + }); + +
+ +Try out the Live Preview above, and then let's walk through the example and describe what's going +on. + +In the `` tag, we specify that it is an Angular +application with the `ng-app` directive. The `ng-app` will cause Angular to {@link +bootstrap auto initialize} your application. + + + +We load Angular using the ` + +From the `ng-model` attribute of the `` tags, Angular automatically sets up two-way data +binding, and we also demonstrate some easy input validation: + + Quantity: + Cost: + +These input widgets look normal enough, but consider these points: + + * When this page loaded, Angular bound the names of the input widgets (`qty` and `cost`) to + variables of the same name. Think of those variables as the "Model" component of the + Model-View-Controller design pattern. + * Note that the HTML widget {@link api/ng.directive:input input} + has special powers. The input invalidates itself by turning red when you enter invalid data or + leave the the input fields blank. These new widget behaviors make it easier to implement field + validation common in CRUD applications. + +And finally, the mysterious `{{ double curly braces }}`: + + Total: {{qty * cost | currency}} + +This notation, `{{ _expression_ }}`, is Angular markup for data-binding. The expression itself can +be a combination of both an expression and a {@link dev_guide.templates.filters filter}: `{{ +expression | filter }}`. Angular provides filters for formatting display data. + +In the example above, the expression in double-curly braces directs Angular to "bind the data we +got from the input widgets to the display, multiply them together, and format the resulting number +into output that looks like money." + +Notice that we achieved this application behavior not by calling Angular methods, nor by +implementing application specific behavior as a framework. We achieved the behavior because the +browser behaved more in line with what is needed for a dynamic web application rather then what is +needed for a static document. Angular has lowered the impedance mismatch to the point where no +library/framework calls are needed. + + +# The Zen of Angular + +Angular is built around the belief that declarative code is better than imperative when it comes +to building UIs and wiring software components together, while imperative code is excellent for +expressing business logic. + + + * It is a very good idea to decouple DOM manipulation from app logic. This dramatically improves + the testability of the code. + * It is a really, _really_ good idea to regard app testing as equal in importance to app + writing. Testing difficulty is dramatically affected by the way the code is structured. + * It is an excellent idea to decouple the client side of an app from the server side. This + allows development work to progress in parallel, and allows for reuse of both sides. + * It is very helpful indeed if the framework guides developers through the entire journey of + building an app: from designing the UI, through writing the business logic, to testing. + * It is always good to make common tasks trivial and difficult tasks possible. + + + +Angular frees you from the following pain: + + * **Registering callbacks:** Registering callbacks clutters your code, making it hard to see the + forest for the trees. Removing common boilerplate code such as callbacks is a good thing. It + vastly reduces the amount of JavaScript coding _you_ have to do, and it makes it easier to see + what your application does. + * **Manipulating HTML DOM programmatically:** Manipulating HTML DOM is a cornerstone of AJAX + applications, but it's cumbersome and error-prone. By declaratively describing how the UI + should change as your application state changes, you are freed from low level DOM manipulation + tasks. Most applications written with Angular never have to programmatically manipulate the + DOM, although you can if you want to. + * **Marshaling data to and from the UI:** CRUD operations make up the majority of AJAX + applications. The flow of marshaling data from the server to an internal object to an HTML + form, allowing users to modify the form, validating the form, displaying validation errors, + returning to an internal model, and then back to the server, creates a lot of boilerplate + code. Angular eliminates almost all of this boilerplate, leaving code that describes the + overall flow of the application rather than all of the implementation details. + * **Writing tons of initialization code just to get started:** Typically you need to write a lot + of plumbing just to get a basic "Hello World" AJAX app working. With Angular you can bootstrap + your app easily using services, which are auto-injected into your application in a {@link + http://code.google.com/p/google-guice/ Guice}-like dependency-injection style. This allows you + to get started developing features quickly. As a bonus, you get full control over the + initialization process in automated tests. + + +# Watch a Presentation About Angular + +Here is a presentation on Angular from May 2012. + + diff --git a/docs/content-ko-back/guide/scope.ngdoc b/docs/content-ko-back/guide/scope.ngdoc new file mode 100644 index 000000000000..b2dd5e533009 --- /dev/null +++ b/docs/content-ko-back/guide/scope.ngdoc @@ -0,0 +1,331 @@ +@ngdoc overview +@name Developer Guide: Scopes +@description + +# What are Scopes? + +{@link api/ng.$rootScope.Scope scope} is an object that refers to the application +model. It is an execution context for {@link expression expressions}. Scopes are +arranged in hierarchical structure which mimic the DOM structure of the application. Scopes can +watch {@link guide/expression expressions} and propagate events. + +## Scope characteristics + + - Scopes provide APIs ({@link api/ng.$rootScope.Scope#$watch $watch}) to observe + model mutations. + + - Scopes provide APIs ({@link api/ng.$rootScope.Scope#$apply $apply}) to + propagate any model changes through the system into the view from outside of the "Angular + realm" (controllers, services, Angular event handlers). + + - Scopes can be nested to isolate application components while providing access to shared model + properties. A scope (prototypically) inherits properties from its parent scope. + + - Scopes provide context against which {@link guide/expression expressions} are evaluated. For + example `{{username}}` expression is meaningless, unless it is evaluated against a specific + scope which defines the `username` property. + +## Scope as Data-Model + +Scope is the glue between application controller and the view. During the template {@link compiler +linking} phase the {@link api/ng.$compileProvider#directive directives} set up +{@link api/ng.$rootScope.Scope#$watch `$watch`} expressions on the scope. The +`$watch` allows the directives to be notified of property changes, which allows the directive to +render the updated value to the DOM. + +Both controllers and directives have reference to the scope, but not to each other. This +arrangement isolates the controller from the directive as well as from DOM. This is an important +point since it makes the controllers view agnostic, which greatly improves the testing story of +the applications. + + + + function MyController($scope) { + $scope.username = 'World'; + + $scope.sayHello = function() { + $scope.greeting = 'Hello ' + $scope.username + '!'; + }; + } + + +
+ Your name: + + +
+ {{greeting}} +
+
+
+ +In the above example notice that the `MyController` assigns `World` to the `username` property of +the scope. The scope then notifies the `input` of the assignment, which then renders the input +with username pre-filled. This demonstrates how a controller can write data into the scope. + +Similarly the controller can assign behavior to scope as seen by the `sayHello` method, which is +invoked when the user clicks on the 'greet' button. The `sayHello` method can read the `username` +property and create a `greeting` property. This demonstrates that the properties on scope update +automatically when they are bound to HTML input widgets. + +Logically the rendering of `{{greeting}}` involves: + + * retrieval of the scope associated with DOM node where `{{greeting}}` is defined in template. + In this example this is the same scope as the scope which was passed into `MyController`. (We + will discuss scope hierarchies later.) + + * Evaluate the `greeting` {@link guide/expression expression} against the scope retrieved above, + and assign the result to the text of the enclosing DOM element. + + +You can think of the scope and its properties as the data which is used to render the view. The +scope is the single source-of-truth for all things view related. + +From a testability point of view, the separation of the controller and the view is desirable, because it allows us +to test the behavior without being distracted by the rendering details. + +
+  it('should say hello', function() {
+    var scopeMock = {};
+    var cntl = new MyController(scopeMock);
+
+    // Assert that username is pre-filled
+    expect(scopeMock.username).toEqual('World');
+
+    // Assert that we read new username and greet
+    scopeMock.username = 'angular';
+    scopeMock.sayHello();
+    expect(scopeMock.greeting).toEqual('Hello angular!');
+  });
+
+ + +## Scope Hierarchies + +Each Angular application has exactly one {@link api/ng.$rootScope root scope}, but +may have several child scopes. + +The application can have multiple scopes, because some {@link guide/directive directives} create +new child scopes (refer to directive documentation to see which directives create new scopes). +When new scopes are created, they are added as children of their parent scope. This creates a tree +structure which parallels the DOM where they're attached + +When Angular evaluates `{{username}}`, it first looks at the scope associated with the given +element for the `username` property. If no such property is found, it searches the parent scope +and so on until the root scope is reached. In JavaScript this behavior is known as prototypical +inheritance, and child scopes prototypically inherit from their parents. + +This example illustrates scopes in application, and prototypical inheritance of properties. + + + + /* remove .doc-example-live in jsfiddle */ + .doc-example-live .ng-scope { + border: 1px dashed red; + } + + + function EmployeeController($scope) { + $scope.department = 'Engineering'; + $scope.employee = { + name: 'Joe the Manager', + reports: [ + {name: 'John Smith'}, + {name: 'Mary Run'} + ] + }; + } + + +
+ Manager: {{employee.name}} [ {{department}} ]
+ Reports: +
    +
  • + {{employee.name}} [ {{department}} ] +
  • +
+
+ {{greeting}} +
+
+
+ +Notice that Angular automatically places `ng-scope` class on elements where scopes are +attached. The ` + + + + +Notice how we nested three `ng-controller` directives in our template. This will result in four +scopes being created for our view: + +- The root scope +- The `MainCtrl` scope, which contains `timeOfDay` and `name` properties +- The `ChildCtrl` scope, which inherits the `timeOfDay` property but overrides (hides) the `name` +property from the previous +- The `GrandChildCtrl` scope, which overrides (hides) both the `timeOfDay` property defined in `MainCtrl` +and the `name` property defined in `ChildCtrl` + +Inheritance works with methods in the same way as it does with properties. So in our previous +examples, all of the properties could be replaced with methods that return string values. + + +## Testing Controllers + +Although there are many ways to test a Controller, one of the best conventions, shown below, +involves injecting the {@link api/ng.$rootScope $rootScope} and {@link api/ng.$controller $controller}: + +**Controller Definition:** +
+    var myApp = angular.module('myApp',[]);
+
+    myApp.controller('MyController', function($scope) {
+      $scope.spices = [{"name":"pasilla", "spiciness":"mild"},
+                       {"name":"jalapeno", "spiceiness":"hot hot hot!"},
+                       {"name":"habanero", "spiceness":"LAVA HOT!!"}];
+      $scope.spice = "habanero";
+    });
+
+ +**Controller Test:** +
+describe('myController function', function() {
+
+  describe('myController', function() {
+    var $scope;
+
+    beforeEach(module('myApp'));
+
+    beforeEach(inject(function($rootScope, $controller) {
+      $scope = $rootScope.$new();
+      $controller('MyController', {$scope: $scope});
+    }));
+
+    it('should create "spices" model with 3 spices', function() {
+      expect($scope.spices.length).toBe(3);
+    });
+
+    it('should set the default value of spice', function() {
+      expect($scope.spice).toBe('habanero');
+    });
+  });
+});
+
+ + +If you need to test a nested Controller you need to create the same scope hierarchy +in your test that exists in the DOM: + +
+describe('state', function() {
+    var mainScope, childScope, grandChildScope;
+
+    beforeEach(module('myApp'));
+
+    beforeEach(inject(function($rootScope, $controller) {
+        mainScope = $rootScope.$new();
+        $controller('MainCtrl', {$scope: mainScope});
+        childScope = mainScope.$new();
+        $controller('ChildCtrl', {$scope: childScope});
+        grandChildScope = childScope.$new();
+        $controller('GrandChildCtrl', {$scope: grandChildScope});
+    }));
+
+    it('should have over and selected', function() {
+        expect(mainScope.timeOfDay).toBe('morning');
+        expect(mainScope.name).toBe('Nikki');
+        expect(childScope.timeOfDay).toBe('morning');
+        expect(childScope.name).toBe('Mattie');
+        expect(grandChildScope.timeOfDay).toBe('evening');
+        expect(grandChildScope.name).toBe('Gingerbreak Baby');
+    });
+});
+
+ + + diff --git a/docs/content-ko/guide/databinding.ngdoc b/docs/content-ko/guide/databinding.ngdoc new file mode 100644 index 000000000000..e5b4f754c974 --- /dev/null +++ b/docs/content-ko/guide/databinding.ngdoc @@ -0,0 +1,38 @@ +@ngdoc overview +@name Data Binding +@description + +Data-binding in Angular web apps is the automatic synchronization of data between the model and view +components. The way that Angular implements data-binding lets you treat the model as the +single-source-of-truth in your application. The view is a projection of the model at all times. +When the model changes, the view reflects the change, and vice versa. + +## Data Binding in Classical Template Systems + + +Most templating systems bind data in only one direction: they merge template and model components +together into a view, as illustrated in the diagram. After the merge occurs, changes to the model +or related sections of the view are NOT automatically reflected in the view. Worse, any changes +that the user makes to the view are not reflected in the model. This means that the developer has +to write code that constantly syncs the view with the model and the model with the view. + +## Data Binding in Angular Templates + + +The way Angular templates works is different, as illustrated in the diagram. They are different +because first the template (which is the uncompiled HTML along with any additional markup or +directives) is compiled on the browser, and second, the compilation step produces a live view. We +say live because any changes to the view are immediately reflected in the model, and any changes in +the model are propagated to the view. This makes the model always the single-source-of-truth for +the application state, greatly simplifying the programming model for the developer. You can think of +the view as simply an instant projection of your model. + +Because the view is just a projection of the model, the controller is completely separated from the +view and unaware of it. This makes testing a snap because it is easy to test your controller in +isolation without the view and the related DOM/browser dependency. + + +## Related Topics + +* {@link scope Angular Scopes} +* {@link templates Angular Templates} diff --git a/docs/content-ko/guide/dev_guide.e2e-testing.ngdoc b/docs/content-ko/guide/dev_guide.e2e-testing.ngdoc new file mode 100644 index 000000000000..4e58f8397c75 --- /dev/null +++ b/docs/content-ko/guide/dev_guide.e2e-testing.ngdoc @@ -0,0 +1,312 @@ +@workInProgress +@ngdoc overview +@name Developer Guide: E2E Testing +@description + +**If you're starting a new Angular project, you may want to look into +using {@link https://github.com/angular/protractor Protractor}, as it is going to +replace the current method of E2E Testing in the near future.** + +As applications grow in size and complexity, it becomes unrealistic to rely on manual testing to +verify the correctness of new features, catch bugs and notice regressions. + +To solve this problem, we have built an Angular Scenario Runner which simulates user interactions +that will help you verify the health of your Angular application. + +# Overview +You will write scenario tests in JavaScript, which describe how your application should behave, +given a certain interaction in a specific state. A scenario is comprised of one or more `it` blocks +(you can think of these as the requirements of your application), which in turn are made of +**commands** and **expectations**. Commands tell the Runner to do something with the application +(such as navigate to a page or click on a button), and expectations tell the Runner to assert +something about the state (such as the value of a field or the current URL). If any expectation +fails, the runner marks the `it` as "failed" and continues on to the next one. Scenarios may also +have **beforeEach** and **afterEach** blocks, which will be run before (or after) each `it` block, +regardless of whether they pass or fail. + + + +In addition to the above elements, scenarios may also contain helper functions to avoid duplicating +code in the `it` blocks. + +Here is an example of a simple scenario: +
+describe('Buzz Client', function() {
+it('should filter results', function() {
+  input('user').enter('jacksparrow');
+  element(':button').click();
+  expect(repeater('ul li').count()).toEqual(10);
+  input('filterText').enter('Bees');
+  expect(repeater('ul li').count()).toEqual(1);
+});
+});
+
+ +Note that +[`input('user')`](https://github.com/angular/angular.js/blob/master/docs/content/guide/dev_guide.e2e-testing.ngdoc#L119) +finds the `` element with `ng-model="user"` not `name="user"`. + +This scenario describes the requirements of a Buzz Client, specifically, that it should be able to +filter the stream of the user. It starts by entering a value in the input field with ng-model="user", clicking +the only button on the page, and then it verifies that there are 10 items listed. It then enters +'Bees' in the input field with ng-model='filterText' and verifies that the list is reduced to a single item. + +The API section below lists the available commands and expectations for the Runner. + +# API +Source: {@link https://github.com/angular/angular.js/blob/master/src/ngScenario/dsl.js} + +## pause() +Pauses the execution of the tests until you call `resume()` in the console (or click the resume +link in the Runner UI). + +## sleep(seconds) +Pauses the execution of the tests for the specified number of `seconds`. + +## browser().navigateTo(url) +Loads the `url` into the test frame. + +## browser().navigateTo(url, fn) +Loads the URL returned by `fn` into the testing frame. The given `url` is only used for the test +output. Use this when the destination URL is dynamic (that is, the destination is unknown when you +write the test). + +## browser().reload() +Refreshes the currently loaded page in the test frame. + +## browser().window().href() +Returns the window.location.href of the currently loaded page in the test frame. + +## browser().window().path() +Returns the window.location.pathname of the currently loaded page in the test frame. + +## browser().window().search() +Returns the window.location.search of the currently loaded page in the test frame. + +## browser().window().hash() +Returns the window.location.hash (without `#`) of the currently loaded page in the test frame. + +## browser().location().url() +Returns the {@link api/ng.$location $location.url()} of the currently loaded page in +the test frame. + +## browser().location().path() +Returns the {@link api/ng.$location $location.path()} of the currently loaded page in +the test frame. + +## browser().location().search() +Returns the {@link api/ng.$location $location.search()} of the currently loaded page +in the test frame. + +## browser().location().hash() +Returns the {@link api/ng.$location $location.hash()} of the currently loaded page in +the test frame. + +## expect(future).{matcher} +Asserts the value of the given `future` satisfies the `matcher`. All API statements return a +`future` object, which get a `value` assigned after they are executed. Matchers are defined using +`angular.scenario.matcher`, and they use the value of futures to run the expectation. For example: +`expect(browser().location().href()).toEqual('http://www.google.com')`. Available matchers +are presented further down this document. + +## expect(future).not().{matcher} +Asserts the value of the given `future` satisfies the negation of the `matcher`. + +## using(selector, label) +Scopes the next DSL element selection. + +## binding(name) +Returns the value of the first binding matching the given `name`. + +## input(name).enter(value) +Enters the given `value` in the text field with the corresponding ng-model `name`. + +## input(name).check() +Checks/unchecks the checkbox with the corresponding ng-model `name`. + +## input(name).select(value) +Selects the given `value` in the radio button with the corresponding ng-model `name`. + +## input(name).val() +Returns the current value of an input field with the corresponding ng-model `name`. + +## repeater(selector, label).count() +Returns the number of rows in the repeater matching the given jQuery `selector`. The `label` is +used for test output. + +## repeater(selector, label).row(index) +Returns an array with the bindings in the row at the given `index` in the repeater matching the +given jQuery `selector`. The `label` is used for test output. + +## repeater(selector, label).column(binding) +Returns an array with the values in the column with the given `binding` in the repeater matching +the given jQuery `selector`. The `label` is used for test output. + +## select(name).option(value) +Picks the option with the given `value` on the select with the given ng-model `name`. + +## select(name).options(value1, value2...) +Picks the options with the given `values` on the multi select with the given ng-model `name`. + +## element(selector, label).count() +Returns the number of elements that match the given jQuery `selector`. The `label` is used for test +output. + +## element(selector, label).click() +Clicks on the element matching the given jQuery `selector`. The `label` is used for test output. + +## element(selector, label).query(fn) +Executes the function `fn(selectedElements, done)`, where selectedElements are the elements that +match the given jQuery `selector` and `done` is a function that is called at the end of the `fn` +function. The `label` is used for test output. + +## element(selector, label).{method}() +Returns the result of calling `method` on the element matching the given jQuery `selector`, where +`method` can be any of the following jQuery methods: `val`, `text`, `html`, `height`, +`innerHeight`, `outerHeight`, `width`, `innerWidth`, `outerWidth`, `position`, `scrollLeft`, +`scrollTop`, `offset`. The `label` is used for test output. + +## element(selector, label).{method}(value) +Executes the `method` passing in `value` on the element matching the given jQuery `selector`, where +`method` can be any of the following jQuery methods: `val`, `text`, `html`, `height`, +`innerHeight`, `outerHeight`, `width`, `innerWidth`, `outerWidth`, `position`, `scrollLeft`, +`scrollTop`, `offset`. The `label` is used for test output. + +## element(selector, label).{method}(key) +Returns the result of calling `method` passing in `key` on the element matching the given jQuery +`selector`, where `method` can be any of the following jQuery methods: `attr`, `prop`, `css`. The +`label` is used for test output. + +## element(selector, label).{method}(key, value) +Executes the `method` passing in `key` and `value` on the element matching the given jQuery +`selector`, where `method` can be any of the following jQuery methods: `attr`, `prop`, `css`. The +`label` is used for test output. + +# Matchers + +Matchers are used in combination with the `expect(...)` function as described above and can +be negated with `not()`. For instance: `expect(element('h1').text()).not().toEqual('Error')`. + +Source: {@link https://github.com/angular/angular.js/blob/master/src/ngScenario/matchers.js} + +
+// value and Object comparison following the rules of angular.equals().
+expect(value).toEqual(value)
+
+// a simpler value comparison using ===
+expect(value).toBe(value)
+
+// checks that the value is defined by checking its type.
+expect(value).toBeDefined()
+
+// the following two matchers are using JavaScript's standard truthiness rules
+expect(value).toBeTruthy()
+expect(value).toBeFalsy()
+
+// verify that the value matches the given regular expression. The regular
+// expression may be passed in form of a string or a regular expression
+// object.
+expect(value).toMatch(expectedRegExp)
+
+// a check for null using ===
+expect(value).toBeNull()
+
+// Array.indexOf(...) is used internally to check whether the element is
+// contained within the array.
+expect(value).toContain(expected)
+
+// number comparison using < and >
+expect(value).toBeLessThan(expected)
+expect(value).toBeGreaterThan(expected)
+
+ +# Example +See the {@link https://github.com/angular/angular-seed angular-seed} project for more examples. + +## Conditional actions with element(...).query(fn) + +E2E testing with angular scenario is highly asynchronous and hides a lot of complexity by +queueing actions and expectations that can handle futures. From time to time, you might need +conditional assertions or element selection. Even though you should generally try to avoid this +(as it is can be sign for unstable tests), you can add conditional behavior with +`element(...).query(fn)`. The following code listing shows how this function can be used to delete +added entries (where an entry is some domain object) using the application's web interface. + +Imagine the application to be structured into two views: + + 1. *Overview view* which lists all the added entries in a table and + 2. a *detail view* which shows the entries' details and contains a delete button. When clicking the + delete button, the user is redirected back to the *overview page*. + +
+beforeEach(function () {
+  var deleteEntry = function () {
+    browser().navigateTo('/entries');
+
+    // we need to select the  element as it might be the case that there
+    // are no entries (and therefore no rows). When the selector does not
+    // result in a match, the test would be marked as a failure.
+    element('table tbody').query(function (tbody, done) {
+      // ngScenario gives us a jQuery lite wrapped element. We call the
+      // `children()` function to retrieve the table body's rows
+      var children = tbody.children();
+
+      if (children.length > 0) {
+        // if there is at least one entry in the table, click on the link to
+        // the entry's detail view
+        element('table tbody a').click();
+        // and, after a route change, click the delete button
+        element('.btn-danger').click();
+      }
+
+      // if there is more than one entry shown in the table, queue another
+      // delete action.
+      if (children.length > 1) {
+        deleteEntry();
+      }
+
+      // remember to call `done()` so that ngScenario can continue
+      // test execution.
+      done();
+    });
+
+  };
+
+  // start deleting entries
+  deleteEntry();
+});
+
+ +In order to understand what is happening, we should emphasize that ngScenario calls are not +immediately executed, but queued (in ngScenario terms, we would be talking about adding +future actions). If we had only one entry in our table, then the following future actions +would be queued: + +
+// delete entry 1
+browser().navigateTo('/entries');
+element('table tbody').query(function (tbody, done) { ... });
+element('table tbody a');
+element('.btn-danger').click();
+
+ +For two entries, ngScenario would have to work on the following queue: + +
+// delete entry 1
+browser().navigateTo('/entries');
+element('table tbody').query(function (tbody, done) { ... });
+element('table tbody a');
+element('.btn-danger').click();
+
+    // delete entry 2
+    // indented to represent "recursion depth"
+    browser().navigateTo('/entries');
+    element('table tbody').query(function (tbody, done) { ... });
+    element('table tbody a');
+    element('.btn-danger').click();
+
+ +# Caveats + +ngScenario does not work with apps that manually bootstrap using angular.bootstrap. You must use the ng-app directive. diff --git a/docs/content-ko/guide/dev_guide.services.$location.ngdoc b/docs/content-ko/guide/dev_guide.services.$location.ngdoc new file mode 100644 index 000000000000..bfd1d5d90999 --- /dev/null +++ b/docs/content-ko/guide/dev_guide.services.$location.ngdoc @@ -0,0 +1,659 @@ +@ngdoc overview +@name Developer Guide: Angular Services: Using $location +@description + +# What does it do? + +The `$location` service parses the URL in the browser address bar (based on the {@link +https://developer.mozilla.org/en/window.location window.location}) and makes the URL available to +your application. Changes to the URL in the address bar are reflected into $location service and +changes to $location are reflected into the browser address bar. + +**The $location service:** + +- Exposes the current URL in the browser address bar, so you can + - Watch and observe the URL. + - Change the URL. +- Maintains synchronization between itself and the browser's URL when the user + - Changes the address in the browser's address bar. + - Clicks the back or forward button in the browser (or clicks a History link). + - Clicks on a link in the page. +- Represents the URL object as a set of methods (protocol, host, port, path, search, hash). + + +## Comparing $location to window.location + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
window.location$location service
purposeallow read/write access to the current browser locationsame
APIexposes "raw" object with properties that can be directly modifiedexposes jQuery-style getters and setters
integration with angular application life-cyclenoneknows about all internal life-cycle phases, integrates with $watch, ...
seamless integration with HTML5 APInoyes (with a fallback for legacy browsers)
aware of docroot/context from which the application is loadedno - window.location.path returns "/docroot/actual/path"yes - $location.path() returns "/actual/path"
+ +## When should I use $location? +Any time your application needs to react to a change in the current URL or if you want to change +the current URL in the browser. + +## What does it not do? +It does not cause a full page reload when the browser URL is changed. To reload the page after +changing the URL, use the lower-level API, `$window.location.href`. + +# General overview of the API + +The `$location` service can behave differently, depending on the configuration that was provided to +it when it was instantiated. The default configuration is suitable for many applications, for +others customizing the configuration can enable new features. + +Once the `$location` service is instantiated, you can interact with it via jQuery-style getter and +setter methods that allow you to get or change the current URL in the browser. + +## $location service configuration + +To configure the `$location` service, retrieve the +{@link api/ng.$locationProvider $locationProvider} and set the parameters as follows: + + +- **html5Mode(mode)**: {boolean}
+ `true` - see HTML5 mode
+ `false` - see Hashbang mode
+ default: `false` + +- **hashPrefix(prefix)**: {string}
+ prefix used for Hashbang URLs (used in Hashbang mode or in legacy browser in Html5 mode)
+ default: `""` + +### Example configuration +
+$locationProvider.html5Mode(true).hashPrefix('!');
+
+ +## Getter and setter methods + +`$location` service provides getter methods for read-only parts of the URL (absUrl, protocol, host, +port) and getter / setter methods for url, path, search, hash: +
+// get the current path
+$location.path();
+
+// change the path
+$location.path('/newValue')
+
+ +All of the setter methods return the same `$location` object to allow chaining. For example, to +change multiple segments in one go, chain setters like this: +
$location.path('/newValue').search({key: value});
+ +## Replace method + +There is a special `replace` method which can be used to tell the $location service that the next +time the $location service is synced with the browser, the last history record should be replaced +instead of creating a new one. This is useful when you want to implement redirection, which would +otherwise break the back button (navigating back would retrigger the redirection). To change the +current URL without creating a new browser history record you can call: +
+  $location.path('/someNewPath');
+  $location.replace();
+  // or you can chain these as: $location.path('/someNewPath').replace();
+
+ +Note that the setters don't update `window.location` immediately. Instead, the `$location` service is +aware of the {@link api/ng.$rootScope.Scope scope} life-cycle and coalesces multiple `$location` +mutations into one "commit" to the `window.location` object during the scope `$digest` phase. Since +multiple changes to the $location's state will be pushed to the browser as a single change, it's +enough to call the `replace()` method just once to make the entire "commit" a replace operation +rather than an addition to the browser history. Once the browser is updated, the $location service +resets the flag set by `replace()` method and future mutations will create new history records, +unless `replace()` is called again. + +### Setters and character encoding +You can pass special characters to `$location` service and it will encode them according to rules +specified in {@link http://www.ietf.org/rfc/rfc3986.txt RFC 3986}. When you access the methods: + +- All values that are passed to `$location` setter methods, `path()`, `search()`, `hash()`, are +encoded. +- Getters (calls to methods without parameters) return decoded values for the following methods +`path()`, `search()`, `hash()`. +- When you call the `absUrl()` method, the returned value is a full url with its segments encoded. +- When you call the `url()` method, the returned value is path, search and hash, in the form +`/path?search=a&b=c#hash`. The segments are encoded as well. + + +# Hashbang and HTML5 Modes + +`$location` service has two configuration modes which control the format of the URL in the browser +address bar: **Hashbang mode** (the default) and the **HTML5 mode** which is based on using the +HTML5 {@link http://www.w3.org/TR/html5/history.html History API}. Applications use the same API in +both modes and the `$location` service will work with appropriate URL segments and browser APIs to +facilitate the browser URL change and history management. + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
Hashbang modeHTML5 mode
configurationthe default{ html5Mode: true }
URL formathashbang URLs in all browsersregular URLs in modern browser, hashbang URLs in old browser
<a href=""> link rewritingnoyes
requires server-side configurationnoyes
+ +## Hashbang mode (default mode) + +In this mode, `$location` uses Hashbang URLs in all browsers. + +### Example + +
+it('should show example', inject(
+  function($locationProvider) {
+    $locationProvider.html5Mode(false);
+    $locationProvider.hashPrefix('!');
+  },
+  function($location) {
+    // open http://example.com/base/index.html#!/a
+    $location.absUrl() == 'http://example.com/base/index.html#!/a'
+    $location.path() == '/a'
+
+    $location.path('/foo')
+    $location.absUrl() == 'http://example.com/base/index.html#!/foo'
+
+    $location.search() == {}
+    $location.search({a: 'b', c: true});
+    $location.absUrl() == 'http://example.com/base/index.html#!/foo?a=b&c'
+
+    $location.path('/new').search('x=y');
+    $location.absUrl() == 'http://example.com/base/index.html#!/new?x=y'
+  }
+));
+
+ +### Crawling your app + +To allow indexing of your AJAX application, you have to add special meta tag in the head section of +your document: +
+ +This will cause crawler bot to request links with `_escaped_fragment_` param so that your server +can recognize the crawler and serve a HTML snapshots. For more information about this technique, +see {@link http://code.google.com/web/ajaxcrawling/docs/specification.html Making AJAX Applications +Crawlable}. + +## HTML5 mode + +In HTML5 mode, the `$location` service getters and setters interact with the browser URL address +through the HTML5 history API, which allows for use of regular URL path and search segments, +instead of their hashbang equivalents. If the HTML5 History API is not supported by a browser, the +`$location` service will fall back to using the hashbang URLs automatically. This frees you from +having to worry about whether the browser displaying your app supports the history API or not; the +`$location` service transparently uses the best available option. + +- Opening a regular URL in a legacy browser -> redirects to a hashbang URL +- Opening hashbang URL in a modern browser -> rewrites to a regular URL + +### Example + +
+it('should show example', inject(
+  function($locationProvider) {
+    $locationProvider.html5Mode(true);
+    $locationProvider.hashPrefix('!');
+  },
+  function($location) {
+    // in browser with HTML5 history support:
+    // open http://example.com/#!/a -> rewrite to http://example.com/a
+    // (replacing the http://example.com/#!/a history record)
+    $location.path() == '/a'
+
+    $location.path('/foo');
+    $location.absUrl() == 'http://example.com/foo'
+
+    $location.search() == {}
+    $location.search({a: 'b', c: true});
+    $location.absUrl() == 'http://example.com/foo?a=b&c'
+
+    $location.path('/new').search('x=y');
+    $location.url() == 'new?x=y'
+    $location.absUrl() == 'http://example.com/new?x=y'
+
+    // in browser without html5 history support:
+    // open http://example.com/new?x=y -> redirect to http://example.com/#!/new?x=y
+    // (again replacing the http://example.com/new?x=y history item)
+    $location.path() == '/new'
+    $location.search() == {x: 'y'}
+
+    $location.path('/foo/bar');
+    $location.path() == '/foo/bar'
+    $location.url() == '/foo/bar?x=y'
+    $location.absUrl() == 'http://example.com/#!/foo/bar?x=y'
+  }
+));
+
+ +### Fallback for legacy browsers + +For browsers that support the HTML5 history API, `$location` uses the HTML5 history API to write +path and search. If the history API is not supported by a browser, `$location` supplies a Hasbang +URL. This frees you from having to worry about whether the browser viewing your app supports the +history API or not; the `$location` service makes this transparent to you. + +### Html link rewriting + +When you use HTML5 history API mode, you will need different links in different browsers, but all you +have to do is specify regular URL links, such as: `link` + +When a user clicks on this link, + +- In a legacy browser, the URL changes to `/index.html#!/some?foo=bar` +- In a modern browser, the URL changes to `/some?foo=bar` + + +In cases like the following, links are not rewritten; instead, the browser will perform a full page +reload to the original link. + +- Links that contain `target` element
+ Example: `link` +- Absolute links that go to a different domain
+ Example: `link` +- Links starting with '/' that lead to a different base path when base is defined
+ Example: `link` + +When running Angular in the root of a domain, along side perhaps a normal application in the same +directory, the "otherwise" route handler will try to handle all the URLs, including ones that map +to static files. + +To prevent this, you can set your base href for the app to `` and then prefix links +to URLs that should be handled with `.`. Now, links to locations, which are not to be routed by Angular, +are not prefixed with `.` and will not be intercepted by the `otherwise` rule in your `$routeProvider`. + + +### Server side + +Using this mode requires URL rewriting on server side, basically you have to rewrite all your links +to entry point of your application (e.g. index.html) + +### Crawling your app + +If you want your AJAX application to be indexed by web crawlers, you will need to add the following +meta tag to the HEAD section of your document: +
+ +This statement causes a crawler to request links with an empty `_escaped_fragment_` parameter so that +your server can recognize the crawler and serve it HTML snapshots. For more information about this +technique, see {@link http://code.google.com/web/ajaxcrawling/docs/specification.html Making AJAX +Applications Crawlable}. + +### Relative links + +Be sure to check all relative links, images, scripts etc. You must either specify the url base in +the head of your main html file (``) or you must use absolute urls +(starting with `/`) everywhere because relative urls will be resolved to absolute urls using the +initial absolute url of the document, which is often different from the root of the application. + +Running Angular apps with the History API enabled from document root is strongly encouraged as it +takes care of all relative link issues. + +### Sending links among different browsers + +Because of rewriting capability in HTML5 mode, your users will be able to open regular url links in +legacy browsers and hashbang links in modern browser: + +- Modern browser will rewrite hashbang URLs to regular URLs. +- Older browsers will redirect regular URLs to hashbang URLs. + +### Example + +Here you can see two `$location` instances, both in **Html5 mode**, but on different browsers, so +that you can see the differences. These `$location` services are connected to a fake browsers. Each +input represents address bar of the browser. + +Note that when you type hashbang url into first browser (or vice versa) it doesn't rewrite / +redirect to regular / hashbang url, as this conversion happens only during parsing the initial URL += on page reload. + +In this examples we use `` + + + +
+
+

Browser with History API

+


+ $location.protocol() = {{$location.protocol()}}
+ $location.host() = {{$location.host()}}
+ $location.port() = {{$location.port()}}
+ $location.path() = {{$location.path()}}
+ $location.search() = {{$location.search()}}
+ $location.hash() = {{$location.hash()}}
+ /base/first?a=b | + sec/ond?flag#hash | + external +
+ +
+

Browser without History API

+


+ $location.protocol() = {{$location.protocol()}}
+ $location.host() = {{$location.host()}}
+ $location.port() = {{$location.port()}}
+ $location.path() = {{$location.path()}}
+ $location.search() = {{$location.search()}}
+ $location.hash() = {{$location.hash()}}
+ /base/first?a=b | + sec/ond?flag#hash | + external +
+
+ + + +
+
+ + +# Caveats + +## Page reload navigation + +The `$location` service allows you to change only the URL; it does not allow you to reload the +page. When you need to change the URL and reload the page or navigate to a different page, please +use a lower level API, {@link api/ng.$window $window.location.href}. + +## Using $location outside of the scope life-cycle + +`$location` knows about Angular's {@link api/ng.$rootScope.Scope scope} life-cycle. When a URL changes in +the browser it updates the `$location` and calls `$apply` so that all $watchers / $observers are +notified. +When you change the `$location` inside the `$digest` phase everything is ok; `$location` will +propagate this change into browser and will notify all the $watchers / $observers. +When you want to change the `$location` from outside Angular (for example, through a DOM Event or +during testing) - you must call `$apply` to propagate the changes. + +## $location.path() and ! or / prefixes + +A path should always begin with forward slash (`/`); the `$location.path()` setter will add the +forward slash if it is missing. + +Note that the `!` prefix in the hashbang mode is not part of `$location.path()`; it is actually +hashPrefix. + + +# Testing with the $location service + +When using `$location` service during testing, you are outside of the angular's {@link +api/ng.$rootScope.Scope scope} life-cycle. This means it's your responsibility to call `scope.$apply()`. + +
+describe('serviceUnderTest', function() {
+  beforeEach(module(function($provide) {
+    $provide.factory('serviceUnderTest', function($location){
+      // whatever it does...
+    });
+  });
+
+  it('should...', inject(function($location, $rootScope, serviceUnderTest) {
+    $location.path('/new/path');
+    $rootScope.$apply();
+
+    // test whatever the service should do...
+
+  }));
+});
+
+ + +# Migrating from earlier AngularJS releases + +In earlier releases of Angular, `$location` used `hashPath` or `hashSearch` to process path and +search methods. With this release, the `$location` service processes path and search methods and +then uses the information it obtains to compose hashbang URLs (such as +`http://server.com/#!/path?search=a`), when necessary. + +## Changes to your code + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
Navigation inside the appChange to
$location.href = value
$location.hash = value
$location.update(value)
$location.updateHash(value)
$location.path(path).search(search)
$location.hashPath = path$location.path(path)
$location.hashSearch = search$location.search(search)
Navigation outside the appUse lower level API
$location.href = value
$location.update(value)
$window.location.href = value
$location[protocol | host | port | path | search]$window.location[protocol | host | port | path | search]
Read accessChange to
$location.hashPath$location.path()
$location.hashSearch$location.search()
$location.href
$location.protocol
$location.host
$location.port
$location.hash
$location.absUrl()
$location.protocol()
$location.host()
$location.port()
$location.path() + $location.search()
$location.path
$location.search
$window.location.path
$window.location.search
+ +## Two-way binding to $location + +The Angular's compiler currently does not support two-way binding for methods (see {@link +https://github.com/angular/angular.js/issues/404 issue}). If you should require two-way binding +to the $location object (using {@link api/ng.directive:input.text +ngModel} directive on an input field), you will need to specify an extra model property +(e.g. `locationPath`) with two watchers which push $location updates in both directions. For +example: + + +
+ +
+
+ +function LocationController($scope, $location) { + $scope.$watch('locationPath', function(path) { + $location.path(path); + }); + $scope.$watch(function() { + return $location.path(); + }, function(path) { + $scope.locationPath = path; + }); +} + +
+ +# Related API + +* {@link api/ng.$location $location API} + + + diff --git a/docs/content-ko/guide/dev_guide.services.creating_services.ngdoc b/docs/content-ko/guide/dev_guide.services.creating_services.ngdoc new file mode 100644 index 000000000000..d5adc4babdff --- /dev/null +++ b/docs/content-ko/guide/dev_guide.services.creating_services.ngdoc @@ -0,0 +1,104 @@ +@ngdoc overview +@name Developer Guide: Angular Services: Creating Services +@description + +While Angular offers several useful services, for any nontrivial application you'll find it useful +to write your own custom services. To do this you begin by registering a service factory function +with a module either via the {@link api/angular.module Module#factory api} or directly +via the {@link api/AUTO.$provide $provide} api inside of module config function. + +All Angular services participate in {@link di dependency injection (DI)} by registering +themselves with Angular's DI system (injector) under a `name` (id) as well as by declaring +dependencies which need to be provided for the factory function of the registered service. The +ability to swap dependencies for mocks/stubs/dummies in tests allows for services to be highly +testable. + + +# Registering Services + +To register a service, you must have a module that this service will be part of. Afterwards, you +can register the service with the module either via the {@link api/angular.Module Module api} or +by using the {@link api/AUTO.$provide $provide} service in the module configuration +function.The following pseudo-code shows both approaches: + +Using the angular.Module api: +
+var myModule = angular.module('myModule', []);
+myModule.factory('serviceId', function() {
+  var shinyNewServiceInstance;
+  //factory function body that constructs shinyNewServiceInstance
+  return shinyNewServiceInstance;
+});
+
+ +Using the $provide service: +
+angular.module('myModule', [], function($provide) {
+  $provide.factory('serviceId', function() {
+    var shinyNewServiceInstance;
+    //factory function body that constructs shinyNewServiceInstance
+    return shinyNewServiceInstance;
+  });
+});
+
+ +Note that you are not registering a service instance, but rather a factory function that will +create this instance when called. + + +# Dependencies + +Services can not only be depended upon, but can also have their own dependencies. These can be specified +as arguments of the factory function. {@link di Read more} about dependency injection (DI) +in Angular and the use of array notation and the $inject property to make DI annotation +minification-proof. + +Following is an example of a very simple service. This service depends on the `$window` service +(which is passed as a parameter to the factory function) and is just a function. The service simply +stores all notifications; after the third one, the service displays all of the notifications by +window alert. + +
+angular.module('myModule', [], function($provide) {
+  $provide.factory('notify', ['$window', function(win) {
+    var msgs = [];
+    return function(msg) {
+      msgs.push(msg);
+      if (msgs.length == 3) {
+        win.alert(msgs.join("\n"));
+        msgs = [];
+      }
+    };
+  }]);
+});
+
+ + +# Instantiating Angular Services + +All services in Angular are instantiated lazily. This means that a service will be created +only when it is needed for instantiation of a service or an application component that depends on it. +In other words, Angular won't instantiate services unless they are requested directly or +indirectly by the application. + + +# Services as singletons + +Lastly, it is important to realize that all Angular services are application singletons. This means +that there is only one instance of a given service per injector. Since Angular is lethally allergic +to global state, it is possible to create multiple injectors, each with its own instance of a +given service, but that is rarely needed, except in tests where this property is crucially +important. + + + +## Related Topics + +* {@link dev_guide.services.understanding_services Understanding Angular Services} +* {@link dev_guide.services.managing_dependencies Managing Service Dependencies} +* {@link dev_guide.services.injecting_controllers Injecting Services Into Controllers } +* {@link dev_guide.services.testing_services Testing Angular Services} + +## Related API + +* {@link api/ng Angular Service API} diff --git a/docs/content-ko/guide/dev_guide.services.injecting_controllers.ngdoc b/docs/content-ko/guide/dev_guide.services.injecting_controllers.ngdoc new file mode 100644 index 000000000000..64fa0aafe351 --- /dev/null +++ b/docs/content-ko/guide/dev_guide.services.injecting_controllers.ngdoc @@ -0,0 +1,120 @@ +@ngdoc overview +@name Developer Guide: Angular Services: Injecting Services Into Controllers +@description + +Using services as dependencies for controllers is very similar to using services as dependencies +for another service. + +Since JavaScript is a dynamic language, DI can't figure out which services to inject by static +types (like in static typed languages). Therefore, you can specify the service name by using the +`$inject` property, which is an array containing strings with names of services to be injected. +The name must match the corresponding service ID registered with angular. The order of the service +IDs matters: the order of the services in the array will be used when calling the factory function +with injected parameters. The names of parameters in factory function don't matter, but by +convention they match the service IDs, which has added benefits discussed below. + +
+function myController($loc, $log) {
+  this.firstMethod = function() {
+    // use $location service
+    $loc.setHash();
+  };
+  this.secondMethod = function() {
+    // use $log service
+    $log.info('...');
+  };
+}
+// which services to inject ?
+myController.$inject = ['$location', '$log'];
+
+ + + + + +
+

Let's try this simple notify service, injected into the controller...

+ + +

(you have to click 3 times to see an alert)

+
+
+ + it('should test service', function() { + expect(element(':input[ng\\:model="message"]').val()).toEqual('test'); + }); + +
+ +## Implicit Dependency Injection + +A new feature of Angular DI allows it to determine the dependency from the name of the parameter. +Let's rewrite the above example to show the use of this implicit dependency injection of +`$window`, `$scope`, and our `notify` service: + + + + +
+

Let's try the notify service, that is implicitly injected into the controller...

+ + +

(you have to click 3 times to see an alert)

+
+
+
+ +However, if you plan to {@link http://en.wikipedia.org/wiki/Minification_(programming) minify} your +code, your variable names will get renamed in which case you will still need to explicitly specify +dependencies with the `$inject` property. + +## Related Topics + +{@link dev_guide.services.understanding_services Understanding Angular Services} +{@link dev_guide.services.creating_services Creating Angular Services} +{@link dev_guide.services.managing_dependencies Managing Service Dependencies} +{@link dev_guide.services.testing_services Testing Angular Services} + +## Related API + +{@link api/ng Angular Service API} diff --git a/docs/content-ko/guide/dev_guide.services.managing_dependencies.ngdoc b/docs/content-ko/guide/dev_guide.services.managing_dependencies.ngdoc new file mode 100644 index 000000000000..b069f4bb3ac1 --- /dev/null +++ b/docs/content-ko/guide/dev_guide.services.managing_dependencies.ngdoc @@ -0,0 +1,114 @@ +@ngdoc overview +@name Developer Guide: Angular Services: Managing Service Dependencies +@description + +Angular allows services to declare other services as dependencies needed for construction of their +instances. + +To declare dependencies, you specify them in the factory function signature and annotate the +function with the inject annotations either using by setting the `$inject` property, as an array of +string identifiers or using the array notation. Optionally the `$inject` property declaration can be +dropped (see "Inferring `$inject`" but note that that is currently an experimental feature). + +Using the array notation: + +
+function myModuleCfgFn($provide) {
+  $provide.factory('myService', ['dep1', 'dep2', function(dep1, dep2) {}]);
+}
+
+ + +Using the $inject property: + +
+function myModuleCfgFn($provide) {
+  var myServiceFactory = function(dep1, dep2) {};
+  myServiceFactory.$inject = ['dep1', 'dep2'];
+  $provide.factory('myService', myServiceFactory);
+}
+
+ + +Using DI inference (incompatible with minifiers): + +
+function myModuleCfgFn($provide) {
+  $provide.factory('myService', function(dep1, dep2) {});
+}
+
+ + +Here is an example of two services, one of which depends on the other and both +of which depend on other services that are provided by the Angular framework: + +
+/**
+ * batchLog service allows for messages to be queued in memory and flushed
+ * to the console.log every 50 seconds.
+ *
+ * @param {*} message Message to be logged.
+ */
+  function batchLogModule($provide){
+    $provide.factory('batchLog', ['$timeout', '$log', function($timeout, $log) {
+      var messageQueue = [];
+
+      function log() {
+        if (messageQueue.length) {
+          $log('batchLog messages: ', messageQueue);
+          messageQueue = [];
+        }
+        $timeout(log, 50000);
+      }
+
+      // start periodic checking
+      log();
+
+      return function(message) {
+        messageQueue.push(message);
+      }
+    }]);
+
+    /**
+     * routeTemplateMonitor monitors each $route change and logs the current
+     * template via the batchLog service.
+     */
+    $provide.factory('routeTemplateMonitor',
+                ['$route', 'batchLog', '$rootScope',
+         function($route,   batchLog,   $rootScope) {
+      $rootScope.$on('$routeChangeSuccess', function() {
+        batchLog($route.current ? $route.current.template : null);
+      });
+    }]);
+  }
+
+  // get the main service to kick of the application
+  angular.injector([batchLogModule]).get('routeTemplateMonitor');
+
+ +Things to notice in this example: + +* The `batchLog` service depends on the built-in {@link api/ng.$timeout $timeout} and +{@link api/ng.$log $log} services, and allows messages to be logged into the +`console.log` in batches. +* The `routeTemplateMonitor` service depends on the built-in {@link api/ngRoute.$route +$route} service as well as our custom `batchLog` service. +* Both of our services use the factory function signature and array notation for inject annotations +to declare their dependencies. It is important that the order of the string identifiers in the array +is the same as the order of argument names in the signature of the factory function. Unless the +dependencies are inferred from the function signature, it is this array with IDs and their order +that the injector uses to determine which services and in which order to inject. + + +## Related Topics + +* {@link dev_guide.services.understanding_services Understanding Angular Services} +* {@link dev_guide.services.creating_services Creating Angular Services} +* {@link dev_guide.services.injecting_controllers Injecting Services Into Controllers } +* {@link dev_guide.services.testing_services Testing Angular Services} + + +## Related API + +* {@link api/ng Angular Service API} +* {@link api/angular.injector Angular Injector API} diff --git a/docs/content-ko/guide/dev_guide.services.ngdoc b/docs/content-ko/guide/dev_guide.services.ngdoc new file mode 100644 index 000000000000..725e01e3eaf4 --- /dev/null +++ b/docs/content-ko/guide/dev_guide.services.ngdoc @@ -0,0 +1,20 @@ +@ngdoc overview +@name Developer Guide: Angular Services +@description + +Services are a feature that Angular brings to client-side web apps from the server side, where +services have been commonly used for a long time. Services in Angular apps are substitutable +objects that are wired together using {@link di dependency injection (DI)}. + + +## Related Topics + +* {@link dev_guide.services.understanding_services Understanding Angular Services} +* {@link dev_guide.services.creating_services Creating Angular Services} +* {@link dev_guide.services.managing_dependencies Managing Service Dependencies} +* {@link dev_guide.services.injecting_controllers Injecting Services Into Controllers} +* {@link dev_guide.services.testing_services Testing Angular Services} + +## Related API + +* {@link api/ng Angular Service API} diff --git a/docs/content-ko/guide/dev_guide.services.testing_services.ngdoc b/docs/content-ko/guide/dev_guide.services.testing_services.ngdoc new file mode 100644 index 000000000000..6e0bbacebdc6 --- /dev/null +++ b/docs/content-ko/guide/dev_guide.services.testing_services.ngdoc @@ -0,0 +1,62 @@ +@ngdoc overview +@name Developer Guide: Angular Services: Testing Angular Services +@description + +The following is a unit test for the 'notify' service in the 'Dependencies' example in {@link +dev_guide.services.creating_services Creating Angular Services}. The unit test example uses Jasmine +spy (mock) instead of a real browser alert. + +
+var mock, notify;
+
+beforeEach(function() {
+  mock = {alert: jasmine.createSpy()};
+
+  module(function($provide) {
+    $provide.value('$window', mock);
+  });
+
+  inject(function($injector) {
+    notify = $injector.get('notify');
+  });
+});
+
+it('should not alert first two notifications', function() {
+  notify('one');
+  notify('two');
+
+  expect(mock.alert).not.toHaveBeenCalled();
+});
+
+it('should alert all after third notification', function() {
+  notify('one');
+  notify('two');
+  notify('three');
+
+  expect(mock.alert).toHaveBeenCalledWith("one\ntwo\nthree");
+});
+
+it('should clear messages after alert', function() {
+  notify('one');
+  notify('two');
+  notify('third');
+  notify('more');
+  notify('two');
+  notify('third');
+
+  expect(mock.alert.callCount).toEqual(2);
+  expect(mock.alert.mostRecentCall.args).toEqual(["more\ntwo\nthird"]);
+});
+
+ + +## Related Topics + +* {@link dev_guide.services.understanding_services Understanding Angular Services} +* {@link dev_guide.services.creating_services Creating Angular Services} +* {@link dev_guide.services.managing_dependencies Managing Service Dependencies} +* {@link dev_guide.services.injecting_controllers Injecting Services Into Controllers} + +## Related API + +* {@link api/ng Angular Service API} diff --git a/docs/content-ko/guide/dev_guide.services.understanding_services.ngdoc b/docs/content-ko/guide/dev_guide.services.understanding_services.ngdoc new file mode 100644 index 000000000000..aebd2fa569ef --- /dev/null +++ b/docs/content-ko/guide/dev_guide.services.understanding_services.ngdoc @@ -0,0 +1,60 @@ +@ngdoc overview +@name Developer Guide: Angular Services: Understanding Angular Services +@description + +## What are Angular Services? + +Angular services are singletons objects or functions that carry out specific tasks common to web apps. +Angular has a number of built in services, such as the {@link api/ng.$http $http service}, which +provides access to the browser's `XMLHttpRequest` object for making requests to a server. Like other core +Angular variables and identifiers, the built-in services always start with `$` (such as `$http` mentioned +above). You can also create your own custom services. + +## Using a Service + +To use an Angular service, you identify it as a dependency for the component (controller, service, +filter or directive) that depends on the service. Angular's dependency injection subsystem takes +care of the rest. The Angular injector subsystem is in charge of service instantiation, resolution +of dependencies, and provision of dependencies to components as requested. + +Angular injects dependencies using +{@link http://misko.hevery.com/2009/02/19/constructor-injection-vs-setter-injection/ "constructor" injection}. +The dependency is passed to the component's factory/constructor function. Because JavaScript is a dynamically +typed language, Angular's dependency injection subsystem cannot use static types to identify service +dependencies. For this reason a component must, explicitly, define its dependencies by using one of the +{@link di injection annotation} methods. For example, by providing a `$inject` property: + + var MyController = function($location) { ... }; + MyController.$inject = ['$location']; + myModule.controller('MyController', MyController); + +Or by providing an "inline" injection annotation: + + var myService = function($http) { ... }; + myModule.factory('myService', ['$http', myService]); + +## Defining a Service + +Application developers are free to define their own services by registering their name, and **service +factory function**, in Angular modules. + +The purpose of the **service factory function** is to generate the single object, or function, that +represents the service to the rest of the application. That object, or function, will then be +injected into any component (controller, service, filter or directive) that specifies a dependency +on the service. + +Angular factory functions are executed lazily. That is, they are only executed when needed +to satisfy a dependency, and are then executed exactly once for each service. Everything that is +dependent on this service gets a reference to the single instance generated by the service factory. + +## Related Topics + +* {@link di About Angular Dependency Injection} +* {@link dev_guide.services.creating_services Creating Angular Services} +* {@link dev_guide.services.managing_dependencies Managing Service Dependencies} +* {@link dev_guide.services.testing_services Testing Angular Services} + +## Related API + +* {@link api/ng Angular Service API} +* {@link api/angular.injector Injector API} diff --git a/docs/content-ko/guide/dev_guide.templates.css-styling.ngdoc b/docs/content-ko/guide/dev_guide.templates.css-styling.ngdoc new file mode 100644 index 000000000000..38962fd2333f --- /dev/null +++ b/docs/content-ko/guide/dev_guide.templates.css-styling.ngdoc @@ -0,0 +1,31 @@ +@ngdoc overview +@name Developer Guide: Templates: Working With CSS in Angular +@description + + +Angular sets these CSS classes. It is up to your application to provide useful styling. + +# CSS classes used by angular + +* `ng-scope` + - **Usage:** angular applies this class to any element that where a new {@link api/ng.$rootScope.Scope scope} + is defined. (see {@link guide/scope scope} guide for more information about scopes) + +* `ng-binding` + - **Usage:** angular applies this class to any element that is attached to a data binding, via `ng-bind` or + {{}} curly braces, for example. (see {@link guide/databinding databinding} guide) + +* `ng-invalid`, `ng-valid` + - **Usage:** angular applies this class to an input widget element if that element's input does + not pass validation. (see {@link api/ng.directive:input input} directive) + +* `ng-pristine`, `ng-dirty` + - **Usage:** angular {@link api/ng.directive:input input} directive applies `ng-pristine` class + to a new input widget element which did not have user interaction. Once the user interacts with + the input widget the class is changed to `ng-dirty`. + + +## Related Topics + +* {@link templates Angular Templates} +* {@link forms Angular Forms} diff --git a/docs/content-ko/guide/dev_guide.unit-testing.ngdoc b/docs/content-ko/guide/dev_guide.unit-testing.ngdoc new file mode 100644 index 000000000000..47c33d3f05e9 --- /dev/null +++ b/docs/content-ko/guide/dev_guide.unit-testing.ngdoc @@ -0,0 +1,341 @@ +@ngdoc overview +@name Developer Guide: Unit Testing +@description + +JavaScript is a dynamically typed language which comes with great power of expression, but it also +comes with almost no help from the compiler. For this reason we feel very strongly that any code +written in JavaScript needs to come with a strong set of tests. We have built many features into +Angular which makes testing your Angular applications easy. So there is no excuse for not testing. + +# It is all about NOT mixing concerns + +Unit testing as the name implies is about testing individual units of code. Unit tests try to +answer questions such as "Did I think about the logic correctly?" or "Does the sort function order the list +in the right order?" + +In order to answer such question it is very important that we can isolate the unit of code under test. +That is because when we are testing the sort function we don't want to be forced into creating +related pieces such as the DOM elements, or making any XHR calls in getting the data to sort. + +While +this may seem obvious it usually is very difficult to be able to call an individual function on a +typical project. The reason is that the developers often mix concerns, and they end up with a +piece of code which does everything. It reads the data from XHR, it sorts it and then it +manipulates the DOM. + +With Angular we try to make it easy for you to do the right thing, and so we +provide dependency injection for your XHR (which you can mock out) and we created abstraction which +allow you to sort your model without having to resort to manipulating the DOM. So that in the end, +it is easy to write a sort function which sorts some data, so that your test can create a data set, +apply the function, and assert that the resulting model is in the correct order. The test does not +have to wait for XHR, or create the right kind of DOM, or assert that your function has mutated the +DOM in the right way. + +## With great power comes great responsibility + +Angular is written with testability in mind, but it still requires that you +do the right thing. We tried to make the right thing easy, but Angular is not magic, which means if +you don't follow these guidelines you may very well end up with an untestable application. + +## Dependency Injection +There are several ways in which you can get a hold of a dependency: +1. You could create it using the `new` operator. +2. You could look for it in a well known place, also known as global singleton. +3. You could ask a registry (also known as service registry) for it. (But how do you get a hold of +the registry? Most likely by looking it up in a well known place. See #2) +4. You could expect that it be handed to you. + +Out of the four options in the list above, only the last one is testable. Let's look at why: + +### Using the `new` operator + +While there is nothing wrong with the `new` operator fundamentally the issue is that calling a new +on a constructor permanently binds the call site to the type. For example lets say that we are +trying to instantiate an `XHR` so that we can get some data from the server. + +
+function MyClass() {
+  this.doWork = function() {
+    var xhr = new XHR();
+    xhr.open(method, url, true);
+    xhr.onreadystatechange = function() {...}
+    xhr.send();
+  }
+}
+
+ +The issue becomes that in tests, we would very much like to instantiate a `MockXHR` which would +allow us to return fake data and simulate network failures. By calling `new XHR()` we are +permanently bound to the actual XHR, and there is no good way to replace it. Yes there is monkey +patching. That is a bad idea for many reasons which are outside the scope of this document. + +The class above is hard to test since we have to resort to monkey patching: +
+var oldXHR = XHR;
+XHR = function MockXHR() {};
+var myClass = new MyClass();
+myClass.doWork();
+// assert that MockXHR got called with the right arguments
+XHR = oldXHR; // if you forget this bad things will happen
+
+ + +### Global look-up: +Another way to approach the problem is to look for the service in a well known location. + +
+function MyClass() {
+  this.doWork = function() {
+    global.xhr({
+      method:'...',
+      url:'...',
+      complete:function(response){ ... }
+    })
+  }
+}
+
+ +While no new instance of the dependency is being created, it is fundamentally the same as `new`, in +that there is no good way to intercept the call to `global.xhr` for testing purposes, other then +through monkey patching. The basic issue for testing is that a global variable needs to be mutated in +order to replace it with call to a mock method. For further explanation why this is bad see: {@link +http://misko.hevery.com/code-reviewers-guide/flaw-brittle-global-state-singletons/ Brittle Global +State & Singletons} + +The class above is hard to test since we have to change global state: +
+var oldXHR = global.xhr;
+global.xhr = function mockXHR() {};
+var myClass = new MyClass();
+myClass.doWork();
+// assert that mockXHR got called with the right arguments
+global.xhr = oldXHR; // if you forget this bad things will happen
+
+ + +### Service Registry: + +It may seem as that this can be solved by having a registry for all of the services, and then +having the tests replace the services as needed. + +
+function MyClass() {
+  var serviceRegistry = ????;
+  this.doWork = function() {
+    var xhr = serviceRegistry.get('xhr');
+    xhr({
+      method:'...',
+      url:'...',
+      complete:function(response){ ... }
+    })
+}
+
+ +However, where does the serviceRegistry come from? if it is: +* `new`-ed up, the test has no chance to reset the services for testing +* global look-up, then the service returned is global as well (but resetting is easier, since +there is only one global variable to be reset). + +The class above is hard to test since we have to change global state: +
+var oldServiceLocator = global.serviceLocator;
+global.serviceLocator.set('xhr', function mockXHR() {});
+var myClass = new MyClass();
+myClass.doWork();
+// assert that mockXHR got called with the right arguments
+global.serviceLocator = oldServiceLocator; // if you forget this bad things will happen
+
+ + +### Passing in Dependencies: +Lastly the dependency can be passed in. + +
+function MyClass(xhr) {
+  this.doWork = function() {
+    xhr({
+      method:'...',
+      url:'...',
+      complete:function(response){ ... }
+    })
+}
+
+ +This is the preferred way since the code makes no assumptions as to where the `xhr` comes from, +rather that whoever created the class was responsible for passing it in. Since the creator of the +class should be different code than the user of the class, it separates the responsibility of +creation from the logic, and that is what dependency-injection is in a nutshell. + +The class above is very testable, since in the test we can write: +
+function xhrMock(args) {...}
+var myClass = new MyClass(xhrMock);
+myClass.doWork();
+// assert that xhrMock got called with the right arguments
+
+ +Notice that no global variables were harmed in the writing of this test. + +Angular comes with {@link di dependency injection} built in which makes the right thing +easy to do, but you still need to do it if you wish to take advantage of the testability story. + +## Controllers +What makes each application unique is its logic, which is what we would like to test. If the logic +for your application is mixed in with DOM manipulation, it will be hard to test as in the example +below: + +
+function PasswordCtrl() {
+  // get references to DOM elements
+  var msg = $('.ex1 span');
+  var input = $('.ex1 input');
+  var strength;
+
+  this.grade = function() {
+    msg.removeClass(strength);
+    var pwd = input.val();
+    password.text(pwd);
+    if (pwd.length > 8) {
+      strength = 'strong';
+    } else if (pwd.length > 3) {
+      strength = 'medium';
+    } else {
+      strength = 'weak';
+    }
+    msg
+     .addClass(strength)
+     .text(strength);
+  }
+}
+
+ +The code above is problematic from a testability point of view, since it requires your test to have the right kind +of DOM present when the code executes. The test would look like this: + +
+var input = $('');
+var span = $('');
+$('body').html('
') + .find('div') + .append(input) + .append(span); +var pc = new PasswordCtrl(); +input.val('abc'); +pc.grade(); +expect(span.text()).toEqual('weak'); +$('body').html(''); +
+ +In angular the controllers are strictly separated from the DOM manipulation logic which results in +a much easier testability story as can be seen in this example: + +
+function PasswordCtrl($scope) {
+  $scope.password = '';
+  $scope.grade = function() {
+    var size = $scope.password.length;
+    if (size > 8) {
+      $scope.strength = 'strong';
+    } else if (size > 3) {
+      $scope.strength = 'medium';
+    } else {
+      $scope.strength = 'weak';
+    }
+  };
+}
+
+ +and the test is straight forward + +
+var $scope = {};
+var pc = $controller('PasswordCtrl', { $scope: $scope });
+$scope.password = 'abc';
+$scope.grade();
+expect($scope.strength).toEqual('weak');
+
+ +Notice that the test is not only much shorter but it is easier to follow what is going on. We say +that such a test tells a story, rather then asserting random bits which don't seem to be related. + +## Filters +{@link api/ng.$filterProvider Filters} are functions which transform the data into user readable +format. They are important because they remove the formatting responsibility from the application +logic, further simplifying the application logic. + +
+myModule.filter('length', function() {
+  return function(text){
+    return (''+(text||'')).length;
+  }
+});
+
+var length = $filter('length');
+expect(length(null)).toEqual(0);
+expect(length('abc')).toEqual(3);
+
+ +## Directives +Directives in angular are responsible for encapsulating complex functionality within custom HTML tags, +attributes, classes or comments. Unit tests are very important for directives because the components +you create with directives may be used throughout your application and in many different contexts. + +### Simple HTML Element Directive + +Lets start with an angular app with no dependencies. + +
+var app = angular.module('myApp', []);
+
+ +Now we can add a directive to our app. + +
+app.directive('aGreatEye', function () {
+    return {
+        restrict: 'E',
+        replace:  true,
+        template: '

lidless, wreathed in flame, {{1 + 1}} times

' + }; +}); +
+ +This directive is used as a tag ``. It replaces the entire tag with the +template `

lidless, wreathed in flame, {{1 + 1}} times

`. Now we are going to write a jasmine unit test to +verify this functionality. Note that the expression `{{1 + 1}}` times will also be evaluated in the rendered content. + +
+describe('Unit testing great quotes', function() {
+    var $compile;
+    var $rootScope;
+
+    // Load the myApp module, which contains the directive
+    beforeEach(module('myApp'));
+
+    // Store references to $rootScope and $compile
+    // so they are available to all tests in this describe block
+    beforeEach(inject(function(_$compile_, _$rootScope_){
+      // The injector unwraps the underscores (_) from around the parameter names when matching
+      $compile = _$compile_;
+      $rootScope = _$rootScope_;
+    }));
+    
+    it('Replaces the element with the appropriate content', function() {
+        // Compile a piece of HTML containing the directive
+        var element = $compile("")($rootScope);
+        // fire all the watches, so the scope expression {{1 + 1}} will be evaluated
+        $rootScope.$digest();
+        // Check that the compiled element contains the templated content
+        expect(element.html()).toContain("lidless, wreathed in flame, 2 times");
+    });
+});
+
+ +We inject the $compile service and $rootScope before each jasmine test. The $compile service is used +to render the aGreatEye directive. After rendering the directive we ensure that the directive has +replaced the content and "lidless, wreathed in flame, 2 times" is present. + + +## Sample project +See the {@link https://github.com/angular/angular-seed angular-seed} project for an example. + diff --git a/docs/content-ko/guide/di.ngdoc b/docs/content-ko/guide/di.ngdoc new file mode 100644 index 000000000000..f694ea12a358 --- /dev/null +++ b/docs/content-ko/guide/di.ngdoc @@ -0,0 +1,241 @@ +@ngdoc overview +@name Developer Guide: Dependency Injection +@description + +# Dependency Injection + +Dependency Injection (DI) is a software design pattern that deals with how code gets hold of its +dependencies. + +For in-depth discussion about DI, see {@link http://en.wikipedia.org/wiki/Dependency_injection +Dependency Injection} at Wikipedia, {@link http://martinfowler.com/articles/injection.html +Inversion of Control} by Martin Fowler, or read about DI in your favorite software design pattern +book. + +## DI in a nutshell + +There are only three ways an object or a function can get a hold of its dependencies: + + 1. The dependency can be created, typically using the `new` operator. + + 2. The dependency can be looked up by referring to a global variable. + + 3. The dependency can be passed in to where it is needed. + + +The first two options of creating or looking up dependencies are not optimal because they hard +code the dependency. This makes it difficult, if not impossible, to modify the dependencies. +This is especially problematic in tests, where it is often desirable to provide mock dependencies +for test isolation. + +The third option is the most viable, since it removes the responsibility of locating the +dependency from the component. The dependency is simply handed to the component. + +
+  function SomeClass(greeter) {
+    this.greeter = greeter;
+  }
+  
+  SomeClass.prototype.doSomething = function(name) {
+    this.greeter.greet(name);
+  }
+
+ +In the above example `SomeClass` is not concerned with locating the `greeter` dependency, it +is simply handed the `greeter` at runtime. + +This is desirable, but it puts the responsibility of getting hold of the dependency on the +code that constructs `SomeClass`. + + + +To manage the responsibility of dependency creation, each Angular application has an {@link +api/angular.injector injector}. The injector is a service locator that is responsible for +construction and lookup of dependencies. + +Here is an example of using the injector service: + +
+  // Provide the wiring information in a module
+  angular.module('myModule', []).
+  
+    // Teach the injector how to build a 'greeter'
+    // Notice that greeter itself is dependent on '$window'
+    factory('greeter', function($window) {
+      // This is a factory function, and is responsible for 
+      // creating the 'greet' service.
+      return {
+        greet: function(text) {
+          $window.alert(text);
+        }
+      };
+    });
+
+  // New injector is created from the module. 
+  // (This is usually done automatically by angular bootstrap)
+  var injector = angular.injector(['myModule', 'ng']);
+  
+  // Request any dependency from the injector
+  var greeter = injector.get('greeter');
+
+ +Asking for dependencies solves the issue of hard coding, but it also means that the injector needs +to be passed throughout the application. Passing the injector breaks the {@link +http://en.wikipedia.org/wiki/Law_of_Demeter Law of Demeter}. To remedy this, we turn the +dependency lookup responsibility to the injector by declaring the dependencies as in this example: + +
+  
+  
+ +
+
+
+  // And this controller definition
+  function MyController($scope, greeter) {
+    $scope.sayHello = function() {
+      greeter.greet('Hello World');
+    };
+  }
+  
+  // The 'ng-controller' directive does this behind the scenes
+  injector.instantiate(MyController);
+
+ +Notice that by having the `ng-controller` instantiate the class, it can satisfy all of the +dependencies of `MyController` without the controller ever knowing about the injector. This is +the best outcome. The application code simply asks for the dependencies it needs, without having to +deal with the injector. This setup does not break the Law of Demeter. + +## Dependency Annotation + +How does the injector know what service needs to be injected? + +The application developer needs to provide annotation information that the injector uses in order +to resolve the dependencies. Throughout Angular, certain API functions are invoked using the +injector, as per the API documentation. The injector needs to know what services to inject into +the function. Below are three equivalent ways of annotating your code with service name +information. These can be used interchangeably as you see fit and are equivalent. + +### Inferring Dependencies + +The simplest way to get hold of the dependencies, is to assume that the function parameter names +are the names of the dependencies. + +
+  function MyController($scope, greeter) {
+    ...
+  }
+
+ +Given a function the injector can infer the names of the service to inject by examining the +function declaration and extracting the parameter names. In the above example `$scope`, and +`greeter` are two services which need to be injected into the function. + +While straightforward, this method will not work with JavaScript minifiers/obfuscators as they +rename the method parameter names. This makes this way of annotating only useful for {@link +http://www.pretotyping.org/ pretotyping}, and demo applications. + +### `$inject` Annotation + +To allow the minifers to rename the function parameters and still be able to inject right services +the function needs to be annotated with the `$inject` property. The `$inject` property is an array +of service names to inject. + +
+  var MyController = function(renamed$scope, renamedGreeter) {
+    ...
+  }
+  MyController.$inject = ['$scope', 'greeter'];
+
+ +In this scenario the ordering of the values in the '$inject' array must match the ordering of the arguments to inject. +Using above code snippet as an example, '$scope' will be injected into 'renamed$scope' and 'greeter' into 'renamedGreeter'. +Care must be taken that the `$inject` annotation is kept in sync with the actual arguments in the +function declaration. + +This method of annotation is useful for controller declarations since it assigns the annotation +information with the function. + +### Inline Annotation + +Sometimes using the `$inject` annotation style is not convenient such as when annotating +directives. + +For example: + +
+  someModule.factory('greeter', function($window) {
+    ...
+  });
+
+ +Results in code bloat due to needing a temporary variable: + +
+  var greeterFactory = function(renamed$window) {
+    ...
+  };
+  
+  greeterFactory.$inject = ['$window'];
+  
+  someModule.factory('greeter', greeterFactory);
+
+ +For this reason the third annotation style is provided as well. + +
+  someModule.factory('greeter', ['$window', function(renamed$window) {
+    ...
+  }]);
+
+ +Keep in mind that all of the annotation styles are equivalent and can be used anywhere in Angular +where injection is supported. + +## Where can I use DI? + +DI is pervasive throughout Angular. It is typically used in controllers and factory methods. + +### DI in controllers + +Controllers are classes which are responsible for application behavior. The recommended way of +declaring controllers is using the array notation: + +
+  someModule.controller('MyController', ['$scope', 'dep1', 'dep2', function($scope, dep1, dep2) {
+    ...
+    $scope.aMethod = function() {
+      ...
+    }
+    ...
+  }]);
+
+ +This avoids the creation of global functions for controllers and also protects against minification. + + +### Factory methods + +Factory methods are responsible for creating most objects in Angular. Examples are directives, +services, and filters. The factory methods are registered with the module, and the recommended way +of declaring factories is: + +
+  angular.module('myModule', []).
+    config(['depProvider', function(depProvider){
+      ...
+    }]).
+    factory('serviceId', ['depService', function(depService) {
+      ...
+    }]).
+    directive('directiveName', ['depService', function(depService) {
+      ...
+    }]).
+    filter('filterName', ['depService', function(depService) {
+      ...
+    }]).
+    run(['depService', function(depService) {
+      ...
+    }]);
+
diff --git a/docs/content-ko/guide/directive.ngdoc b/docs/content-ko/guide/directive.ngdoc new file mode 100644 index 000000000000..507910e414fc --- /dev/null +++ b/docs/content-ko/guide/directive.ngdoc @@ -0,0 +1,915 @@ +@ngdoc overview +@name Directives +@description + +# Creating Custom Directives + +
+**Note:** this guide is targeted towards developers who are already familiar with AngularJS basics. +If you're just getting started, we recommend the {@link tutorial/ tutorial} first. +If you're looking for the **directives API**, we recently moved it to {@link api/ng.$compile `$compile`}. +
+ + +This document explains when you'd want to create your own directives in your AngularJS app, and +how to implement them. + + +## What are Directives? + +At a high level, directives are markers on a DOM element (such as an attribute, element +name, or CSS class) that tell AngularJS's **HTML compiler** ({@link api/ng.$compile `$compile`}) to +attach a specified behavior to that DOM element or even transform the DOM element and its children. + +Angular comes with a set of these directives built-in, like `ngBind`, `ngModel`, and `ngView`. +Much like you create controllers and services, you can create your own directives for Angular to use. +When Angular {@link guide/bootstrap bootstraps} your application, the +{@link guide/compiler HTML compiler} traverses the DOM matching directives against the DOM elements. + +
+**What does it mean to "compile" an HTML template?** + +For AngularJS, "compilation" means attaching event listeners to the HTML to make it interactive. +The reason we use the term "compile" is that the recursive process of attaching directives +mirrors the process of compiling source code in +{@link http://en.wikipedia.org/wiki/Compiled_languages compiled programming languages}. +
+ + +## Matching Directives + +Before we can write a directive, we need to know how Angular's {@link guide/compiler HTML compiler} +determines when to use a given directive. + +In the following example, we say that the `` element **matches** the `ngModel` directive. + +```javascript + +``` + +The following also **matches** `ngModel`: + +```javascript + +``` + +Angular **normalizes** an element's tag and attribute name to determine which elements match which +directives. We typically refer to directives by their case-sensitive +{@link http://en.wikipedia.org/wiki/CamelCase camelCase} **normalized** name (e.g. `ngModel`). +However, in the DOM, we refer to directives by case-insensitive forms, typically using +{@link http://en.wikipedia.org/wiki/Letter_case#Computers dash-delimited} attributes on DOM elements +(e.g. `ng-model`). + +The **normalization** process is as follows: + +1. Strip `x-` and `data-` from the front of the element/attributes. +2. Convert the `:`, `-`, or `_`-delimited name to `camelCase`. + +Here are some equivalent examples of elements that match `ngBind`: + + + + angular.module('docsBindExample', []) + .controller('Ctrl1', function Ctrl1($scope) { + $scope.name = 'Max Karl Ernst Ludwig Planck (April 23, 1858 – October 4, 1947)'; + }); + + +
+ Hello
+
+
+
+
+
+
+
+ + it('should show off bindings', function() { + expect(element('div[ng-controller="Ctrl1"] span[ng-bind]').text()) + .toBe('Max Karl Ernst Ludwig Planck (April 23, 1858 – October 4, 1947)'); + }); + +
+ +
+**Best Practice:** Prefer using the dash-delimited format (e.g. `ng-bind` for `ngBind`). +If you want to use an HTML validating tool, you can instead use the `data`-prefixed version (e.g. +`data-ng-bind` for `ngBind`). +The other forms shown above are accepted for legacy reasons but we advise you to avoid them. +
+ +`$compile` can match directives based on element names, attributes, class names, as well as comments. + +All of the Angular-provided directives match attribute name, tag name, comments, or class name. +The following demonstrates the various ways a directive (`myDir` in this case) can be referenced +from within a template: + +```html + + + + +``` + +
+**Best Practice:** Prefer using directives via tag name and attributes over comment and class names. +Doing so generally makes it easier to determine what directives a given element matches. +
+ +
+**Best Practice:** Comment directives were commonly used in places where the DOM API limits the +ability to create directives that spanned multiple elements (e.g. inside `` elements). +AngularJS 1.2 introduces {@link api/ng.directive:ngRepeat `ng-repeat-start` and `ng-repeat-end`} +as a better solution to this problem. Developers are encouraged to use this over custom comment +directives when possible. + + + + +### Text and attribute bindings + +During the compilation process the {@link api/ng.$compile compiler} matches text and attributes +using the {@link api/ng.$interpolate $interpolate} service to see if they contain embedded +expressions. These expressions are registered as {@link api/ng.$rootScope.Scope#methods_$watch watches} +and will update as part of normal {@link api/ng.$rootScope.Scope#methods_$digest digest} cycle. An +example of interpolation is shown below: + +```html +Hello {{username}}! +``` + + +### `ngAttr` attribute bindings + +Web browsers are sometimes picky about what values they consider valid for attributes. + +For example, considering this template: + +```html + + + +``` + +We would expect Angular to be able to bind to this, but when we check the console we see +something like `Error: Invalid value for attribute cx="{{cx}}"`. Because of the SVG DOM API's +restrictions, you cannot simply write `cx="{{cx}}"`. + +With `ng-attr-cx` you can work around this problem. + +If an attribute with a binding is prefixed with the `ngAttr` prefix (denormalized as `ng-attr-`) +then during the binding will be applied to the corresponding unprefixed attribute. This allows +you to bind to attributes that would otherwise be eagerly processed by browsers +(e.g. an SVG element's `circle[cx]` attributes). + +For example, we could fix the example above by instead writing: + +```html + + + +``` + + +## Creating Directives + +First let's talk about the API for registering directives. Much like controllers, directives are +registered on modules. To register a directive, you use the `module.directive` API. +`module.directive` takes the +{@link guide/directive#creating-custom-directives_matching-directives normalized} directive name +followed by a **factory function.** This factory function should return an object with the different +options to tell `$compile` how the directive should behave when matched. + + +The factory function is invoked only once when the +{@link api/ng.$compile compiler} matches the directive for the first time. You can perform any +initialization work here. The function is invoked using +{@link api/AUTO.$injector#methods_invoke $injector.invoke} which makes it injectable just like a +controller. + +
+**Best Practice:** Prefer using the definition object over returning a function. +
+ + +We'll go over a few common examples of directives, then dive deep into the different options +and compilation process. + +
+**Best Practice:** In order to avoid collisions with some future standard, it's best to prefix your own +directive names. For instance, if you created a `` directive, it would be problematic if HTML7 +introduced the same element. A two or three letter prefix (e.g. `btfCarousel`) works well. Similarly, do +not prefix your own directives with `ng` or they might conflict with directives included in a future +version of Angular. +
+ +For the following examples, we'll use the prefix `my` (e.g. `myCustomer`). + + +### Template-expanding directive + +Let's say you have a chunk of your template that represents a customer's information. This template +is repeated many times in your code. When you change it in one place, you have to change it in +several others. This is a good opportunity to use a directive to simplify your template. + +Let's create a directive that simply replaces its contents with a static template: + + + + angular.module('docsSimpleDirective', []) + .controller('Ctrl', function($scope) { + $scope.customer = { + name: 'Naomi', + address: '1600 Amphitheatre' + }; + }) + .directive('myCustomer', function() { + return { + template: 'Name: {{customer.name}} Address: {{customer.address}}' + }; + }); + + +
+
+
+
+
+ +Notice that we have bindings in this directive. After `$compile` compiles and links +`
`, it will try to match directives on the element's children. This means you +can compose directives of other directives. We'll see how to do that in +{@link guide/directive#creating-custom-directives_demo_creating-directives-that-communicate an example} +below. + +In the example above we in-lined the value of the `template` option, but this will become annoying +as the size of your template grows. + +
+**Best Practice:** Unless your template is very small, it's typically better to break it apart into +its own HTML file and load it with the `templateUrl` option. +
+ +If you are familiar with `ngInclude`, `templateUrl` works just like it. Here's the same example +using `templateUrl` instead: + + + + angular.module('docsTemplateUrlDirective', []) + .controller('Ctrl', function($scope) { + $scope.customer = { + name: 'Naomi', + address: '1600 Amphitheatre' + }; + }) + .directive('myCustomer', function() { + return { + templateUrl: 'my-customer.html' + }; + }); + + +
+
+
+
+ + Name: {{customer.name}} Address: {{customer.address}} + +
+ +Great! But what if we wanted to have our directive match the tag name `` instead? +If we simply put a `` element into the HMTL, it doesn't work. + +
+**Note:** When you create a directive, it is restricted to attribute only by default. In order to +create directives that are triggered by element name, you need to use the `restrict` option. +
+ +The `restrict` option is typically set to: + +* `'A'` - only matches attribute name +* `'E'` - only matches element name +* `'AE'` - matches either attribute or element name + +Let's change our directive to use `restrict: 'E'`: + + + + angular.module('docsRestrictDirective', []) + .controller('Ctrl', function($scope) { + $scope.customer = { + name: 'Naomi', + address: '1600 Amphitheatre' + }; + }) + .directive('myCustomer', function() { + return { + restrict: 'E', + templateUrl: 'my-customer.html' + }; + }); + + + +
+ +
+
+ + + Name: {{customer.name}} Address: {{customer.address}} + +
+ +For more on the +{@link api/ng.$compile#description_comprehensive-directive-api_directive-definition-object `restrict`} +property, see the +{@link api/ng.$compile#description_comprehensive-directive-api_directive-definition-object API docs}. + +
+**When should I use an attribute versus an element?** + +Use an element when you are creating a component that is in control of the template. The common case +for this is when you are creating a Domain-Specific Language for parts of your template. + +Use an attribute when you are decorating an existing element with new functionality. +
+ +Using an element for the `myCustomer` directive is clearly the right choice because you're not +decorating an element with some "customer" behavior; you're defining the core behavior of the +element as a customer component. + + + +### Isolating the Scope of a Directive + +Our `myCustomer` directive above is great, but it has a fatal flaw. We can only use it once within a +given scope. + +In its current implementation, we'd need to create a different controller each time In order to +re-use such a directive: + + + + angular.module('docsScopeProblemExample', []) + .controller('NaomiCtrl', function($scope) { + $scope.customer = { + name: 'Naomi', + address: '1600 Amphitheatre' + }; + }) + .controller('IgorCtrl', function($scope) { + $scope.customer = { + name: 'Igor', + address: '123 Somewhere' + }; + }) + .directive('myCustomer', function() { + return { + restrict: 'E', + templateUrl: 'my-customer.html' + }; + }); + + +
+ +
+
+
+ +
+
+ + Name: {{customer.name}} Address: {{customer.address}} + +
+ +This is clearly not a great solution. + +What we want to be able to do is separate the scope inside a directive from the scope +outside, and then map the outer scope to a directive's inner scope. We can do this by creating what +we call an **isolate scope**. To do this, we can use a directive's `scope` option: + + + + angular.module('docsIsolateScopeDirective', []) + .controller('Ctrl', function($scope) { + $scope.naomi = { name: 'Naomi', address: '1600 Amphitheatre' }; + $scope.igor = { name: 'Igor', address: '123 Somewhere' }; + }) + .directive('myCustomer', function() { + return { + restrict: 'E', + scope: { + customer: '=customer' + }, + templateUrl: 'my-customer.html' + }; + }); + + +
+ +
+ +
+
+ + Name: {{customer.name}} Address: {{customer.address}} + +
+ +Looking at `index.html`, the first `` element binds the inner scope's `customer` to +`naomi`, which we have exposed on our controller's scope. The second binds `customer` to `igor`. + +Let's take a closer look at the scope option: + +```javascript +//... +scope: { + customer: '=customer' +}, +//... +``` + +The property name (`customer`) corresponds to the variable name of the `myCustomer` directive's +isolated scope. The value of the property (`=customer`) tells `$compile` to bind to the `customer` +attribute. + +
+**Note:** These `=attr` attributes in the `scope` option of directives are normalized just like +directive names. To bind to the attribute in `
`, you'd specify a binding +of `=bindToThis`. +
+ +For cases where the attribute name is the same as the value you want to bind to inside the +directive's scope, you can use this shorthand syntax: + +```javascript +//... +scope: { + // same as '=customer' + customer: '=' +}, +//... +``` + +Besides making it possible to bind different data to the scope inside a directive, using an isolated +scope has another effect. + +We can show this by adding another property, `vojta`, to our scope and trying to access it from +within our directive's template: + + + + angular.module('docsIsolationExample', []) + .controller('Ctrl', function($scope) { + $scope.naomi = { name: 'Naomi', address: '1600 Amphitheatre' }; + + $scope.vojta = { name: 'Vojta', address: '3456 Somewhere Else' }; + }) + .directive('myCustomer', function() { + return { + restrict: 'E', + scope: { + customer: '=customer' + }, + templateUrl: 'my-customer-plus-vojta.html' + }; + }); + + +
+ +
+
+ + Name: {{customer.name}} Address: {{customer.address}} +
+ Name: {{vojta.name}} Address: {{vojta.address}} +
+
+ +Notice that `{{vojta.name}}` and `{{vojta.address}}` are empty, meaning they are undefined. +Although we defined `vojta` in the controller, it's not available within the directive. + +As the name suggests, the **isolate scope** of the directive isolates everything except models that +you've explicitly added to the `scope: {}` hash object. This is helpful when building reusable +components because it prevents a component from changing your model state except for the models +that you explicitly pass in. + +
+**Note:** Normally, a scope prototypically inherits from its parent. An isolated scope does not. +
+ +
+**Best Practice:** Use the `scope` option to create isolate scopes when making components that you +want to reuse throughout your app. +
+ + +### Creating a Directive that Manipulates the DOM + +In this example we will build a directive that displays the current time. +Once a second, it updates the DOM to reflect the current time. + +Directives that want to modify the DOM typically use the `link` option. +`link` takes a function with the following signature, `function link(scope, element, attrs) { ... }` +where: + +* `scope` is an Angular scope object. +* `element` is the jqLite-wrapped element that this directive matches. +* `attrs` is an object with the normalized attribute names and their corresponding values. + +In our `link` function, we want to update the displayed time once a second, or whenever a user +changes the time formatting string that our directive binds to. We also want to remove the timeout +if the directive is deleted so we don't introduce a memory leak. + + + + angular.module('docsTimeDirective', []) + .controller('Ctrl2', function($scope) { + $scope.format = 'M/d/yy h:mm:ss a'; + }) + .directive('myCurrentTime', function($timeout, dateFilter) { + + function link(scope, element, attrs) { + var format, + timeoutId; + + function updateTime() { + element.text(dateFilter(new Date(), format)); + } + + scope.$watch(attrs.myCurrentTime, function(value) { + format = value; + updateTime(); + }); + + function scheduleUpdate() { + // save the timeoutId for canceling + timeoutId = $timeout(function() { + updateTime(); // update DOM + scheduleUpdate(); // schedule the next update + }, 1000); + } + + element.on('$destroy', function() { + $timeout.cancel(timeoutId); + }); + + // start the UI update process. + scheduleUpdate(); + } + + return { + link: link + }; + }); + + +
+ Date format:
+ Current time is: +
+
+
+ +There are a couple of things to note here. +Just like the `module.controller` API, the function argument in `module.directive` is dependency +injected. Because of this, we can use `$timeout` and `dateFilter` inside our directive's `link` +function. + +We register an event `element.on('$destroy', ...)`. What fires this `$destroy` event? + +There are a few special events that AngularJS emits. When a DOM node that has been compiled +with Angular's compiler is destroyed, it emits a `$destroy` event. Similarly, when an AngularJS +scope is destroyed, it broadcasts a `$destroy` event to listening scopes. + +By listening to this event, you can remove event listeners that might cause memory leaks. +Listeners registered to scopes and elements are automatically cleaned up when they are destroyed, +but if you registered a listener on a service, or registered a listener on a DOM node that isn't +being deleted, you'll have to clean it up yourself or you risk introducing a memory leak. + +
+**Best Practice:** Directives should clean up after themselves. You can use +`element.on('$destroy', ...)` or `scope.$on('$destroy', ...)` to run a clean-up function when the +directive is removed. +
+ + +### Creating a Directive that Wraps Other Elements + +We've seen that you can pass in models to a directive using the isolate scope, but sometimes +it's desirable to be able to pass in an entire template rather than a string or an object. +Let's say that we want to create a "dialog box" component. The dialog box should be able to +wrap any arbitrary content. + +To do this, we need to use the `transclude` option. + + + + angular.module('docsTransclusionDirective', []) + .controller('Ctrl', function($scope) { + $scope.name = 'Tobias'; + }) + .directive('myDialog', function() { + return { + restrict: 'E', + transclude: true, + templateUrl: 'my-dialog.html' + }; + }); + + +
+ Check out the contents, {{name}}! +
+
+ +
+
+
+
+ +What does this `transclude` option do, exactly? `transclude` makes the contents of a directive with +this option have access to the scope **outside** of the directive rather than inside. + +To illustrate this, see the example below. Notice that we've added a `link` function in `script.js` +that redefines `name` as `Jeff`. What do you think the `{{name}}` binding will resolve to now? + + + + angular.module('docsTransclusionExample', []) + .controller('Ctrl', function($scope) { + $scope.name = 'Tobias'; + }) + .directive('myDialog', function() { + return { + restrict: 'E', + transclude: true, + scope: {}, + templateUrl: 'my-dialog.html', + link: function (scope, element) { + scope.name = 'Jeff'; + } + }; + }); + + +
+ Check out the contents, {{name}}! +
+
+ +
+
+
+
+ +Ordinarily, we would expect that `{{name}}` would be `Jeff`. However, we see in this example that +the `{{name}}` binding is still `Tobias`. + +The `transclude` option changes the way scopes are nested. It makes it so that the **contents** of a +transcluded directive have whatever scope is outside the directive, rather than whatever scope is on +the inside. In doing so, it gives the contents access to the outside scope. + +Note that if the directive did not create its own scope, then `scope` in `scope.name = 'Jeff';` would +reference the outside scope and we would see `Jeff` in the output. + +This behavior makes sense for a directive that wraps some content, because otherwise you'd have to +pass in each model you wanted to use separately. If you have to pass in each model that you want to +use, then you can't really have arbitrary contents, can you? + +
+**Best Practice:** only use `transclude: true` when you want to create a directive that wraps +arbitrary content. +
+ +Next, we want to add buttons to this dialog box, and allow someone using the directive to bind their +own behavior to it. + + + + angular.module('docsIsoFnBindExample', []) + .controller('Ctrl', function($scope, $timeout) { + $scope.name = 'Tobias'; + $scope.hideDialog = function () { + $scope.dialogIsHidden = true; + $timeout(function () { + $scope.dialogIsHidden = false; + }, 2000); + }; + }) + .directive('myDialog', function() { + return { + restrict: 'E', + transclude: true, + scope: { + 'close': '&onClose' + }, + templateUrl: 'my-dialog-close.html' + }; + }); + + +
+ + Check out the contents, {{name}}! + +
+
+ +
+ × +
+
+
+
+ +We want to run the function we pass by invoking it from the directive's scope, but have it run +in the context of the scope where its registered. + +We saw earlier how to use `=prop` in the `scope` option, but in the above example, we're using +`&prop` instead. `&` bindings expose a function to an isolated scope allowing the isolated scope +to invoke it, but maintaining the original scope of the function. So when a user clicks the +`x` in the dialog, it runs `Ctrl`'s `close` function. + +
+**Best Practice:** use `&prop` in the `scope` option when you want your directive +to expose an API for binding to behaviors. +
+ + +### Creating a Directive that Adds Event Listeners + +Previously, we used the `link` function to create a directive that manipulated its +DOM elements. Building upon that example, let's make a directive that reacts to events on +its elements. + +For instance, what if we wanted to create a directive that lets a user drag an +element? + + + + angular.module('dragModule', []). + directive('myDraggable', function($document) { + return function(scope, element, attr) { + var startX = 0, startY = 0, x = 0, y = 0; + + element.css({ + position: 'relative', + border: '1px solid red', + backgroundColor: 'lightgrey', + cursor: 'pointer' + }); + + element.on('mousedown', function(event) { + // Prevent default dragging of selected content + event.preventDefault(); + startX = event.pageX - x; + startY = event.pageY - y; + $document.on('mousemove', mousemove); + $document.on('mouseup', mouseup); + }); + + function mousemove(event) { + y = event.pageY - startY; + x = event.pageX - startX; + element.css({ + top: y + 'px', + left: x + 'px' + }); + } + + function mouseup() { + $document.unbind('mousemove', mousemove); + $document.unbind('mouseup', mouseup); + } + } + }); + + + Drag ME + + + + + +### Creating Directives that Communicate + +You can compose any directives by using them within templates. + +Sometimes, you want a component that's built from a combination of directives. + +Imagine you want to have a container with tabs in which the contents of the container correspond +to which tab is active. + + + + angular.module('docsTabsExample', []) + .directive('myTabs', function() { + return { + restrict: 'E', + transclude: true, + scope: {}, + controller: function($scope) { + var panes = $scope.panes = []; + + $scope.select = function(pane) { + angular.forEach(panes, function(pane) { + pane.selected = false; + }); + pane.selected = true; + }; + + this.addPane = function(pane) { + if (panes.length == 0) { + $scope.select(pane); + } + panes.push(pane); + }; + }, + templateUrl: 'my-tabs.html' + }; + }) + .directive('myPane', function() { + return { + require: '^myTabs', + restrict: 'E', + transclude: true, + scope: { + title: '@' + }, + link: function(scope, element, attrs, tabsCtrl) { + tabsCtrl.addPane(scope); + }, + templateUrl: 'my-pane.html' + }; + }); + + + + +

Hello

+

Lorem ipsum dolor sit amet

+
+ +

World

+ Mauris elementum elementum enim at suscipit. +

counter: {{i || 0}}

+
+
+
+ +
+ +
+
+
+ +
+
+
+
+ +The `myPane` directive has a `require` option with value `^myTabs`. When a directive uses this +option, `$compile` will throw an error unless the specified controller is found. The `^` prefix +means that this directive searches for the controller on its parents (without the `^` prefix, the +directive would look for the controller on just its own element). + +So where does this `myTabs` controller come from? Directives can specify controllers using +the unsurprisingly named `controller` option. As you can see, the `myTabs` directive uses this +option. Just like `ngController`, this option attaches a controller to the template of the directive. + +Looking back at `myPane`'s definition, notice the last argument in its `link` function: `tabsCtrl`. +When a directive requires a controller, it receives that controller as the fourth argument of its +`link` function. Taking advantage of this, `myPane` can call the `addPane` function of `myTabs`. + +Savvy readers may be wondering what the difference is between `link` and `controller`. +The basic difference is that `controller` can expose an API, and `link` functions can interact with +controllers using `require`. + +
+**Best Practice:** use `controller` when you want to expose an API to other directives. +Otherwise use `link`. +
+ +### Summary + +Here we've seen the main use cases for directives. Each of these samples acts as a good starting +point for creating your own directives. + +You might also be interested in an in-depth explanation of the compilation process that's +available in the {@link guide/compiler compiler guide}. + +The {@link api/ng.$compile `$compile` API} page has a comprehensive list of directive options for +reference. + diff --git a/docs/content-ko/guide/expression.ngdoc b/docs/content-ko/guide/expression.ngdoc new file mode 100644 index 000000000000..3499af723ac1 --- /dev/null +++ b/docs/content-ko/guide/expression.ngdoc @@ -0,0 +1,148 @@ +@ngdoc overview +@name Developer Guide: Expressions +@description + +Expressions are JavaScript-like code snippets that are usually placed in bindings such as `{{ +expression }}`. Expressions are processed by the {@link api/ng.$parse $parse} +service. Expressions are often post processed using {@link filter filters} to create a more user-friendly format. + +For example, these are all valid expressions in angular: + + * `1+2` + * `user.name` + + +## Angular Expressions vs. JS Expressions + +It might be tempting to think of Angular view expressions as JavaScript expressions, but that is +not entirely correct, since Angular does not use a JavaScript `eval()` to evaluate expressions. +You can think of Angular expressions as JavaScript expressions with following differences: + + * **Attribute Evaluation:** evaluation of all properties are against the scope, doing the + evaluation, unlike in JavaScript where the expressions are evaluated against the global + `window`. + + * **Forgiving:** expression evaluation is forgiving to `undefined` and `null`, unlike in JavaScript, + where trying to evaluate undefined properties can generate `ReferenceError` or `TypeError`. + + * **No Control Flow Statements:** you cannot do any of the following in angular expression: + conditionals, loops, or throw. + +If, on the other hand, you do want to run arbitrary JavaScript code, you should make it a +controller method and call the method. If you want to `eval()` an angular expression from +JavaScript, use the {@link api/ng.$rootScope.Scope#methods_$eval `$eval()`} method. + +## Example + + + 1+2={{1+2}} + + + it('should calculate expression in binding', function() { + expect(binding('1+2')).toEqual('3'); + }); + + + +You can try evaluating different expressions here: + + + + +
+ Expression: + + +
    +
  • + [ X ] + {{expr}} => +
  • +
+
+
+ + it('should allow user expression testing', function() { + element('.expressions :button').click(); + var li = using('.expressions ul').repeater('li'); + expect(li.count()).toBe(1); + expect(li.row(0)).toEqual(["3*10|currency", "$30.00"]); + }); + +
+ + +# Property Evaluation + +Evaluation of all properties takes place against a scope. Unlike JavaScript, where names default +to global window properties, Angular expressions have to use {@link api/ng.$window +`$window`} to refer to the global `window` object. For example, if you want to call `alert()`, which is +defined on `window`, in an expression you must use `$window.alert()`. This is done intentionally to +prevent accidental access to the global state (a common source of subtle bugs). + + + + +
+ Name: + +
+
+ + it('should calculate expression in binding', function() { + var alertText; + this.addFutureAction('set mock', function($window, $document, done) { + $window.mockWindow = { + alert: function(text){ alertText = text; } + }; + done(); + }); + element(':button:contains(Greet)').click(); + expect(this.addFuture('alert text', function(done) { + done(null, alertText); + })).toBe('Hello World'); + }); + +
+ +## Forgiving + +Expression evaluation is forgiving to undefined and null. In JavaScript, evaluating `a.b.c` throws +an exception if `a` is not an object. While this makes sense for a general purpose language, the +expression evaluations are primarily used for data binding, which often look like this: + + {{a.b.c}} + +It makes more sense to show nothing than to throw an exception if `a` is undefined (perhaps we are +waiting for the server response, and it will become defined soon). If expression evaluation wasn't +forgiving we'd have to write bindings that clutter the code, for example: `{{((a||{}).b||{}).c}}` + +Similarly, invoking a function `a.b.c()` on undefined or null simply returns undefined. + + +## No Control Flow Statements + +You cannot write a control flow statement in an expression. The reason behind this is core to the +Angular philosophy that application logic should be in controllers, not in the view. If you need a +conditional, loop, or to throw from a view expression, delegate to a JavaScript method instead. + diff --git a/docs/content-ko/guide/filter.ngdoc b/docs/content-ko/guide/filter.ngdoc new file mode 100644 index 000000000000..86cf17efb754 --- /dev/null +++ b/docs/content-ko/guide/filter.ngdoc @@ -0,0 +1,123 @@ +@ngdoc overview +@name Filters +@description + +A filter formats the value of an expression for display to the user. They can be used in view templates, +controllers or services and it is easy to define your own filter. + +The underlying API is the {@link api/ng.$filterProvider filterProvider}. + +## Using filters in view templates + +Filters can be applied to expressions in view templates using the following syntax: + + {{ expression | filter }} + +E.g. the markup `{{ 12 | currency }}` formats the number 12 as a currency using the {@link api/ng.filter:currency `currency`} +filter. The resulting value is `$12.00`. + +Filters can be applied to the result of another filter. This is called "chaining" and uses +the following syntax: + + {{ expression | filter1 | filter2 | ... }} + +Filters may have arguments. The syntax for this is + + {{ expression | filter:argument1:argument2:... }} + +E.g. the markup `{{ 1234 | number:2 }}` formats the number 1234 with 2 decimal points using the +{@link api/ng.filter:number `number`} filter. The resulting value is `1,234.00`. + + +## Using filters in controllers and services + +You can also use filters in controllers and services. For this, add a dependency with the name `Filter` +to your controller or service. E.g. using the dependency `numberFilter` will inject the number filter. +The injected argument is a function that takes the value to format as first argument and filter parameters +starting with the second argument. + +The example below uses the filter called {@link api/ng.filter:filter `filter`}. +This filter reduces arrays into sub arrays based on +conditions. The filter can be applied in the view template with markup like +`{{ctrl.array | filter:'a'}}`, which would do a fulltext search for "a". +However, using a filter in a view template will reevaluate the filter on +every digest, which can be costly if the array is big. + +The example below therefore calls the filter directly in the controller. +By this, the controller is able to call the filter only when needed (e.g. when the data is loaded from the backend +or the filter expression is changed). + + + + + +
+
+ All entries: + {{entry.name}} +
+
+ Entries that contain an "a": + {{entry.name}} +
+
+
+
+ + +## Creating custom filters + +Writing your own filter is very easy: just register a new filter factory function with +your module. Internally, this uses the {@link api/ng.$filterProvider `filterProvider`}. +This factory function should return a new filter function which takes the input value +as the first argument. Any filter arguments are passed in as additional arguments to the filter +function. + +The following sample filter reverses a text string. In addition, it conditionally makes the +text upper-case. + + + + + +
+
+ No filter: {{greeting}}
+ Reverse: {{greeting|reverse}}
+ Reverse + uppercase: {{greeting|reverse:true}}
+
+
+
+ diff --git a/docs/content-ko/guide/forms.ngdoc b/docs/content-ko/guide/forms.ngdoc new file mode 100644 index 000000000000..f3f95b7c81d7 --- /dev/null +++ b/docs/content-ko/guide/forms.ngdoc @@ -0,0 +1,324 @@ +@ngdoc overview +@name Forms +@description + +Controls (`input`, `select`, `textarea`) are ways for a user to enter data. +A Form is a collection of controls for the purpose of grouping related controls together. + +Form and controls provide validation services, so that the user can be notified of invalid input. +This provides a better user experience, because the user gets instant feedback on how to correct the error. +Keep in mind that while client-side validation plays an important role in providing good user experience, it can easily be circumvented and thus can not be trusted. +Server-side validation is still necessary for a secure application. + + +# Simple form +The key directive in understanding two-way data-binding is {@link api/ng.directive:ngModel ngModel}. +The `ngModel` directive provides the two-way data-binding by synchronizing the model to the view, as well as view to the model. +In addition it provides an {@link api/ng.directive:ngModel.NgModelController API} for other directives to augment its behavior. + + + +
+
+ Name:
+ E-mail:
+ Gender: male + female
+ + + +
form = {{user | json}}
+
master = {{master | json}}
+
+ + +
+
+ + +Note that `novalidate` is used to disable browser's native form validation. + + + +# Using CSS classes + +To allow styling of form as well as controls, `ngModel` add these CSS classes: + +- `ng-valid` +- `ng-invalid` +- `ng-pristine` +- `ng-dirty` + +The following example uses the CSS to display validity of each form control. +In the example both `user.name` and `user.email` are required, but are rendered with red background only when they are dirty. +This ensures that the user is not distracted with an error until after interacting with the control, and failing to satisfy its validity. + + + +
+
+ Name: +
+ E-mail:
+ Gender: male + female
+ + + +
+ + + + +
+
+ + + +# Binding to form and control state + +A form is an instance of {@link api/ng.directive:form.FormController FormController}. +The form instance can optionally be published into the scope using the `name` attribute. +Similarly, control is an instance of {@link api/ng.directive:ngModel.NgModelController NgModelController}. +The control instance can similarly be published into the form instance using the `name` attribute. +This implies that the internal state of both the form and the control is available for binding in the view using the standard binding primitives. + +This allows us to extend the above example with these features: + +- RESET button is enabled only if form has some changes +- SAVE button is enabled only if form has some changes and is valid +- custom error messages for `user.email` and `user.agree` + + + +
+
+ Name: +
+ E-mail: +
+
Invalid: + Tell us your email. + This is not a valid email. +
+ + Gender: male + female
+ + + I agree:
+
Please agree and sign.
+ + + + +
+ + +
+
+ + + +# Custom Validation + +Angular provides basic implementation for most common html5 {@link api/ng.directive:input input} +types: ({@link api/ng.directive:input.text text}, {@link api/ng.directive:input.number number}, {@link api/ng.directive:input.url url}, {@link api/ng.directive:input.email email}, {@link api/ng.directive:input.radio radio}, {@link api/ng.directive:input.checkbox checkbox}), as well as some directives for validation (`required`, `pattern`, `minlength`, `maxlength`, `min`, `max`). + +Defining your own validator can be done by defining your own directive which adds a custom validation function to the `ngModel` {@link api/ng.directive:ngModel.NgModelController controller}. +To get a hold of the controller the directive specifies a dependency as shown in the example below. +The validation can occur in two places: + + * **Model to View update** - + Whenever the bound model changes, all functions in {@link api/ng.directive:ngModel.NgModelController#properties_$formatters NgModelController#$formatters} array are pipe-lined, so that each of these functions has an opportunity to format the value and change validity state of the form control through {@link api/ng.directive:ngModel.NgModelController#methods_$setValidity NgModelController#$setValidity}. + + * **View to Model update** - + In a similar way, whenever a user interacts with a control it calls {@link api/ng.directive:ngModel.NgModelController#methods_$setViewValue NgModelController#$setViewValue}. +This in turn pipelines all functions in the {@link api/ng.directive:ngModel.NgModelController#properties_$parsers NgModelController#$parsers} array, so that each of these functions has an opportunity to convert the value and change validity state of the form control through {@link api/ng.directive:ngModel.NgModelController#methods_$setValidity NgModelController#$setValidity}. + +In the following example we create two directives. + + * The first one is `integer` and it validates whether the input is a valid integer. + For example `1.23` is an invalid value, since it contains a fraction. + Note that we unshift the array instead of pushing. + This is because we want to be first parser and consume the control string value, as we need to execute the validation function before a conversion to number occurs. + + * The second directive is a `smart-float`. + It parses both `1.2` and `1,2` into a valid float number `1.2`. + Note that we can't use input type `number` here as HTML5 browsers would not allow the user to type what it would consider an invalid number such as `1,2`. + + + + +
+
+
+ Size (integer 0 - 10): + {{size}}
+ This is not valid integer! + + The value must be in range 0 to 10! +
+ +
+ Length (float): + + {{length}}
+ + This is not a valid float number! +
+ +
+ + +
+
+ + +# Implementing custom form controls (using `ngModel`) +Angular implements all of the basic HTML form controls ({@link api/ng.directive:input input}, {@link api/ng.directive:select select}, {@link api/ng.directive:textarea textarea}), which should be sufficient for most cases. +However, if you need more flexibility, you can write your own form control as a directive. + +In order for custom control to work with `ngModel` and to achieve two-way data-binding it needs to: + + - implement `$render` method, which is responsible for rendering the data after it passed the {@link api/ng.directive:ngModel.NgModelController#properties_$formatters NgModelController#$formatters}, + - call `$setViewValue` method, whenever the user interacts with the control and model needs to be updated. This is usually done inside a DOM Event listener. + +See {@link guide/directive $compileProvider.directive} for more info. + +The following example shows how to add two-way data-binding to contentEditable elements. + + + + + +
Some
+
model = {{content}}
+ + +
+
diff --git a/docs/content-ko/guide/i18n.ngdoc b/docs/content-ko/guide/i18n.ngdoc new file mode 100644 index 000000000000..7042991c91e8 --- /dev/null +++ b/docs/content-ko/guide/i18n.ngdoc @@ -0,0 +1,124 @@ +@ngdoc overview +@name Developer Guide: i18n and l10n +@description + +# I18n and L10n in AngularJS + +**What is i18n and l10n?** + +Internationalization, abbreviated i18n, is the process of developing products in such a way that +they can be localized for languages and cultures easily. Localization, abbreviated l10n, is the +process of adapting applications and text to enable their usability in a particular cultural or +linguistic market. For application developers, internationalizing an application means abstracting +all of the strings and other locale-specific bits (such as date or currency formats) out of the +application. Localizing an application means providing translations and localized formats for the +abstracted bits. + +**What level of support for i18n/l10n is currently in Angular?** + +Currently, Angular supports i18n/l10n for {@link +http://docs.angularjs.org/#!/api/ng.filter:date datetime}, {@link +http://docs.angularjs.org/#!/api/ng.filter:number number} and {@link +http://docs.angularjs.org/#!/api/ng.filter:currency currency} filters. + +Additionally, Angular supports localizable pluralization support provided by the {@link +api/ng.directive:ngPluralize ngPluralize directive}. + +All localizable Angular components depend on locale-specific rule sets managed by the {@link +api/ng.$locale $locale service}. + +For readers who want to jump straight into examples, we have a few web pages that showcase how to +use Angular filters with various locale rule sets. You can find these examples either on {@link +https://github.com/angular/angular.js/tree/master/i18n/e2e Github} or in the i18n/e2e folder of +Angular development package. + +**What is a locale id?** + +A locale is a specific geographical, political, or cultural region. The most commonly used locale +ID consists of two parts: language code and country code. For example, en-US, en-AU, zh-CN are all +valid locale IDs that have both language codes and country codes. Because specifying a country code +in locale ID is optional, locale IDs such as en, zh, and sk are also valid. See the {@link +http://userguide.icu-project.org/locale ICU } website for more information about using locale IDs. + +**Supported locales in Angular** +Angular separates number and datetime format rule sets into different files, each file for a +particular locale. You can find a list of currently supported locales {@link +https://github.com/angular/angular.js/tree/master/i18n/locale here} +# Providing locale rules to Angular + +There are two approaches to providing locale rules to Angular: + +**1. Pre-bundled rule sets** + +You can pre-bundle the desired locale file with Angular by concatenating the content of the +locale-specific file to the end of `angular.js` or `angular.min.js` file. + +For example on *nix, to create an angular.js file that contains localization rules for german +locale, you can do the following: + +`cat angular.js i18n/angular-locale_de-de.js > angular_de-de.js` + +When the application containing `angular_de-de.js` script instead of the generic angular.js script +starts, Angular is automatically pre-configured with localization rules for the german locale. + +**2. Including locale js script in index.html page** + +You can also include the locale specific js file in the index.html page. For example, if one client +requires German locale, you would serve index_de-de.html which will look something like this: + +
+
+ 
+….
+   
+   
+….
+ 
+
+
+ +**Comparison of the two approaches** +Both approaches described above requires you to prepare different index.html pages or js files for +each locale that your app may be localized into. You also need to configure your server to serve +the correct file that correspond to the desired locale. + +However, the second approach (Including locale js script in index.html page) is likely to be slower +because an extra script needs to be loaded. + + +# "Gotchas" + +**Currency symbol "gotcha"** + +Angular's {@link http://docs.angularjs.org/#!/api/ng.filter:currency currency filter} allows +you to use the default currency symbol from the {@link api/ng.$locale locale service}, +or you can provide the filter with a custom currency symbol. If your app will be used only in one +locale, it is fine to rely on the default currency symbol. However, if you anticipate that viewers +in other locales might use your app, you should provide your own currency symbol to make sure the +actual value is understood. + +For example, if you want to display account balance of 1000 dollars with the following binding +containing currency filter: `{{ 1000 | currency }}`, and your app is currently in en-US locale. +'$1000.00' will be shown. However, if someone in a different local (say, Japan) views your app, her +browser will specify the locale as ja, and the balance of '¥1000.00' will be shown instead. This +will really upset your client. + +In this case, you need to override the default currency symbol by providing the {@link +http://docs.angularjs.org/#!/api/ng.filter:currency currency filter} with a currency symbol as +a parameter when you configure the filter, for example, {{ 1000 | currency:"USD$"}}. This way, +Angular will always show a balance of 'USD$1000' and disregard any locale changes. + +**Translation length "gotcha"** + +Keep in mind that translated strings/datetime formats can vary greatly in length. For example, +`June 3, 1977` will be translated to Spanish as `3 de junio de 1977`. There are bound to be other +more extreme cases. Hence, when internationalizing your apps, you need to apply CSS rules +accordingly and do thorough testing to make sure UI components do not overlap. + + +**Timezones** + +Keep in mind that Angular datetime filter uses the time zone settings of the browser. So the same +application will show different time information depending on the time zone settings of the +computer that the application is running on. Neither Javascript nor Angular currently supports +displaying the date with a timezone specified by the developer. diff --git a/docs/content-ko/guide/ie.ngdoc b/docs/content-ko/guide/ie.ngdoc new file mode 100644 index 000000000000..2634196f3430 --- /dev/null +++ b/docs/content-ko/guide/ie.ngdoc @@ -0,0 +1,187 @@ +@ngdoc overview +@name Developer Guide: Internet Explorer Compatibility +@description + +# Overview + +This document describes the Internet Explorer (IE) idiosyncrasies when dealing with custom HTML +attributes and tags. Read this document if you are planning on deploying your Angular application +on IE v8.0 or earlier. + +# Short Version + +To make your Angular application work on IE please make sure that: + + 1. You polyfill JSON.stringify if necessary (IE7 will need this). You can use + [JSON2](https://github.com/douglascrockford/JSON-js) or + [JSON3](http://bestiejs.github.com/json3/) polyfills for this. +
+       
+       
+         
+           
+         
+         
+           ...
+         
+       
+     
+ + 2. add `id="ng-app"` to the root element in conjunction with `ng-app` attribute +
+       
+       
+         ...
+       
+     
+ + 3. you **do not** use custom element tags such as `` (use the attribute version + `
` instead), or + + 4. if you **do use** custom element tags, then you must take these steps to make IE happy: +
+       
+       
+         
+           
+         
+         
+           ...
+         
+       
+     
+ +The **important** parts are: + + * `xmlns:ng` - *namespace* - you need one namespace for each custom tag you are planning on + using. + + * `document.createElement(yourTagName)` - *creation of custom tag names* - Since this is an + issue only for older version of IE you need to load it conditionally. For each tag which does + not have namespace and which is not defined in HTML you need to pre-declare it to make IE + happy. + + +# Long Version + +IE has issues with element tag names which are not standard HTML tag names. These fall into two +categories, and each category has its own fix. + + * If the tag name starts with `my:` prefix than it is considered an XML namespace and must + have corresponding namespace declaration on `` + + * If the tag has no `:` but it is not a standard HTML tag, then it must be pre-created using + `document.createElement('my-tag')` + + * If you are planning on styling the custom tag with CSS selectors, then it must be + pre-created using `document.createElement('my-tag')` regardless of XML namespace. + + +## The Good News + +The good news is that these restrictions only apply to element tag names, and not to element +attribute names. So this requires no special handling in IE: `
`. + + +## What happens if I fail to do this? + +Suppose you have HTML with unknown tag `mytag` (this could also be `my:tag` or `my-tag` with same +result): + +
+  
+    
+      some text
+    
+  
+
+ +It should parse into the following DOM: + +
+#document
+  +- HTML
+     +- BODY
+        +- mytag
+           +- #text: some text
+
+ +The expected behavior is that the `BODY` element has a child element `mytag`, which in turn has +the text `some text`. + +But this is not what IE does (if the above fixes are not included): + +
+#document
+  +- HTML
+     +- BODY
+        +- mytag
+        +- #text: some text
+        +- /mytag
+
+ +In IE, the behavior is that the `BODY` element has three children: + + 1. A self closing `mytag`. Example of self closing tag is `
`. The trailing `/` is optional, + but the `
` tag is not allowed to have any children, and browsers consider `
some + text
` as three siblings not a `
` with `some text` as child. + + 2. A text node with `some text`. This should have been a child of `mytag` above, not a sibling. + + 3. A corrupt self closing `/mytag`. This is corrupt since element names are not allowed to have + the `/` character. Furthermore this closing element should not be part of the DOM since it is + only used to delineate the structure of the DOM. + + +## CSS Styling of Custom Tag Names + +To make CSS selectors work with custom elements, the custom element name must be pre-created with +`document.createElement('my-tag')` regardless of XML namespace. + +
+  
+    
+      
+      
+    
+    
+      
+      
+      ...
+    
+  
+
+ + + diff --git a/docs/content-ko/guide/index.ngdoc b/docs/content-ko/guide/index.ngdoc new file mode 100644 index 000000000000..8d1ea0e57e7b --- /dev/null +++ b/docs/content-ko/guide/index.ngdoc @@ -0,0 +1,183 @@ +@ngdoc overview +@name Developer Guide +@description + +# Guide to AngularJS Documentation + +Everything you need to know about AngularJS + +* {@link guide/introduction What is AngularJS?} + +* {@link guide/concepts Conceptual Overview} + +## Tutorials + +* {@link tutorial/index Official AngularJS Tutorial} + +* [10 Reasons Why You Should Use AngularJS](http://www.sitepoint.com/10-reasons-use-angularjs/) + +* [Design Principles of AngularJS (video)](https://www.youtube.com/watch?v=HCR7i5F5L8c) + +* [Fundamentals in 60 Minutes (video)](http://www.youtube.com/watch?v=i9MHigUZKEM) + +* [For folks with jQuery background](http://stackoverflow.com/questions/14994391/how-do-i-think-in-angularjs-if-i-have-a-jquery-background) + +## Core Concepts + +### Templates + +In Angular applications, you move the job of filling page templates with data from the server to the client. The result is a system better structured for dynamic page updates. Below are the core features you'll use. + +* {@link guide/databinding Data binding} + +* {@link guide/expression Expressions} + +* {@link guide/directive Directives} + +* {@link api/ngRoute.$route Views and routes (see the example)} + +* {@link guide/filter Filters} + +* {@link guide/forms Forms} and [Concepts of AngularJS Forms](http://mrbool.com/the-concepts-of-angularjs-forms/29117) + +### Application Structure + +* **Blog post: **[When to use directives, controllers or services](http://kirkbushell.me/when-to-use-directives-controllers-or-services-in-angular/) + +* **App wiring:** {@link guide/di Dependency injection} + +* **Exposing model to templates:** {@link guide/scope Scopes} + +* **Communicating with servers:** {@link api/ng.$http $http}, {@link api/ngResource.$resource $resource} + +### Other AngularJS Features + +* **Animation:** {@link guide/animations Core concepts}, {@link api/ngAnimate ngAnimate API}, and [Animation in AngularJS 1.2](http://www.yearofmoo.com/2013/08/remastered-animation-in-angularjs-1-2.html) + +* **Security:** {@link api/ng.$sce Strict Contextual Escaping}, {@link api/ng.directive:ngCsp Content Security Policy}, {@link api/ngSanitize.$sanitize $sanitize}, [video](https://www.youtube.com/watch?v=18ifoT-Id54) + +* **Internationalization and Localization:** {@link guide/i18n Angular Guide to i18n and l10n}, {@link api/ng.filter:date date filter}, {@link api/ng.filter:currency currency filter}, [Creating multilingual support](http://www.novanet.no/blog/hallstein-brotan/dates/2013/10/creating-multilingual-support-using-angularjs/) + +* **Mobile:** {@link api/ngTouch Touch events} + +### Testing + +* **Unit testing:** [Using Karma (video)](http://www.youtube.com/watch?v=YG5DEzaQBIc), {@link guide/dev_guide.unit-testing Unit testing}, {@link guide/dev_guide.services.testing_services Testing services}, [Karma in Webstorm](http://blog.jetbrains.com/webstorm/2013/10/running-javascript-tests-with-karma-in-webstorm-7/) + +* **Scenario testing:** [Protractor](https://github.com/angular/protractor) + +## Specific Topics + +* **Login: **[Google example](https://developers.google.com/+/photohunt/python), [Facebook example](http://blog.brunoscopelliti.com/facebook-authentication-in-your-angularjs-web-app), [authentication strategy](http://blog.brunoscopelliti.com/deal-with-users-authentication-in-an-angularjs-web-app), [unix-style authorization](http://frederiknakstad.com/authentication-in-single-page-applications-with-angular-js/) + +* **Mobile:** [Angular on Mobile Guide](http://www.ng-newsletter.com/posts/angular-on-mobile.html), [PhoneGap](http://devgirl.org/2013/06/10/quick-start-guide-phonegap-and-angularjs/) + +* **Other Languages:** [CoffeeScript](http://www.coffeescriptlove.com/2013/08/angularjs-and-coffeescript-tutorials.html), [Dart](https://github.com/angular/angular.dart.tutorial/wiki) + +* **Realtime: **[Socket.io](http://www.creativebloq.com/javascript/angularjs-collaboration-board-socketio-2132885), [OmniBinder](https://github.com/jeffbcross/omnibinder) + +* **Visualization:** [SVG](http://gaslight.co/blog/angular-backed-svgs), [D3.js](http://www.ng-newsletter.com/posts/d3-on-angular.html) + +## Tools + +* **Debugging:** [Batarang](https://chrome.google.com/webstore/detail/angularjs-batarang/ighdmehidhipcmcojjgiloacoafjmpfk?hl=en) + +* **Testing:** [Karma](http://karma-runner.github.io), [Protractor](https://github.com/angular/protractor) + +* **Editor support:** [Webstorm](http://plugins.jetbrains.com/plugin/6971) (and [video](http://www.youtube.com/watch?v=LJOyrSh1kDU)), [Sublime Text](https://github.com/angular-ui/AngularJS-sublime-package), [Visual Studio](http://madskristensen.net/post/angularjs-intellisense-in-visual-studio-2012) + +* **Workflow:** [Yeoman.io](https://github.com/yeoman/generator-angular) and [Angular Yeoman Tutorial](http://www.sitepoint.com/kickstart-your-angularjs-development-with-yeoman-grunt-and-bower/) + +## Complementary Libraries + +This is a short list of libraries with specific support and documentation for working with Angular. You can find a full list of all known Angular external libraries at [ngmodules.org](http://ngmodules.org/). + +* **Internationalization:** [angular-translate](http://pascalprecht.github.io/angular-translate/), [angular-gettext](http://angular-gettext.rocketeer.be/) + +* **RESTful services:** [Restangular](https://github.com/mgonto/restangular) + +* **SQL and NoSQL backends:** [BreezeJS](http://www.breezejs.com/), [AngularFire](http://angularfire.com/) + +* **UI Widgets: **[KendoUI](http://kendo-labs.github.io/angular-kendo/#/), [UI Bootstrap](http://angular-ui.github.io/bootstrap/), [Wijmo](http://wijmo.com/tag/angularjs-2/) + +## Deployment + +### General + +* **Javascript minification: **[Background](http://thegreenpizza.github.io/2013/05/25/building-minification-safe-angular.js-applications/), [ngmin automation tool](http://www.thinkster.io/pick/XlWneEZCqY/angularjs-ngmin) + +* **Tracking:** [Angularyitcs (Google Analytics)](http://ngmodules.org/modules/angularytics), [Logging Client-Side Errors](http://www.bennadel.com/blog/2542-Logging-Client-Side-Errors-With-AngularJS-And-Stacktrace-js.htm) + +* **SEO:** [By hand](http://www.yearofmoo.com/2012/11/angularjs-and-seo.html), [prerender.io](http://prerender.io/), [Brombone](http://www.brombone.com/), [SEO.js](http://getseojs.com/), [SEO4Ajax](http://www.seo4ajax.com/) + +### Server-Specific + +* **Django:** [Tutorial](http://blog.mourafiq.com/post/55034504632/end-to-end-web-app-with-django-rest-framework), [Integrating AngularJS with Django](http://django-angular.readthedocs.org/en/latest/integration.html) + +* **FireBase:** [AngularFire](http://angularfire.com/), [Realtime Apps with AngularJS and FireBase (video)](http://www.youtube.com/watch?v=C7ZI7z7qnHU) + +* **Google Cloud Platform: **[with Cloud Endpoints](https://cloud.google.com/resources/articles/angularjs-cloud-endpoints-recipe-for-building-modern-web-applications), [with Go](https://github.com/GoogleCloudPlatform/appengine-angular-gotodos) + +* **Hood.ie:** [60 Minutes to Awesome](http://www.roberthorvick.com/2013/06/30/todomvc-angularjs-hood-ie-60-minutes-to-awesome/) + +* **MEAN Stack: **[Blog post](http://blog.mongodb.org/post/49262866911/the-mean-stack-mongodb-expressjs-angularjs-and), [Setup](http://thecodebarbarian.wordpress.com/2013/07/22/introduction-to-the-mean-stack-part-one-setting-up-your-tools/), [GDL Video](https://developers.google.com/live/shows/913996610) + +* **Rails: **[Tutorial](http://coderberry.me/blog/2013/04/22/angularjs-on-rails-4-part-1/), [AngularJS with Rails4](https://shellycloud.com/blog/2013/10/how-to-integrate-angularjs-with-rails-4), [angularjs-rails](https://github.com/hiravgandhi/angularjs-rails) + +* **PHP: **[Building a RESTful web service](http://blog.brunoscopelliti.com/building-a-restful-web-service-with-angularjs-and-php-more-power-with-resource), [End to End with Laravel 4 (video)](http://www.youtube.com/watch?v=hqAyiqUs93c) + +## Learning Resources + +###Books +* [AngularJS](http://www.amazon.com/AngularJS-Brad-Green/dp/1449344852) by Brad Green and Shyam Seshadri +* [Mastering Web App Development](http://www.amazon.com/Mastering-Web-Application-Development-AngularJS/dp/1782161821) by Pawel Kozlowski and Pete Bacon Darwin +* [AngularJS Directives](http://www.amazon.com/AngularJS-Directives-Alex-Vanston/dp/1783280336) by Alex Vanston +* [Recipes With AngularJS](http://www.amazon.co.uk/Recipes-Angular-js-Frederik-Dietz-ebook/dp/B00DK95V48) by Frederik Dietz +* [Developing an AngularJS Edge](http://www.amazon.com/Developing-AngularJS-Edge-Christopher-Hiller-ebook/dp/B00CJLFF8K) by Christopher Hiller +* [ng-book: The Complete Book on AngularJS](http://ng-book.com/) by Ari Lerner + +###Videos: +* [egghead.io](http://egghead.io/), +* [Angular on YouTube](http://youtube.com/angularjs) + +###Courses +* **Free on-line:** + [thinkster.io](http://thinkster.io), + [CodeAcademy](http://www.codecademy.com/courses/javascript-advanced-en-2hJ3J/0/1) +* **Paid on-line:** + [Pluralsite (3 courses)](http://www.pluralsight.com/training/Courses/Find?highlight=true&searchTerm=angularjs), + [Tuts+](https://tutsplus.com/course/easier-js-apps-with-angular/), + [lynda.com](http://www.lynda.com/AngularJS-tutorials/Up-Running-AngularJS/133318-2.html) +* **Paid on-site:** + [angularbootcamp.com](http://angularbootcamp.com/) + +## Getting Help + +The recipe for getting help on your unique issue is to create an example that could work (even if it doesn't) in a shareable example on [Plunker](http://plnkr.co/), [JSFiddle](http://jsfiddle.net/), or similar site and then post to one of the following: + +* [Stackoverflow.com](http://stackoverflow.com/search?q=angularjs) + +* [AngularJS mailing list](https://groups.google.com/forum/#!forum/angular) + +* [AngularJS IRC channel](http://webchat.freenode.net/?channels=angularjs&uio=d4) + +## Social Channels + +* **Daily updates:** [Google+](https://plus.google.com/u/0/+AngularJS) or [Twitter](https://twitter.com/angularjs) + +* **Weekly newsletter:** [ng-newsletter](http://www.ng-newsletter.com/) + +* **Meetups: **[meetup.com](http://www.meetup.com/find/?keywords=angularJS&radius=Infinity&userFreeform=San+Francisco%2C+CA&mcId=z94108&mcName=San+Francisco%2C+CA&sort=member_count&eventFilter=mysugg) + +* **Official news and releases: **[AngularJS Blog](http://blog.angularjs.org/) + +## Contributing to AngularJS + +Though we have a core group of core contributors at Google, Angular is an open source project with hundreds of contributors. We'd love you to be one of them. When you're ready, please read the {@link misc/contribute Guide for contributing to AngularJS}. + +## Final Bits + +Didn't find what you're looking for here? Check out [AngularJS-Learning](https://github.com/jmcunningham/AngularJS-Learning) for an even more comprehensive list of links to videos, tutorials, and blog posts. + +If you have awesome AngularJS resources that belong on this page, please tell us about them on [Google+](https://plus.google.com/u/0/+AngularJS) or [Twitter](https://twitter.com/angularjs). + diff --git a/docs/content-ko/guide/introduction.ngdoc b/docs/content-ko/guide/introduction.ngdoc new file mode 100644 index 000000000000..92b9b20f194f --- /dev/null +++ b/docs/content-ko/guide/introduction.ngdoc @@ -0,0 +1,108 @@ +@ngdoc overview +@name Introduction +@description + + +# What Is Angular? + +AngularJS is a structural framework for dynamic web apps. It lets you use HTML as your template +language and lets you extend HTML's syntax to express your application's components clearly and +succinctly. Out of the box, it eliminates much of the code you currently write through data +binding and dependency injection. And it all happens in JavaScript within the browser, making it +an ideal partner with any server technology. + +Angular is what HTML would have been had it been designed for applications. HTML is a great +declarative language for static documents. It does not contain much in the way of creating +applications, and as a result building web applications is an exercise in *what do I have to do +to trick the browser into doing what I want.* + +The impedance mismatch between dynamic applications and static documents is often solved with: + + * **a library** - a collection of functions which are useful when writing web apps. Your code is + in charge and it calls into the library when it sees fit. E.g., `jQuery`. + * **frameworks** - a particular implementation of a web application, where your code fills in + the details. The framework is in charge and it calls into your code when it needs something + app specific. E.g., `knockout`, `ember`, etc. + + +Angular takes another approach. It attempts to minimize the impedance mismatch between document +centric HTML and what an application needs by creating new HTML constructs. Angular teaches the +browser new syntax through a construct we call directives. Examples include: + + * Data binding, as in `{{}}`. + * DOM control structures for repeating/hiding DOM fragments. + * Support for forms and form validation. + * Attaching code-behind to DOM elements. + * Grouping of HTML into reusable components. + + + +## A complete client-side solution + +Angular is not a single piece in the overall puzzle of building the client-side of a web +application. It handles all of the DOM and AJAX glue code you once wrote by hand and puts it in a +well-defined structure. This makes Angular opinionated about how a CRUD application should be +built. But while it is opinionated, it also tries to make sure that its opinion is just a +starting point you can easily change. Angular comes with the following out-of-the-box: + + * Everything you need to build a CRUD app in a cohesive set: data-binding, basic templating + directives, form validation, routing, deep-linking, reusable components, dependency injection. + * Testability story: unit-testing, end-to-end testing, mocks, test harnesses. + * Seed application with directory layout and test scripts as a starting point. + + +## Angular Sweet Spot + +Angular simplifies application development by presenting a higher level of abstraction to the +developer. Like any abstraction, it comes at a cost of flexibility. In other words not every app +is a good fit for Angular. Angular was built with the CRUD application in mind. Luckily CRUD +applications represent the majority of web applications. To understand what Angular is +good at, though, it helps to understand when an app is not a good fit for Angular. + +Games and GUI editors are examples of applications with intensive and tricky DOM manipulation. +These kinds of apps are different from CRUD apps, and as a result are probably not a good fit for Angular. +In these cases it may be better to use a library with a lower level of abstraction, such as `jQuery`. + +# The Zen of Angular + +Angular is built around the belief that declarative code is better than imperative when it comes +to building UIs and wiring software components together, while imperative code is excellent for +expressing business logic. + + + * It is a very good idea to decouple DOM manipulation from app logic. This dramatically improves + the testability of the code. + * It is a really, _really_ good idea to regard app testing as equal in importance to app + writing. Testing difficulty is dramatically affected by the way the code is structured. + * It is an excellent idea to decouple the client side of an app from the server side. This + allows development work to progress in parallel, and allows for reuse of both sides. + * It is very helpful indeed if the framework guides developers through the entire journey of + building an app: from designing the UI, through writing the business logic, to testing. + * It is always good to make common tasks trivial and difficult tasks possible. + + + +Angular frees you from the following pains: + + * **Registering callbacks:** Registering callbacks clutters your code, making it hard to see the + forest for the trees. Removing common boilerplate code such as callbacks is a good thing. It + vastly reduces the amount of JavaScript coding _you_ have to do, and it makes it easier to see + what your application does. + * **Manipulating HTML DOM programmatically:** Manipulating HTML DOM is a cornerstone of AJAX + applications, but it's cumbersome and error-prone. By declaratively describing how the UI + should change as your application state changes, you are freed from low-level DOM manipulation + tasks. Most applications written with Angular never have to programmatically manipulate the + DOM, although you can if you want to. + * **Marshaling data to and from the UI:** CRUD operations make up the majority of AJAX + applications' tasks. The flow of marshaling data from the server to an internal object to an HTML + form, allowing users to modify the form, validating the form, displaying validation errors, + returning to an internal model, and then back to the server, creates a lot of boilerplate + code. Angular eliminates almost all of this boilerplate, leaving code that describes the + overall flow of the application rather than all of the implementation details. + * **Writing tons of initialization code just to get started:** Typically you need to write a lot + of plumbing just to get a basic "Hello World" AJAX app working. With Angular you can bootstrap + your app easily using services, which are auto-injected into your application in a {@link + http://code.google.com/p/google-guice/ Guice}-like dependency-injection style. This allows you + to get started developing features quickly. As a bonus, you get full control over the + initialization process in automated tests. + diff --git a/docs/content-ko/guide/migration.ngdoc b/docs/content-ko/guide/migration.ngdoc new file mode 100644 index 000000000000..b1c13d3df101 --- /dev/null +++ b/docs/content-ko/guide/migration.ngdoc @@ -0,0 +1,651 @@ +@ngdoc overview +@name Migrating from 1.0 to 1.2 +@description + + +AngularJS version 1.2 introduces several breaking changes that will may require changes to your +application's source code. + +Although we try to avoid breaking changes, there are some cases where it is unavoidable. +AngularJS 1.2 has undergone a thourough security review to make applications safer by default, +which has driven many of these changes. Several new features, especially animations, would not +be possible without a few changes. Finally, some outstanding bugs were best fixed by changing +an existing API. + +
+

**Note:** AngularJS versions 1.1.x are considered "experimental" with breaking changes between minor releases. +Version 1.2 is the result of several versions on the 1.1 branch, and has a stable API.

+ +

If you have an application on 1.1 and want to migrate it to 1.2, everything in the guide +below should still apply, but you may want to consult the +[changelog](https://github.com/angular/angular.js/blob/master/CHANGELOG.md) as well.

+
+ + + + +## ngRoute has been moved into its own module + +Just like `ngResource`, `ngRoute` is now its own module. + +Applications that use `$route`, `ngView`, and/or `$routeParams` will now need to load an +`angular-route.js` file and have their application's module dependency on the `ngRoute` module. + +Before: + +```html + +``` + +```javascript +var myApp = angular.module('myApp', ['someOtherModule']); +``` + +After: + +```html + + +``` + +```javascript +var myApp = angular.module('myApp', ['ngRoute', 'someOtherModule']); +``` + +See [5599b55b](https://github.com/angular/angular.js/commit/5599b55b04788c2e327d7551a4a699d75516dd21). + + +## Templates no longer automatically unwrap promises + +`$parse` and templates in general will no longer automatically unwrap promises. + +Before: + +```javascript +$scope.foo = $http({method: 'GET', url: '/someUrl'}); +``` + +```html +

{{foo}}

+``` + +After: + +```javascript +$http({method: 'GET', url: '/someUrl'}) + .success(function(data) { + $scope.foo = data; + }); +``` + +```html +

{{foo}}

+``` + +This feature has been deprecated. If absolutely needed, it can be reenabled for now via the +`$parseProvider.unwrapPromises(true)` API. + +See [5dc35b52](https://github.com/angular/angular.js/commit/5dc35b527b3c99f6544b8cb52e93c6510d3ac577), +[b6a37d11](https://github.com/angular/angular.js/commit/b6a37d112b3e1478f4d14a5f82faabf700443748). + + +## Syntax for named wildcard parameters changed in `$route` + +To migrate the code, follow the example below. Here, `*highlight` becomes `:highlight*` + +Before: + +```javascript +$routeProvider.when('/Book1/:book/Chapter/:chapter/*highlight/edit', + {controller: noop, templateUrl: 'Chapter.html'}); +``` + +After: + +```javascript +$routeProvider.when('/Book1/:book/Chapter/:chapter/:highlight*/edit', + {controller: noop, templateUrl: 'Chapter.html'}); +``` + +See [04cebcc1](https://github.com/angular/angular.js/commit/04cebcc133c8b433a3ac5f72ed19f3631778142b). + + +## You can only bind one expression to `*[src]` or `*[ng-src]` + +With the exception of `` and `` elements, you cannot bind more than one expression to the +`src` attribute of elements. + +This is one of several improvements to security introduces by Angular 1.2. + +Concatenating expressions makes it hard to understand whether some combination of concatenated +values are unsafe to use and potentially subject to XSS vulnerabilities. To simplify the task of +auditing for XSS issues, we now require that a single expression be used for `*[src/ng-src]` +bindings such as bindings for `iframe[src]`, `object[src]`, etc. + +
+ + + + + + + + + + + + + + + + + + + +
Examples
<img src="{{a}}/{{b}}">ok
<iframe src="{{a}}/{{b}}"></iframe>bad
<iframe src="{{a}}"></iframe>ok
+ + +To migrate your code, you can combine multiple expressions using a method attached to your scope. + +Before: + +```javascript +scope.baseUrl = 'page'; +scope.a = 1; +scope.b = 2; +``` + +```html + +