Thursday, May 15, 2014

angular pitfalls: the need for $scope.$apply()

Long story short: sometimes, especially when you're using widgets "outside the angular ecosystem" and/or you're using ng-if type logic, you might get burnt by the way components inherit $scope; in particular, primitive variable types might get "shadowed", so you would change $scope.someVar, and it doesn't change in the parent scope (where it actually matters for talking with the rest of your page)

One work around is using $scope.$apply() like this article suggests. For me, that was a pretty quick solution, with minimal code changes.

Another idea is avoiding shared pirimitive variables directly on $scope, put it in a map-like object instead. My suggestion for naming that is $scope.scopeNoReallyShareThisScope... but I'm feeling especially cynical about angular.js at the moment. A giant forest of hard-to-monitor scope-based couplings between DOM and code is no way to live.

No comments:

Post a Comment