本文参考自后补全的代码:http://blog.csdn.net/liwusen/article/details/52078435
<body ng-app="myapp">
<h1>动态编译指令,动态编译指令模板内容</h1>
<div class="container" ng-controller="MyController">
<button ng-click="addDirective()">添加动态指令</button>
<div id="root"></div>
</div>
<!-- my-text method-from-outer="methodInCtrl()"></my-text -->
<script type="application/javascript">
angular.module('myapp', [])
.directive('myText', function ($compile) {
var templatecC = '<div ng-click="hello()">Hi everyone</div>';
return {
restrict: 'AE',
template: templatecC,
scope: {
hello: "&methodFromOuter"
},
link: function (scope, ele, attr) {
ele.on("click", function () {
scope.$apply(function () {
//使用指令的scope进行编译模板内容,并添加到当前指令下面
var content = $compile(templatecC)(scope);
ele.append(content);
})
});
}
}
})
.controller("MyController", ["$scope", "$compile", function ($scope, $compile) {
$scope.addDirective = function () {
//使用controller的$scope进行编译指令,添加到指定的元素下。
var dynamicDirective = $compile("<my-text></my-text>")($scope);
angular.element("div#root").append(dynamicDirective);
}
$scope.methodInCtrl = function () {
alert("hello 123456");
}
}])
</script>
</body>