Compile angularjs template to show on a notification

三世轮回 提交于 2019-12-24 02:37:06

问题


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


回答1:


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.




回答2:


After looking at your jsfiddle: jsfiddle.net/bh6kX/19 I have a few comments before we get to the answer.

The compile function does not return html, it returns a link function which is used to bind template (a DOM element/tree) to a scope docs. You also don't need to compile anything as it looks like pnotify (Which I have no experience with) takes direct text as the parameter. So after looping through your error variable, which I've shortened to just:

var errors = [{"text":"error1"},{"text":"error2"}];

And just joining the text together, I passed that into ptnoify and it worked. The styling isn't there, but i have a feeling that's just jsfiddle not liking the css.

fiddle: http://jsfiddle.net/rtCP3/36/



来源:https://stackoverflow.com/questions/14034091/compile-angularjs-template-to-show-on-a-notification

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!