you should avoid using the this
in this context. it's better to just declare a new variable.
myApp.factory('LoginFactory', ['$http', function ($http) { var data; $http.get('/api/login.json').success(function (d) { data = d; }); return { getData: function () { return data; } }; }]);
you will still have a race problem, so I would also recommend with both chains
myApp.factory('LoginFactory', ['$http', function ($http) { var promise = $http.get('/api/login.json'); return { getData: function (callback) { promise.success(callback); } }; }]);
or even conditional get
myApp.factory('LoginFactory', ['$http', function ($http) { var data; return { getData: function (callback) { if(data) { callback(data); } else { $http.get('/api/login.json').success(function(d) { callback(data = d); }); } } }; }]);
The last two approaches require you to rewrite your controller, but
myApp.controller('AccountsCtrl', ['$scope', 'Accounts', 'LoginFactory', function($scope, Accounts, LoginFactory){ LoginFactory.getData(function(data) { $scope.login = data; console.log('$scope.login: %o', $scope.login); $scope.accounts = Accounts.index();
source share