You get a $scope. You get a $scope. AND you get a $scope!
June 10, 2014
I was working on a list-type directive[1] when I noticed that a variable in the global $scope wasn't updating, while the corresponding var (wheeeee two-way binding) was updating correctly. $scope.watch
wasn't triggering. I was using an isolated scope on the directive and it looked like two-way data binding was broken.
Googling didn't really yield a solution, so I wrote a less complicated directive but with the same two-way-data binding. Realized that ng-repeat
was the culprit.
I imagine scopes to be fenced in areas. Apparently using ng-repeat
with a directive that had an isolated scope, was creating a fenced in area within another fenced in area, and Angular didn't want to do all that jumping over. Angular likes creating scopes all over the place.
I'm not quite sure how prototypical inheritance in Angular works or the nitty gritty of how or why different scopes are created; and I don't think I have to know those things to get going.
Granted knowing all the details of how ng-repeat
and isolated scopes work would probably help fix bugs or architect the code base EXACTLY the way I wanted it to.
After talked to Stew about the bug for a bit (though it's not really a bug, it's more like me not understanding 1000% how Angular works), I've realized that I could just make things easier for the team by NOT using an isolated scope in this directive.
I used isolated scopes in the first place because I thought it would be a safe assumption that the directive would be used in more than one place, that it should be modular.
After examining the project spec and design comps, it turns out that this list-type directive is a singleton, and only really appears on one page of the app. Using an isolated scope in this case didn't make much sense. I'm sure I could spent time to have both an isolated scope and ng-repeat
working, but the time and effort probably wouldn't have been worth it.
So now I have to refactor this directive to use a child scope, which isn't going to be too painful, thankfully.
1: I don't think I'm using directives at their fullest potential. I'm only using them as a type of include (a la PHP or ERB) and to wrap DOM logic and manipulation.