AngularJS - scope variable does not get updated from method -
i'm totally new angularjs , have problem not understand. have 2 methods. first 1 takes data webservice , puts in in variable defined in scope. when want use variable in second method undefined. can me understand why happening , provide solution?
var myapp= angular.module( "myapp", [] ); myapp.controller("myappcontroller", function( $scope ) { $scope.getall = function(){ $.ajax({ type: "get", datatype: "jsonp", contenttype: "application/json; charset=utf-8", url: ..something..., success: function (parameters) { $scope.profiles = angular.copy(parameters); <-- correct data returned $scope.$apply(); }, error: function () { alert("error calling web service."); } }); } $scope.getcategories = function(){ var = $scope.profiles; <-- @ point profiles empty ... } $scope.getall(); $scope.getcategories(); }
there no guarantee getall
has completed before getcategories
invoked, since asynchronous request. if want sequentially invoke getall
, getcategories
, should invoke getcategories
inside success
callback of getall
. promises
neater way of chaining asynchronous callbacks (i assume you're using jquery since you're calling $.ajax
).
... <snipped code> success: function(parameters) { // snipped more code $scope.getcategories(); }
(and if you're using jquery promises)
$.ajax(ajaxcalloneopts).then($.ajax(ajaxcalltwoopts));
neither "angularish" though, might want of provided services working http/rest resources instead of using jquery.
Comments
Post a Comment