Angularjs 从动态文本呈现指令
我正在尝试使用从动态文本加载的自定义指令,'直到现在我已经创建了该指令,如果在HTML文件中使用该指令,则可以工作,但我要做的是在模型字符串中使用该指令 这是一个样本 js文件:Angularjs 从动态文本呈现指令,angularjs,angularjs-directive,Angularjs,Angularjs Directive,我正在尝试使用从动态文本加载的自定义指令,'直到现在我已经创建了该指令,如果在HTML文件中使用该指令,则可以工作,但我要做的是在模型字符串中使用该指令 这是一个样本 js文件: 'use strict'; var app = angular.module('test', ['ngSanitize']); app.controller('MainController', function($scope, $sce){ var index = 0; $scope.confi
'use strict';
var app = angular.module('test', ['ngSanitize']);
app.controller('MainController', function($scope, $sce){
var index = 0;
$scope.config = [
{
"id": "uniqueIdOne",
"question": "What is your name?",
"answer" : ""
},
{
"id": "uniqueIdTwo",
"question": "Great <answer></answer>, <strong>this is some random text</strong>.",
"answer": ""
}
];
$scope.goNextQuestion = function(){
$scope.current = $scope.config[++index];
$scope.trustHtml();
}
$scope.trustHtml = function(){
$scope.saveHtml = $sce.trustAsHtml( $scope.config[index].question );
}
$scope.current = $scope.config[0];
$scope.trustHtml();
});
app.directive('answer', function() {
return {
template: 'This is rendered by the directive answer.',
};
});
我可以用指令加载文本,但不呈现内容
问题是:如何触发指令render
提前谢谢 您应该创建一个指令来编译包含该指令的文本 使用$compile service,以便触发指令render,如: JS HTML 链接演示:
'use strict';
var app = angular.module('test', ['ngSanitize']);
app.controller('MainController', function($scope, $sce){
var index = 0;
$scope.config = [
{
"id": "uniqueIdOne",
"question": "What is your name?",
"answer" : ""
},
{
"id": "uniqueIdTwo",
"question": "Great <answer></answer>, <strong>this is some random text</strong>.",
"answer": ""
}
];
$scope.goNextQuestion = function(){
$scope.current = $scope.config[++index];
$scope.trustHtml();
}
$scope.trustHtml = function(){
$scope.saveHtml = $sce.trustAsHtml( $scope.config[index].question );
}
$scope.current = $scope.config[0];
$scope.trustHtml();
});
app.directive('answer', function() {
return {
template: 'This is rendered by the directive answer.',
};
});
app.directive('myDirective',[ '$compile', function($compile){
return {
restrict: 'A',
link: function($scope, iEle, attrs){
var compiledTpl;
function destroyData() {
if (compiledTpl) {
compiledTpl.remove();
compiledTpl = null;
}
if ($scope.$newScope) {
$scope.$newScope.$destroy();
$scope.$newScope = null;
}
}
$scope.$watch(attrs.myDirective, function (tpl) {
destroyData();
if (tpl) {
tpl = '<div>' + tpl + '</div>';//make sure tpl is a html template.
$scope.$newScope = $scope.$new();
compiledTpl = $compile(tpl)($scope.$newScope);// compile the directive in string (trigger the directive render).
iEle.append(compiledTpl);
} else {
iEle.html('');
}
});
$scope.$on('$destroy', destroyData);//avoid memory leak.
}
};
}]);
<div my-directive="config[1].question"></div>