<!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<link rel="stylesheet" href="bootstrap.min.css">
<script src="jquery.min.js"></script>
<script src="angular.min.js"></script>
<script src="bootstrap.min.js"></script>
<script type="text/javascript">
angular.module('myapp', [])
.directive('addBookBtn', function($compile) {
return {
restrict: 'EA',
replace: true,
template: '<h3>Hello world</h3><h3>Hello world</h3>',
link: function(scope, elem, attrs) {
}
};
});
</script>
<style type="text/css">
</style>
</head>
<body ng-app="myapp">
<add-book-btn></add-book-btn>
</body>
</html>
运行上面的代码报错Error: [$compile:tplrt]
原因是replace:true,此时要求template只有一个root element,但是template不符合要求。
所以要么replace:false,要么template改为<div><h3>Hello world</h3><h3>Hello world</h3></div>