After spending countless hours experimenting with variations of this code, it remains a mystery to me why one version works while the other fails.
The situation is as follows: I am attempting to display a list of registered users retrieved from a database query that returns only a few columns. When a user's name is clicked, more detailed information about that user is fetched from the database and displayed in a separate view. Currently, I achieve this using regular <a>
elements with an ng-click
directive that sets a value called currentid
. Another part of my code utilizes $watch()
to trigger a new database query whenever the currentid
changes. While this process seems to be functioning correctly (I can observe the output from my watch callback displaying in the console, and the database query is returning the correct data), there are instances where the currentid
changes unpredictably, leading to confusion on my end.
- A jsfiddle where it doesn't work: http://jsfiddle.net/aLcRL/11/
- A jsfiddle where it DOES work: http://jsfiddle.net/aLcRL/12/
(Click on the "rmunn" and "admin" links in the table: the "Current ID" value below should update. And please excuse the bare-bones styling; graphic design is not my forte ("Dammit, Jim!"), plus it's quite late in my time zone, and I lack the motivation to beautify this. It serves its purpose, highlighting the issue at hand.)
The key distinction between these two scenarios is that one binds to currentid
, while the other binds to vars.currentid
. Conceptually, I understand why binding directly to currentid
could pose issues in a parent-child scope relationship (the child's value potentially taking precedence over the parent's); drawing parallels to my background in Python helps me make sense of this (similar to how instance namespaces in Python can overshadow class-defined namespaces). However, given that I'm working within a single controller context in this jsfiddle, shouldn't all variables reside in the same scope?
This struggle has consumed my entire day, with attempts to decipher various Stack Overflow discussions such as How does data binding work in AngularJS? leaving me even more perplexed with mentions of $apply()
, $digest()
, and scopes galore. If anyone could offer a straightforward beginner's guide to scopes in Angular (or direct me to an existing resource that I might have overlooked), I would greatly appreciate it.
"I've mastered Clojure and Haskell, surely tackling a simple Javascript framework will be a breeze," was my initial assumption. Alas, I couldn't have been more mistaken. :-)