You could achieve this by using promises or a callback. But you will not be able to make it like you tried to in just one linear procedure. Get aware of async JavaScript bevhaviors. Here is an example fiddle.
With promises
function graphreport(agentList) {
var b;
var self = this;
var deferred = $q.defer();
var promise = deferred.promise;
agentList.getAgentsList().then(function (data) {
self.agents = data.data.users;
console.log(data.data.users.length);
b = data.data.users.length;
deferred.resolve(data.data.users.length);
});
promise.then(function (b) {
console.log(b);
});
}
With callback function
function graphreport(agentList) {
var self = this;
agentList.getAgentsList().then(function (data) {
self.agents = data.data.users;
console.log(data.data.users.length);
myCallack(data.data.users.length);
});
function myCallack(b) {
console.log(b);
}
}
With co & yield like in this demo fiddle.
var myApp = angular.module('myApp',[]);
myApp.controller('MyCtrl', function ($timeout, $q) {
co(function *() {
var deferred = $q.defer();
var promise = deferred.promise;
function someAsync() {
$timeout(function () {
deferred.resolve('test');
}, 250);
}
someAsync();
var b = yield promise;
console.log(b);
});
});