I have the following scenario, I need data from a particular url.I also need to save this datas into a variable that I can call everywhere in my controller. To overcome such issue, I have written a service like below :
app.service("userData", function ($http, $q) {
var deferred = $q.defer();
this.getUsers = function () {
return $http.get('/users')
.then(function (response) {
deferred.resolve(response.data);
return deferred.promise;
}, function (response) {
deferred.reject(response);
return deferred.promise;
})
;
};
});
And then my controller looks like :
app.controller('UserCtrl', function($scope, $q, userData) {
var myData = userData.getUsers()
.then(
function (result) {
$scope.users = result;
},
function (error) {
console.log(error.statusText);
}
);
console.log(myData)
});
It prints :
So how can i store data into a variable which is accessible all over the controller ? Thanks..