[英]Create a directive from an angular controller
我有一個控制器,它使用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}}'
};
});
如果有更好的解決方法,我也很高興聽到。
謝謝!
您可以嘗試以下方法:
...
.directive('myDir', function ($sce) {
return {
restrict: 'E',
template: '<div ng-bind-html="$sce.trustAsHtml(info)"></div>',
scope: { info: '=' },
link: function (scope) {
scope.$sce = $sce;
}
};
});
您必須使用$ 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));
});
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.