Search code examples
javascriptjqueryangularjsdirective

Integrating widget into a angular app using a directive


So I have currently integrated Yotpo 'reviews and comments' into my Angular application.

It consists of a javascript widget and some Html:

Js:

var e=document.createElement("script");

e.type="text/javascript",
e.async=true,
e.src="//staticw2.yotpo.com/API/widget.js",
e.id="test";

var t=document.getElementsByTagName("script")[0];
t.parentNode.insertBefore(e,t);

HTML:

<div class="yotpo yotpo-main-widget"
     data-product-id="{{ product.sku }}"
     data-name="{{ product.title }}"
     data-url="{{ pageUrl }}"
    data-image-url="{{ pageImage }}"
    data-description="{{ product.description }}">
</div>

By placing the JS into a directive, I have got it to work, however, it will only work when you reload the page.

To try and fix this, I remove the script when the user leaves the page and reinsert the script when the user goes back into the page

Example:

link: function ($scope, elem) {
    elem.bind('$destroy', function() {
        var widgetScript = angular.element('#foo');
        jQuery(WidgetScript).remove();
    });

    function loadWidget() {
        var e=document.createElement("script");

        e.type="text/javascript",
        e.async=true,
        e.src="//staticw2.yotpo.com/API/widget.js",
        e.id="foo";

        var t=document.getElementsByTagName("script")[0];
        t.parentNode.insertBefore(e,t);
    }

    loadWidget();
}

Unfortunately this doesn't work. Any advice would be very much appreciated.


Solution

  • So I have found a solution and thought I would post it here, as I am sure someone else will no doubt come across this issue if they are using Yotpo with Angular.

    The answer is yotpo.initWidgets();

    Unfortunately there is no information about this in Yotpo's documentations.

    So this is what I have ended up doing, and it works like a charm:

    .directive('yotpo', function ($document, $timeout) {
        return {
            restrict: 'AE',
            link: function() {
    
                function loadWidget() {
                    var e = document.createElement("script");
    
                    e.type = "text/javascript",
                    e.async = true,
                    e.src = "//staticw2.yotpo.com/API/widget.js",
                    e.id = "test";
    
                    var t = document.getElementsByTagName("script")[0];
                    t.parentNode.insertBefore(e,t);
                }
    
                loadWidget();
    
                if (typeof yotpo !== 'undefined') {
                    $timeout(function () {
                        yotpo.initWidgets();
                    }, 500)
    
                }
            }
        }