Reputation: 167
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.
Upvotes: 2
Views: 2350
Reputation: 1001
For Yotpo's "v3" widget library / API (release late 2022) the answer appears to be calling:
yotpoWidgetsContainer.initWidgets()
Their documentation on this is out of date, but I was able to find a corroborating official source in their docs on writing SPAs.
Upvotes: 2
Reputation: 167
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)
}
}
}
Upvotes: 2
Reputation: 11
You don't need a directive to make this work.
The widget.js script uses the data attributes in the HTML. You need to make sure that those data attributes are set before the javascript is loaded.
I also recommend that you'll use one-way binding for the attributes.
Upvotes: 0