AngularJS:块作用域声明(let、const、function、class)在严格模式之外还不支持

AngularJS: Block-scoped declarations (let, const, function, class) not yet supported outside strict mode

本文关键字:模式 不支持 function 作用域 声明 AngularJS const let class      更新时间:2023-09-26

我有了这个指令:

app.directive('customDropdown', function() {
    return {
        restrict: 'E',
        templateUrl: '/static/templates/directive_templates/customdropdown.html',
        link: function(scope, element, attrs) {
            console.log(attrs.custom-class);
        }
    }
})

标记:

<custom-dropdown custom-class="custom-select-menu">
</custom-dropdown>

但是,由于console.log(attrs.custom-class),我得到了问题中提到的错误。当我把custom-class变成custom时它就消失了。知道为什么会弹出错误吗?不能使用连字符?

attrs.custom-class custom-class在javascript中不是有效的标识符。所以你有两个选择:

  • 将custom-class重命名为不带连字符的名称

  • 使用括号语法:attrs['custom-class']

这意味着你必须通过在文件或函数的开头写"use strict"来声明严格模式,以使用块作用域声明。

function test(){
    "use strict";
    let a = 1;
}