Why will my twitter widget not render if i change the view in angularjs?

前端 未结 6 1775
日久生厌
日久生厌 2021-01-01 22:46

Hi and thanks for reading.

I have a angular app im making and ive stumbled on a problem. set up as so

index.html-



        
6条回答
  •  天涯浪人
    2021-01-01 23:24

    The problem is because when Angular switches views the script tag that was originally inserted is not removed from the document. I fixed this on my own website by removing the Twitter script element whenever my Twitter timeline directive is not in the view. See the code below with comments.

     function (scope, el, attrs) {
         el.bind('$destroy', function() {
             var twitterScriptEl = angular.element('#twitter-wjs');
             twitterScriptEl.remove();
         });
    
         // function provided by Twitter that's been formatted for easier reading
         function (d, s, id) {
             var js, fjs = d.getElementsByTagName(s)[0], p = /^http:/.test(d.location) ? 'http' : 'https';
    
             // If the Twitter script element is already on the document this will not get called. On a regular webpage that gets reloaded this isn't a problem. Angular views are loaded dynamically.
             if (!d.getElementById(id)) {
                 js = d.createElement(s);
                 js.id = id;
                 js.src = p + "://platform.twitter.com/widgets.js";
                 js.parentNode.insertBefore(js, fjs);
             }
         }(document, "script", "twitter-wjs");        
     }
    

提交回复
热议问题