[英]AngularJS doesn't compiles expressions inside the script tag
我嘗試使用文件內的<script>..</script>
編譯HTML模板,但是AngularJS編譯器不會編譯<script>
標記內的所有表達式。
我的控制器:
.controller('showChannelController', function ($scope, $http, $stateParams, $compile, $templateRequest) {
$http.get("http://localhost/show?id=" + $stateParams.id)
.then(function (response) {
$scope.info = response.data.data;
$templateRequest('application/script.html').then(function(template) {
$('body').append($compile(template)($scope));
});
});
});
我的application/script.html
模板如下所示:
<script>
$(function() {
// Load Player
var player = new Clappr.Player({
source: "{{source_url}}",
parentId: "#player",
autoPlay: true,
width: 962,
height: 540,
});
});
</script>
如果不包含后端,是否可以解決此問題?
不要使用括號。 使用變量。 它應該直接工作。 使用$ rootScope傳遞變量的值。 這里使用$ rootScope,因為它在所有應用程序中都是通用的。
這是例子。
angular.module('tss.application').controller('VideoController',function($log, $rootScope, $scope, $window ) {
var player = new Clappr.Player({
source: $rootScope.vp,
parentId: "#player",
autoPlay: true
});
});
我在video_modal.html中使用此控制器---這是播放器打開的彈出模式。 視頻的來源是動態的,具體取決於用戶的點擊/選擇。
<div ng-controller="VideoController">
<div id="player"></div>
</div>
通過這種解決方法或通過加載jQuery,可以在模板中使用<script>
標記(它替換了Angular jqLite實現並以不同方式對待腳本節點)。
但是不可能在腳本中使用Angular表達式。 這將是一個巨大的安全漏洞,因為這將需要使用eval
執行任意代碼。
它可以是包含上面代碼的指令。
app.directive('player', () => ({
scope: { url: '@' },
link: (scope, element, attrs) => {
scope.id = Math.round(Math.random()*10e4);
attrs.$set('id', 'player-' + scope.id);
scope.instance = new Clappr.Player({
source: scope.url,
parentId: '#' + scope.id,
...
});
}
}));
這取決於Clappr.Player
如何提供父元素。 如果它接受DOM元素作為父$element[0]
,則可以提供$element[0]
而不是`parentId
實現后端版本,只需在服務器端生成包含所有必需參數的腳本,然后將完整的腳本傳輸到AngularJS。 然后在AngularJS控制器中應用接收到的數據。
$('body').append($compile(response.data.script)($scope));
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.