I'm having trouble figuring out a way to use local variables in a controller that contains an asynchronous call. Is there a way to force the controller to run [at least some of] the code sequentially?
Controller:
angular.module('myApp.controllers.contacts', [])
.controller('CtrlContacts',
[ '$scope','apiUsers',
function($scope, apiUsers){
var selected = $scope.selected = [];
apiUsers.getShortlist().then(function(response){
// WILL correctly populate the associated view
$scope.selected = response.data.data.contacts;
// WILL NOT correctly populate the associated view
selected = response.data.data.contacts;
console.log(selected); // shows the correct data
});
}
;
If apiUser.getShortlist() were not an asynchronous call, this would work just fine.
I wouldn't mind so much, but the variables can get a bit unwieldy. Additionally, it's a pain trying to cross-train people when occasional responses have to be "I'm not sure why, but do it or angular will get angry".
=========
EDIT
=========
Thanks Esteban and Greg.
Was thinking of my selected variable as an object property, like a dummy. I'm actually using "controller as" syntax, so I ended up writing my controller like this:
Controller:
angular.module('myApp.controllers.contacts', [])
.controller('CtrlContacts',
[ '$scope','apiUsers',
function($scope, apiUsers){
var self = this;
var selected = $scope.selected = [];
apiUsers.getShortlist().then(function(response){
self.selected = response.data.data.contacts;
});
}
;
$scope
. It's hard to tell what you're asking. Is it that you want your views to be able to access vars that aren't a part of$scope
?