绑定后需要手动编译html。创建这样的指令。
.directive('dynamic', function ($compile) {
return {
restrict: 'A',
replace: true,
link: function (scope, ele, attrs) {
scope.$watch(attrs.dynamic, function(html) {
ele.html(html);
$compile(ele.contents())(scope);
});
}
};
});
然后在 html 中调用 this 并将 html 字符串绑定到指令
<div dynamic="returnedTemplate"></div>
控制器
$scope.name = 'blah blah';
$scope.message = 'Good day';
$scope.returnedTemplate = '<h3 class="md-title">{{name}}</h3><p class="md-title">{{message}}</p>'
演示
angular.module("app",[])
.controller("ctrl",function($scope){
$scope.name = 'blah blah';
$scope.message = 'Good day';
$scope.returnedTemplate = '<h3 class="md-title">{{name}}</h3><p class="md-title">{{message}}</p>'
}).directive('dynamic', function ($compile) {
return {
restrict: 'A',
replace: true,
link: function (scope, ele, attrs) {
scope.$watch(attrs.dynamic, function(html) {
ele.html(html);
$compile(ele.contents())(scope);
});
}
};
});
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<div ng-app="app" ng-controller="ctrl">
<div dynamic="returnedTemplate"></div>
</div>