javascript - How controller components are instantiated in AngularJS? -


this controller.

angular.module('homepage').controller('buttonviewctrl',  [function() {     console.log(this);     this.buttondisplay = false;     console.log(this);      this.nav = function() {         console.log(this);  //returns object {buttondisplay: false}         //console.log(json.stringify(this));         this.buttondisplay = true;     };      this.closenav = function() {         console.log(this); //returns object {buttondisplay: true}         //console.log(json.stringify(this));          this.buttondisplay = false;     }; }]) 

the first console.log method logs empty object.

second console.log method logs controller object property buttondisplay added it. enter image description here

the third console.log method (in nav()) logs controller object methods so: enter image description here

the fourth console.log method logs same object buttondisplay property changed.

enter image description here

i have 2 questions.

1) example, per understanding, when angular sees controller definition declares empty object. attaches properties object executed. question how come when nav() method triggered, detects there other methods in controller , attaches them controller object (closenav() in case). behavior expected attach nav() method when triggered, , when closenav() triggered attach controller object. can see though, in figure 3, angular has attached closenav() controller without being triggered. how angular doing this?

2) according best practices of angular, should not manipulate dom in controller. in controller, nav() function dispalys navigation bar template , closenav() function closes it. considered dom manipulation? adding presentation logic in controller?

1) example, per understanding, when angular sees controllerdefinition declares empty object.

actually no, angular remembers controller has been registered under name. controller instantiated when angular determines needed, e.g. when encountering dom node ng-controller="..." directive. @ point calls new controllerfunction(...), passing in of declared dependencies arguments.

the first 2 console.log() calls execute while controller still being initialized, , that's reason don't see of members there yet.

2) according best practices of angular, should not manipulate dom in controller. in controller, nav() function dispalys navigation bar template , closenav() function closes it. considered dom manipulation?

no, isn't, that's fine. after it's controller's job provide data view (template) needs. direct dom manipulation if you, example, start creating new dom elements, directly manipulating attributes, registering event handlers on them, etc. (that kind of stuff belongs directives).


Comments

Popular posts from this blog

yii2 - Yii 2 Running a Cron in the basic template -

asp.net - 'System.Web.HttpContext' does not contain a definition for 'GetOwinContext' Mystery -

mercurial graft feature, can it copy? -