带脚本的AngularJS指令

AngularJS directive with script

本文关键字:指令 AngularJS 脚本      更新时间:2023-09-26

基本上,我有我的指令定义sample.js为:

app.directive('myDirective', function() {
    return {
        restrict: 'E',
        scope: {
            info: '='
        },
        templateUrl: 'link-to-sample.html'
    };
});

在我的sample.html我得到(例如):

<script>
     $(div).css('height', {{info}}+'px') //THIS DOESN'T WORK
</script>
<div></div>

在我的index.html中,我想通过info=''标记传递一个数值,并在脚本中使用它,在sample.html文件中运行。

<my-directive info='100'></my-directive>

但是在<script></script>标签中仅使用{{info}}似乎不起作用。

如果你们能帮我,我会很感激的。


注:我知道,我可以写一个代码内部指令,使用compile,或template:,但我真的想保持在单独的.html文件。

强烈不鼓励在模板文件中嵌入脚本标签来处理指令中的DOM。它不能很好地配合Angular的DOM更新方式,而且它不能访问作用域和周围的指令。另外,在不允许使用内联脚本的CSP下,它会中断。

推荐的方法是使用link函数并删除模板中的脚本标记。

app.directive('myDirective', function() {
    return {
        restrict: 'E',
        scope: {
            info: '='
        },
        templateUrl: 'link-to-sample.html',
        link: function (element, $scope, attrs) {
            element.find('div').css('height', $scope.info + 'px');
        },
    };
});

您仍然可以为模板HTML保留单独的sample.html。你就是不讲道理。在我看来,这是更好的关注点分离。

<div></div>