bobtta bobtta - 1 month ago 12
AngularJS Question

Accessing $scope data from view to factory in AngularJs

How can I access $scope data from view to my factory in angularjs? I can access $scope.items from my controller, but when I need to use it in my factory to use the data and generate a pdf I cannot access it.

angular.module('myApp', [])

.controller('myCtrl', function($scope, $http, testFactory) {

$scope.link = "http://localhost:3450/loading.html";
testFactory.all().then(
function(res){
$scope.link = res;
},
function(err){
console.log(err);
}
);

})

.factory('testFactory', function($q){

var pdfInfo = {
content: [
//data should be here...
]
};

var link = {};
function _all(){
var d = $q.defer();
pdfMake.createPdf(pdfInfo).getDataUrl(function(outputDoc){
d.resolve(outputDoc);
});
return d.promise;
}
link.all = _all;
return link;
});


I used factory when I click the generate button from my view, it will wait until the pdf is generated. Coz when I did not do it this way before, I need to click the button twice just to get the pdf generated.

Answer

You can just pass the data to your factory as a function parameter.

angular.module('myApp', [])

.controller('myCtrl', function($scope, $http, testFactory) {

    var pdfInfo = {
        content: $scope.items
    };

    $scope.link = "http://localhost:3450/loading.html";
    testFactory.all(pdfInfo).then(
        function(res) {
            $scope.link = res;
        },
        function(err) {
            console.log(err);
        }
    );

})

.factory('testFactory', function($q) {

    var link = {};

    function _all(pdfInfo) {
        var d = $q.defer();
        pdfMake.createPdf(pdfInfo).getDataUrl(function(outputDoc) {
            d.resolve(outputDoc);
        });
        return d.promise;
    }
    link.all = _all;
    return link;
});