I'm trying to move from jQuery world to Angular.
One of functionalities that I'm trying to port to Angular is printing using AJAX. Idea was to have template defined on client side, do request to server, fill template and print it.
I've done it using Handlebars:
function drukuj(orderId, templateName) {
var data;
$.ajax({
//zapis
contentType: "application/json; charset=utf-8",
type: "POST",
url: "AJAX.asmx/Print",
data: "{orderId: " + orderId + "}",
success: function(msg) {
data = JSON.parse(msg.d);
var template = Handlebars.getTemplate(templateName).done(function(tpl) {
var html = tpl(data);
$.print(html);
}).fail(function(err) {
alert(err);
});
},
error: function(XMLHttpRequest, textStatus, errorThrown) {
alert(textStatus);
}
});
};
Now I'm trying to convert this to angular directive. This is what I have:
(function() {
'use strict';
angular
.module('my.directives', [])
.directive('printMe', ['$timeout', '$window', '$compile', '$rootScope', printMe]);
function printMe($timeout, $window, $compile, $rootScope) {
return {
restrict: 'A',
compile: function() {
return function postLink(scope, element, attrs) {
var title = "Default title";
if (attrs.title) {
title = attrs.title;
}
element.on('click', function() {
print();
});
function print() {
var scope = $rootScope.$new();
angular.extend(scope, {
name: "Me",
items: [{
data: "One"
}, {
data: "Two"
}, {
data: "Three"
}]
});
var template = angular.element('<div ng-repeat="item in items">{{item.data}}</div>');
var linkFunction = $compile(template);
var result = linkFunction(scope);
scope.$apply();
console.log(result.html());
$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('<h1>' + title + '</h1>');
w.document.write(result.html());
w.document.write('</body></html>');
w.document.close();
});
}
// Cleanup on destroy
scope.$on('$destroy', function() {
element.off('click');
});
};
}
};
}
})();
Idea is to have template as variable (get if from $templateCache or have it hard-coded), data as variable (from $http request) and them compile them both into final html so I'll be able to put it in new window and call print on it.
I've tried solution from this question and this, but I can't get that html.
I've created Plunker to show what I've created for now.
I'm still new to angular so any comments about my directive are welcome.