繁体   English   中英

AngularJS不会在script标签内编译表达式

[英]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 jqLit​​e实现并以不同方式对待脚本节点)。

但是不可能在脚本中使用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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM