Frage

Ich muss in meinen Vorlagen ein eingebettetes Skript verwenden, aber vor der Ausführung des Skripts dynamisch einen Pfad zu einem Bild einfügen.

Ich habe eine Anweisung geschrieben, um den Bildpfad als Bereichsvariable zu erstellen und dann zu verwenden $interpolate um dies in das einzufügen <script> Etikett.

Die Referenz wird jetzt (als Zeichenfolge) gespeichert in $scope.tag ist der Code, den ich wie ein Skript-Tag einfügen und interpretieren/ausführen möchte.

Stattdessen wird das Skript-Tag jedoch als Zeichenfolge in meine Vorlage eingefügt, und ich weiß scheinbar nicht, welchen zusätzlichen Schritt ich unternehmen müsste, um die Skript-Tag-Zeichenfolge tatsächlich als Skript-Tag auszugeben.

Hier ist die Vorlage (in der Direktive als bezeichnet). templateUrl):

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

Richtlinie:

'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) {}
    };
  });

Als Referenz dient an dieser Stelle die $scope.tag Variable enthält eine Zeichenfolge von:

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

Lösung

Es scheint, dass:

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

funktioniert, die jQuery verwendet, um das Skript-Tag an das Element der Direktive anzuhängen.

Lizenziert unter: CC-BY-SA mit Zuschreibung
Nicht verbunden mit StackOverflow
scroll top