Search code examples
templatescompilationnotificationsangularjsgrowl

Compile angularjs template to show on a notification


I want to use this library(http://pinesframework.org/pnotify/) on my angularjs project

to show error notifications here is a simple usage for it :

    $.pnotify({
        title: 'Oh No!',
        text: text OR HTML,
        type: 'error'
    });

What i want is showing the errors i got as JSON on a notification, but i cant add html with angular tags in this notification.

This is what i tried to do (Im calling it from a service and i am passing the $scope to the function):

        scope.errors = {"errors":[{"text":"error1"},{"text":"error2"}]};
        var htmlTemplate = '<p ng-repeat = "error in errors.errors">{{error.text}}</p>';
        var result = $compile(htmlTemplate)(scope); 

Then

        $.pnotify({title: title,
        text: result,
        type: 'error',
    });

but the notification just show [object Object]

if i tried adding it to a div like this it works fine

    result.appendTo($("#someDiv"));

i tried to solve it but nothing worked for me ,i want to solve it from the angularjs side not by changing the library for my case.

Thanks


Solution

  • The solution I came up with involves $compile()ing the template after pnotify adds it to the DOM. To find out where it is in the DOM after pnotify adds it, I used the addClass parameter to add a dummy class called myClazz. I then used a jQuery selector to find it:

    var htmlTemplate = '<p ng-repeat = "error in errors.errors">{{error.text}}</p>';
    $.pnotify({
        title: 'title',
        text: htmlTemplate,
        type: 'error',
        addclass: 'myClazz'
    });
    // now that htmlTemplate has been added to the DOM, $compile it
    var element = $('.myClazz');
    $compile(element)(scope);
    

    Fiddle

    Note that the DOM manipulation should really be done in a directive, not a service.