我有一个控制器,它使用 AJAX 调用为我填充一些数据。此调用接收一个字符串,其中包含文本指令以及一些其他文本。我想解析收到的字符串,以便它实际上创建所需的指令,但我绝对没有运气。指令将驻留在表中,所以我对进行任何类型的 DOM 操作以使其工作有点谨慎。
以下是此案例的简化示例,该示例当前不起作用:http://plnkr.co/edit/RM5FrUxAP1VVF55vSzK7?p=preview
angular.module('docsIsolateScopeDirective', [])
.controller('Controller', ['$scope', '$parse',
function($scope, $parse) {
$scope.data="A"
$scope.mydir = $parse('<my-dir info=data></my-dir>');
}
])
.directive('myDir', function() {
return {
restrict: 'E',
scope: {
info: '='
},
template: '{{info}}'
};
});
如果有更好的方法,我也很高兴听到它。
谢谢!
您必须使用$compile来实现此目的。这是 plnkr,看看这是否有帮助
http://plnkr.co/edit/GbaA9yo6QjOVHNfw3jzA?p=preview
.directive('dynamicDirective', function($compile) {
return {
restrict: 'E',
replace: true,
scope:{
content:'='
},
link: function (scope, ele, attrs) {
scope.$watch('content', function(html) {
ele.append( $compile(html)(scope.$parent));
});
}
你可以试试这个:
...
.directive('myDir', function ($sce) {
return {
restrict: 'E',
template: '<div ng-bind-html="$sce.trustAsHtml(info)"></div>',
scope: { info: '=' },
link: function (scope) {
scope.$sce = $sce;
}
};
});