Question

I need to use an embedded script in my templates but dynamically insert a path to an image before the script runs.

I've written a directive to build the image path as a scope variable, then use $interpolate to insert this into the <script> tag.

The reference now stored (as a string) in $scope.tag is the code I would like to be injected and interpreted/run as a script tag would.

Instead however the script tag is added as a string in my template and I can't seem to workout what extra step I would need to take to actually output the script tag string as a script tag.

Here is the template (referred to in directive as the templateUrl):

<div>
  {{ tag }}
</div>

Directive:

'use strict';

angular.module('App')
  .directive('sslLogo', function($location, $interpolate) {
    return {
      replace: false,
      restrict: 'AE',
      templateUrl: '/views/partials/ssl-logo.html',
      controller: function($scope, $element, $attrs) {
        // Outputs the full base url (http:// ... .com/ )
        var base_url = '';
            base_url += $location.protocol() + '://';
            base_url += $location.host();

            if ( $location.port() ) {
              base_url += ':' + $location.port();
            }

        // Add the path to the image asset.
        $scope.logo_url = base_url + "/images/static/comodo-wildcardssl.png";

        // Interpolate this path into the script tag and then store the script tag to be output to the template.
        $scope.tag = $interpolate('<script type="text/javascript">TrustLogo("{{ logo_url }}", "SCCC", "none");</script>', false, true)({ logo_url: $scope.logo_url });
      },
      link: function(scope, element, attrs) {}
    };
  });

For reference, at this point the $scope.tag variable will contain a string of:

<script type="text/javascript">TrustLogo("http://localhost:9000/images/static/comodo-wildcardssl.png", "SCCC", "none");</script>
Was it helpful?

Solution

It seems that:

...
link: function(scope, element, attrs) {
  element.append( scope.tag );
}
...

works which uses jQuery to append the script tag to the directive's element.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top