2

I've got a printing service, it has a function that gets passed the template url and data for the template.

I need to somehow populate that template with the data provided and then open it in a new window. Here's pseudo code for my idea:

PrintWindow.printModal = function(data, template) {
get(template).success(function(data) {
    populatedTemplate = populate(template)
    var mywindow = window.open('', '_blank');
    mywindow.document.write('<html><head>');
    mywindow.document.write('</head><body>');
    mywindow.document.write(populatedTemplate);
    mywindow.document.write('</body></html>');
});
return true;

};

How could I achieve this?

user59388
  • 159
  • 1
  • 10

2 Answers2

1

Figured it out:

$http.get(template).success(function(data) {
    var templateElement = angular.element('<div></div>');
    templateElement.append(data);
    var clonedElement = $compile(templateElement)($scope.data);
    $timeout(function() {
        var printWindow = window.open('', '_blank');
        printWindow.document.write('<html><head>');
        printWindow.document.write('</head><body>');
        printWindow.document.write(clonedElement.html());
        printWindow.document.write('</body></html>');
    });
});
user59388
  • 159
  • 1
  • 10
  • Trying to do the exact same thing! Just wondering how you were able to use $scope inside a service? I'm trying to access data as a variable and I'm getting a 'scope.$watch is not a function' error. – Desmond Jan 22 '16 at 06:01
0

You need to provide a scope within the service, so using $scope didn't work for me. I had to create a new $rootScope.

Here's my code:

module.exports = function ($compile, $templateCache, $timeout, $rootScope) {

  var printService = {};

  printService.createPrint = function(contentPassed) {

    var scope = $rootScope.$new();
    angular.extend(scope, contentPassed);

    var templateElement = angular.element('<div></div>');
    var content = $templateCache.get('document.template.print');
    templateElement.append(content);
    var clonedElement = $compile(templateElement)(scope);

    $timeout(function() {
      var w = window.open('', '', 'width=595,height=842,scrollbars=1');
      w.document.open();
      w.document.write('<html><head>');
      w.document.write('</head><body>');
      w.document.write(clonedElement.html());
      w.document.write('</body></html>');
      w.document.close();
    });
  };

  return printService;

};
Desmond
  • 1,656
  • 3
  • 22
  • 34