AngularJS 템플릿에 내 범위의 문자열로 저장된 스크립트 태그를 어떻게 출력 할 수 있습니까?
-
21-12-2019 - |
문제
스크립트가 실행되기 전에 내 템플릿에서 내장 스크립트를 사용해야하지만 이미지에 경로를 동적으로 삽입해야합니다.
Scope 변수로 이미지 경로를 빌드하려면 지시문을 작성한 다음 $interpolate
를 사용하여 <script>
태그에 삽입하십시오.
$scope.tag
의 Stored (문자열로 문자열로)는 스크립트 태그로 주입하고 해석 / 실행하는 코드이며
대신 스크립트 태그가 내 템플리트의 문자열로 추가되며 실제로 스크립트 태그 문자열을 스크립트 태그로 실제로 출력하려면 실제로 수행 해야하는 추가 단계를 수행하는 것 같습니다.
여기에 템플리트 (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를 사용하여 스크립트 태그를 지시문의 요소에 추가하는 작품입니다.
제휴하지 않습니다 StackOverflow