angularjs - How come Angular doesn't update with scope here? -
i'm pretty new angular , i'm using firebase backend. hoping debug issue. when first go page www.mywebsite.com/#defaulthash data doesn't load dom, after visiting hash link , coming though.
my controller this:
/* initialize data */ var fb = new firebase('https://asdf.firebaseio.com/'); /* set data automatically update on change */ fb.on('value', function(snapshot) { var data = snapshot.val(); $scope.propertyconfiguration = data.products; console.log($scope.propertyconfiguration); console.log("data retrieved"); }); /* save data on button submit */ $scope.saveconfigs = function(){ var setfbref = new firebase('https://asdf.firebaseio.com/products'); setfbref.update($scope.propertyconfiguration); console.log("configurations saved!"); }; i have 3 hash routes "shared", "registration", , "home" otherwise.redirectto set "shared".(they use controller) here's error occurs: (all "links" href="#hashwhereever")
1) go website.com/#shared or refresh. console logs $scope.propertyconfiguration , "data retrieved". dom shows nothing.
2) click website.com/#registration, console logs $scope data properly, dom loaded correctly.
3) click website.com/#shared, console logs $scope data yet time dom loads correctly.
4) refresh correctly loaded website.com/#shared. dom elements disappear.
since $scope.data correct in cases here, shouldn't angular make sure dom reflects model properly? why dom loads correctly when clicking page link.
i can "fix" adding window.location.hash = "shared" throws huge amount of errors in console.
fixed:(sorta)
the function $scope.$apply() forces view sync model. i'd answer question myself , close i'm still wondering why view doesn't load correctly when correctly assign value $scope. if angular's "dirty checking" checks whenever there possibility model has changed, doesn't assigning value $scope overqualify?
angular has no way know you've assigned value $scope.variable. there's no magic here. when run directive (ng-click/ng-submit) or angular internal functions, call $apply() , trigger digest (a check of dirty flags , update routine).
a possibly safer approach $apply use $timeout. currently, if call write op in firebase, synchronously trigger event listener (child_added, child_changed, value, etc). cause call $apply while still within $apply scope. if this, error thrown. $timeout bypasses this.
see this question bit more on topic of digest , $timeout.
this doc in angular developer guide covers how compile works; great background read serious angular dev.
also, can save deal of energy using official firebase bindings angular, take of these implementation details account.
vaguely related note: in not-too-distant future, angular able take advantage of object.observe magic handle these updates.
Comments
Post a Comment