问题
I'm using Angular for the first time on a large project and one of the requirements is that we use AddThis for social sharing for articles. But in addition to the AddThis sharing, we want to track the share events in google analytics.
So what I want to do is add the AddThis
<div class="addthis_toolbox addthis_16x16_style">
<a class="addthis_button_preferred_1"></a>
<a class="addthis_button_preferred_2"></a>
<a class="addthis_button_preferred_3"></a>
<a class="addthis_button_preferred_4"></a>
<a class="addthis_button_compact"></a>
</div>
<script type="text/javascript" src="//s7.addthis.com/js/300/addthis_widget.js#pubid=XXXXX"></script>
and in the controller, add an event handler as described in their docs http://support.addthis.com/customer/portal/articles/381263-addthis-client-api-#configuration-sharing
addthis.addEventListener('addthis.menu.open', eventHandler);
addthis.addEventListener('addthis.menu.close', eventHandler);
addthis.addEventListener('addthis.menu.share', eventHandler);
The problem, is that I can't seem to get a reference to the addthis object in the $scope of the controller. Does anyone know how I can accomplish this either via directive or some other trick to do a document.ready and getting a reference to the addthis object?
回答1:
addthis
is a property of window
and must be visible in any scope, however I guess that type
parameter of addEventListener
is not evaluated inside addthis_widget.js
Did you try this?
<div class="addthis_toolbox addthis_16x16_style">
<a class="addthis_button_preferred_1"></a>
<a class="addthis_button_preferred_2"></a>
<a class="addthis_button_preferred_3"></a>
<a class="addthis_button_preferred_4"></a>
<a class="addthis_button_compact"></a>
</div>
<script type="text/javascript" src="//s7.addthis.com/js/300/addthis_widget.js#pubid=XXXXX"></script>
<script type="text/javascript">
addthis.addEventListener('addthis.menu.open', eventHandler);
addthis.addEventListener('addthis.menu.close', eventHandler);
addthis.addEventListener('addthis.menu.share', eventHandler);
<script>
That way events should be applied each time you reload the widget.
If does't help, you can wrap it into a directive like I did here. Try to add your listeners inside the directive.
来源:https://stackoverflow.com/questions/16321095/angular-js-and-addthis-eventhandlers