bluebill1049 bluebill1049 - 1 month ago 10
Javascript Question

Accessing $scope in AngularJS factory?

I am new to AngularJS and find it very interesting, but I am a bit unclear about the following situation.

app.factory('deleteFac', function($http){

var factory = {};

factory.edit = function(id){
$http.get('?controller=store&action=getDetail&id=' + id).
success(function(data, status){
/**
got an error on the following
when i use return data; and i get data undefined
in the controller which i get it because its doing a ajax call
you don't get data until the call first.
**/
$scope.detail = data;
})
}

return factory;
})


I am getting error when I assign to
$scope
and use return data, is there anyway I can assign the return data to the
$scope
?

Answer

You don't typically use $scope inside a factory, service or provider. Usually, you would return the promise (returned by $http) and then handle the promise in a controller (where you do have $scope).

factory.edit = function(id){
    return $http.get('?controller=store&action=getDetail&id=' + id);
}

Controller function:

$scope.edit = function(id) {

    deleteFac.edit(id).then(function(response) {
        $scope.something = response.model;
    });
}