Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to send HTML email with AngularJS?

I am using a cordova email plugin in that works when I send simple text.

However, I am trying to instead use a template to construct the body of the email. I thought $compile would do the trick so I created an on click function:

    $scope.openShare = function (title,body) {
    var templateURL = "templates/roi-email.html";   
    $http.get(templateURL).success(function(data, status, headers, config) {
            var templateRendered = $compile( data )( $scope );

           if(window.plugins && window.plugins.emailComposer) {
                       window.plugins.emailComposer.showEmailComposerWithCallback(function(result) {
                    console.log("Response -> " + result);
                }, 
                title, // Subject
                templateRendered,                     // Body
                [],    // To
                null,                    // CC
                null,                    // BCC
                true,                   // isHTML
                null,                    // Attachments
                null);                   // Attachment Data
            }

However, templateRendered is not a string object. I think it is an mg-view object.

So how do covert the raw html in 'data' to a rendered string to i.e., templateRendered to pass to the email composer?

like image 796
jimijon Avatar asked Mar 02 '26 11:03

jimijon


2 Answers

Use an angular element and don't forget to trigger the $apply on the used scope:

http://jsfiddle.net/coma/o63wvscn/

app.controller('Main', function($scope, $compile, $timeout) {

    var scope = angular.extend($scope.$new(), {
        user: {
            email: '[email protected]'
        }
    });

    var email = angular.element('<div><p>{{ user.email }}</p></div>');
    $compile(email)(scope);

    scope.$apply();
    alert(email.html());
});
like image 150
coma Avatar answered Mar 06 '26 05:03

coma


$compile returns the DOM element; not a string. So you can access templateRendered.html() (jQuery) to get the content. However, as the doc says:

After linking the view is not updated until after a call to $digest which typically is done by Angular automatically.

So you need to wait (or trigger one) for the current digest cycle to finish before you access templateRendered.html().

see a working example : http://plnkr.co/edit/cYsS1c7GbEVRP7RODHvx?p=preview

like image 31
Sylvain Avatar answered Mar 06 '26 03:03

Sylvain