2016-11-04 78 views
0

我如何可以訪問視圖$範圍數據,以我的angularjs工廠嗎?我可以從我的控制器訪問$ scope.items,但是當我需要在我的工廠中使用它來使用數據並生成PDF時,我無法訪問它。

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; 
}); 

我使用了工廠,當我從我的視圖中單擊生成按鈕,它會一直等到生成pdf。因爲我之前沒有這樣做,我需要點擊按鈕兩次才能生成pdf。

+0

這很簡單,因爲$範圍服務不能在工廠 –

回答

0

您可以將數據只是通過給工廠作爲 函數參數。

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; 
}); 
+0

是的,就是我在答案中所做的。雖然謝謝! – bobtta

+0

既然我不能接受我自己的答案,你的答案與我相同,我會接受你的答案。 – bobtta

0

我做到了。我忘了發送$scope.items到我的工廠。所以我所做的是我在我的控制器中加入了testFactory.all($scope.items),而不是簡單的testFactory.all()

在我廠

然後,

我以前function _all(value),這樣我就可以用通過控制器的意見傳遞的值。我不確定這是否正確,但是有效。如果你有,請建議好的做法。

0

這是一個不好的做法,$範圍走動等服務,因爲它們可能會改變它,影響你的控制器邏輯。它將使控制器與其他服務耦合。 如果您的工廠需要控制器的數據,最好將這些參數傳遞給工廠的功能。

編輯:我看你沒做到這一點,是的 - 通過$ scope.items是首選的方式(而不是,例如,傳遞$範圍)。

+0

訪問我聽說這是不好的做法,我目前正在研究在angularjs一次一個很好的做法。希望我會完全理解它。 – bobtta

+0

太棒了!如果這有幫助,請投票或標記答案:)無論如何,祝你好運。 –