You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Angular指令templateURL报[$sce:insecurl]错误 新手求助

Angular指令templateURL触发$sce安全限制问题解决

问题代码

angular.module('myApp').directive('multiSelectDropdown', function ($sce) {
    return {
        restrict: 'E',
        scope: {
            options: '=',
            field: '=',
            countSelected: '='
        },
        templateUrl: 'C:\Users\\user\\source\\repos\\WebApplication4\\WebApplication4\\Views\\Home\\multiSelectDropdown.cshtml'
    };
});

报错信息

angular.js:11706 Error: [$sce:insecurl] Blocked loading resource from url not allowed by $sceDelegate policy. URL: C:Users\user\source\repos\WebApplication4\WebApplication4\Views\Home\multiSelectDropdown.cshtml

问题原因

  1. Angular的SCE(严格上下文转义)安全机制默认拦截非同源的本地绝对路径,防止不安全资源加载。
  2. 路径转义错误:C:\Users\\user\\...里的\U会被JS解析为转义字符,导致最终路径缺失反斜杠,格式无效。

解决方法

1. 使用相对路径(优先推荐)

把templateURL改成相对于当前JS文件或应用根目录的相对路径,确保服务器能正确访问模板文件。比如指令JS在Scripts目录,模板在Views/Home/,可以这么写:

templateUrl: '../Views/Home/multiSelectDropdown.cshtml'

根据实际目录结构调整层级即可。

2. 配置SCE信任指定路径

如果必须用绝对路径,在Angular配置阶段把该路径加入信任列表:

angular.module('myApp').config(function($sceDelegateProvider) {
    $sceDelegateProvider.resourceUrlWhitelist([
        'self', // 允许同源资源加载
        'C:\\Users\\user\\source\\repos\\WebApplication4\\WebApplication4\\Views\\Home\\**.cshtml' // 信任目标模板路径
    ]);
});

注意路径要用双反斜杠转义,也可以用**通配符匹配该目录下所有cshtml文件。

3. 内联模板(适合简单模板)

如果模板内容不多,直接把模板代码写在指令的template属性里,彻底避开路径问题:

angular.module('myApp').directive('multiSelectDropdown', function ($sce) {
    return {
        restrict: 'E',
        scope: {
            options: '=',
            field: '=',
            countSelected: '='
        },
        template: `
            <div class="multi-select-dropdown">
                <!-- 这里写你的模板HTML内容 -->
            </div>
        `
    };
});

内容的提问来源于stack exchange,提问作者Ali Haydar

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.19 21:15:38