在AngularJs中从视图到工厂访问$scope数据

Accessing $scope data from view to factory in AngularJs

本文关键字:访问 scope 数据 工厂 AngularJs 视图      更新时间:2023-09-26

如何在angularjs中从view到factory访问$scope数据?我可以访问$scope。项,但是当我需要在工厂中使用它来使用数据并生成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;
});

我使用factory,当我从视图中单击generate按钮时,它将等待直到pdf生成。因为我以前没有这样做过,我需要点击两次按钮才能生成pdf。

您可以将数据作为参数传递给工厂函数参数。

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

我做到了。我忘记把$scope.items寄到我的工厂了。我所做的就是在控制器中添加testFactory.all($scope.items)而不是普通的testFactory.all()

然后在我的工厂,

我使用了function _all(value),所以我可以使用视图通过控制器传递的值。我不确定这是否是正确的方法,但它有效。请建议好的做法,如果你有。

将$scope移到其他服务是一种不好的做法,因为它们可能会改变它并影响您的控制器逻辑。它将在控制器和其他服务之间建立耦合。如果您的工厂需要来自控制器的数据,那么最好将这些参数传递给工厂的函数。

编辑:我看到你设法做到了,是的-传递$scope。Items是首选的方法(例如,不传递$scope)。