angularjs - Access $scope.property outside of a callback function in a controller -
can't think of better title, sorry.
please consider following code -
//controller function productctrl($scope) { getcategories(function (result) { $scope.category = result.categories[0].name; }); // asynchronouse method; getcategories calls uses xhr , returns result callback. } //view {{category}}
when view loads in browser, getcategories
gets called immediately. how make load on demand, onload on div or can re-use method somewhere else? like, $scope.getcategories
returns data wanted, not on controller load. , how use method in view? e.g. <div onload=getcategories()></div>
works?
another question, view not print category
. how make $scope.category
available outside of getcategories
?
when view loads in browser, getcategories gets called immediately. how make load on demand?
wrap in function, , call function when appropriate:
$scope.getcategories = function() { getcategories(function (result) { ... } }
so can re-use method somewhere else?
if multiple views need access result of getcatetories, should create service stores result. controllers can inject service access it.
the view not print category.
your ajax happening "outside" of angular, angular doesn't know callback being called , $scope.category
being updated. add $scope.$apply()
after update $scope.category
in callback , angular run digest cycle , update view.
Comments
Post a Comment