用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就能解决问题!