Error: [$compile:multidir] Multiple directives [xxxx, xxxx] asking for new/isolated scope

本文探讨Angular中因多重指令导致的隔离作用域错误,分析两种常见场景及解决策略,包括移除'replace:true'属性或使用额外的div元素包裹。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

用angular做项目,应该会碰到Error: [$compile:multidir] Multiple directives [xxxx, xxxx] asking for new/isolated scope这个报错,这个意思是多个指令在一个元素上创建了多个隔离作用域!有两种情况会报这种错误!,先看第一种情况,看下面j简单的代码:

<body>
    <div ng-app="App">
        <custom-tag>
        </custom-tag>
    </div>
</body>
<script>
angular.module("App", []).directive("customTag", function () {
            return {
                restrict: "ECAM",
                scope: {

                },
            }
        }).directive("customTag", function () {
            return {
                restrict: "ECAM",
                scope: {

                },
            }
        })
</script>

上面代码注册两个相同的’customTag’指令,所以一个元素上会出现2个隔离作用域!
在这里插入图片描述
再看另外一种情况,看下面简单的代码:

<body>
    <div ng-app="App">
        <custom-tag>
        </custom-tag>
    </div>
</body>
<script>
angular.module("App", []).directive("customTag", function () {
            return {
                restrict: "ECAM",
                template: "<test></test>",
                replace: true
                scope: {

                }
            }
        }).directive("test", function () {
            return {
                restrict: "ECAM",
                template: "<div>我是test指令模板</>",
                scope: {

                },
                replace: true
            }
        })
  </script>

看下面报错:
在这里插入图片描述

上面代码里面,'custom-tag’这个元素出现了两个隔离作用域,首先他自己有个隔离作用域,另外一个隔离作用域是’test’产生的,两个作用域作用在一个元素上!一般这种情况有两种解决方案,第一种是把’replace: true’去掉,看下面代码:

angular.module("App", []).directive("customTag", function () {
        return {
            restrict: "ECAM",
            template: "<test></test>",
            scope: {

            }
        }
}).directive("test", function () {
    return {
        restrict: "ECAM",
        template: "<div>我是test指令模板</>",
        scope: {

        },
    }
})

因为去掉了replace: true 那么隔离作用域就会出现在上,看下面解析完的html
在这里插入图片描述
第二种方案就是在模板上加个div包裹住,看下面代码:

angular.module("App", []).directive("customTag", function () {
   return {
       restrict: "ECAM",
       template: "<div><test></test><div>",
       replace: true,
       scope: {

       }
   }
}).directive("test", function () {
   return {
       restrict: "ECAM",
       template: "<div>我是test指令模板</>",
       scope: {

       },
   }
})

那么隔离作用域就会出现在我新加的外层div上,看下面解析完的html
在这里插入图片描述
所以为了避免这个问题,一般在directive指令模板中外层都需要一个元素包裹住,或者不要写replace: true就能解决问题!

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值