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.
the third console.log
method (in nav()
) logs controller object methods so:
the fourth console.log
method logs same object buttondisplay
property changed.
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
Post a Comment