似乎是這樣。我在測試中使用了Angular 1.6,但是我能夠在包含綁定的角度指令中使用shadow DOM。
這裏是我的示例代碼:
<!DOCTYPE html>
<html ng-app="app">
<head>
<meta charset="utf-8">
<title>Angular 1.x ShadowDOM example</title>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.5.6/angular.min.js"></script>
<script>
var app = angular.module('app', []);
app.controller('myElController', ($scope) => {
});
var template = `
<style>
:host {
left: 50%;
position: fixed;
top: 50%;
transform: translate(-50%,-50%);
border: 1px solid black;
box-shadow: 4px 4px 4px rgba(0,0,0,.4);
display: inline-block;
padding: 6px 12px;
}
h3 {
border-bottom: 1px solid #999;
margin: 0 -12px 8px;
padding: 0 12px 8px;
}
p {
margin: 0;
}
</style>
<h3>{{title}}</h3>
<p>{{info}}</p>
`;
app.directive('myEl', ($compile) => {
return {
"restrict": "E",
"controller": "myElController",
"template": '',
"scope": {
"title": "@",
"info": "@"
},
"link": function($scope, $element) {
console.log('here');
$scope.shadowRoot = $element[0].attachShadow({mode:'open'});
$scope.shadowRoot.innerHTML = template;
$compile($scope.shadowRoot)($scope);
}
};
});
</script>
</head>
<body>
<div>
<my-el title="This is a title" info="This is the info of the element"></my-el>
</div>
<div class="shell">
<h3>Outside title (H3)</h3>
<p>Outside content (P)</p>
</div>
</body>
</html>
訣竅是不具備該指令默認模板。只是我們一個空的字符串。然後,在link
函數中,您將創建陰影根並將其設置爲實際模板的innerHTML。然後,您需要在影子根上運行$compile
以將其綁定回指令的$範圍。
請注意,這隻適用於原生支持陰影DOM的瀏覽器。任何Polyfill都不會支持真正的CSS封裝。爲此,最好使用BEM CSS的一種形式:http://getbem.com/introduction/