seguso
seguso

Reputation: 2273

AngularJS: script not working when view changes (ui-router)

I have an AngularJS web site with ui-router and I had to include a script from imdb which shows the movie rating. My problem is that the script seems to work only when the page is first loaded, but not when I change page and go back to the previous page.

Since the problem can only reproduced with multiple files, I have set up a plunker: http://plnkr.co/edit/T6aGzATdflcyOLfgSTSK?p=preview

As you can see, the imdb rating only appears when the page loads, but if you go to page2 and go back to page1, it does not reappear.

What I already tried: I put the imdb supplied script in the "$viewcontentloaded", as follows:

$scope.$on('$viewContentLoaded', function () {
            console.log("view content loaded");

            (function(d, s, id) {
                    var js, stags = d.getElementsByTagName(s)[0];
                    if (d.getElementById(id)) {
                        return;
                    }

                    js = d.createElement(s);
                    js.id = id;
                    js.src = "http://g-ec2.images-amazon.com/images/G/01/imdb/plugins/rating/js/rating.min.js";
                    stags.parentNode.insertBefore(js, stags);
                })(document, 'script', 'imdb-rating-api');
         });

the html code supplied by imdb is trivial:

 <span  class="imdbRatingPlugin" data-user="ur66948148" data-title="{{imdb()}}" 
    data-style="p3">

  <a href="http://www.imdb.com/title/{{imdb()}}/?ref_=plg_rt_1">
      <img src="http://g-ecx.images-amazon.com/images/G/01/imdb/plugins/rating/images/imdb_37x18.png" alt="{{name}}" target="_blank" />
  </a>
</span>

the imdb() function is defined in my controller as returning the imdb code:

$scope.imdb = function() {
    return "tt1935859";
  }

I would like a general strategy to approach these kinds of problems.

Update: I downloaded the actual javascript code from Imdb and debugged it. It seems the script fails the second time, because it assumes some DOM element does not exist. But the second time, the DOM element exists, because the script itself created it in the first pass. By commenting the line

if (!document.getElementById("imdb-jsonp-" + tconst)) 

now the problem is solved. (plunker) In other words, it seems the javascript was not made for angular.

However, my question is not about solving this specific problem. It is whether a general strategy exists to solve such problems, without having to debug javascript code not written for Angular. In other words, my question is: is there a way to solve this problem without changing the original imdb javascript code? I.e. can we make it so that, the second time it runs, the script finds the same DOM it found the first time (for which it is tested and works)?

Upvotes: 1

Views: 357

Answers (0)

Related Questions