我需要在模板中使用嵌入脚本,但在脚本运行之前动态插入图像的路径。

我编写了一个指令来将图像路径构建为范围变量,然后使用 $interpolate 将其插入到 <script> 标签。

引用现在存储(作为字符串)在 $scope.tag 是我想要像脚本标签一样注入和解释/运行的代码。

然而,脚本标签作为字符串添加到我的模板中,我似乎无法计算出需要采取哪些额外步骤才能将脚本标签字符串实际输出为脚本标签。

这是模板(在指令中称为 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