VolcovMeter VolcovMeter - 3 months ago 24x
AngularJS Question

AngularJS: How to access variable from inside a promise and use within the controller?

I'm trying to declare an array inside a function of a controller that happens after the factory pulls for data, and then access it after the function is done being completed. Here's what I have for my code:

app.controller('SignUpController', function ($scope, $http, $location, DailyCounterService, $localStorage) {

DailyCounterService.GetDailyCountersList().then(function (d) {
$scope.DailyCounters = d.data;
$scope.allCounters = [];

var daySixteen = d.data.filter(function (d) {
// This is where I'm building the array I want to access later

return d.MIDay === "16";

// This prints in console '[2, 6, 1, 1, 7, 8, 2......]'
// So the array is now initialized

}, function (error) {

// Here is where I want to access $scope.allCounters once again
// But Can't because doing this:
// prints 'undefined'
// How would I make $scope.allCounters be able to be accessed here?
.factory('DailyCounterService', function ($http) {
var fac = {};
fac.GetDailyCountersList = function () {
return $http.get('/Data/GetDailyCountersList')
return fac;

As I've asked in the comments towards the end of my controller, how would I be able to access the variable set in the function prior outside of that function?


Well, if this controller is associated with a route, then you can tie up this get code in the resolve attribute of the route provider like this,

.when("/signup", {
    templateUrl: "signup.html",
    controller: "SignUpController",
    resolve: {
            DailyCounterService.GetDailyCountersList().then(function (d) {
             // Do your stuff
             return allCounters;
        }, function (error) {

and access allCounters in you controller like this,

 app.controller('SignUpController', function ($scope, $http, $location, allCounters, DailyCounterService, $localStorage)

By this way all counters will always be initialized when your controller is loaded.

More on resolve: http://odetocode.com/blogs/scott/archive/2014/05/20/using-resolve-in-angularjs-routes.aspx