angularjsテンプレートにスコープに文字列として保存されているスクリプトタグを出力する方法

StackOverflow https://stackoverflow.com//questions/25053926

質問

テンプレートに埋め込みスクリプトを使用する必要がありますが、スクリプトの実行前のイメージへのパスを動的に挿入する必要があります。

私はイメージパスをスコープ変数として構築するための指令を書いてから、$interpolateを使用して<script>タグに挿入します。

$scope.tagの(文字列として)保存されている(文字列として)、スクリプトタグとして解釈され、解釈/実行されるコードがあります。

しかし、スクリプトタグは私のテンプレートの文字列として追加され、スクリプトタグ文字列をスクリプトタグとして実際に出力するのにかかる余分なステップiを取り除くことはできません。

これはテンプレート(templateUrlと指令内)です。

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

ディレクティブ:

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

参照のために、この時点で$scope.tag変数には、次の文字列が含まれます。

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

役に立ちましたか?

解決

そうです:

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

jQueryを使用してスクリプトタグをディレクティブの要素に追加します。

ライセンス: CC-BY-SA帰属
所属していません StackOverflow
scroll top