显示包含指令的文本
displaying text that contains directives
在我的网站上,我想标准化链接到其他人的方式,所以我为此制定了一个指令:
<my-person id="1"></my-person>
和
app.directive('myPerson', function() {
return {
restrict: 'E',
replace: 'true',
template: '<a href="#/person/{{person.id}}">{{person.name}}</a>',
scope: {
person_id : '=id',
},
controller: function($scope, Repository) {
Repository.getPerson($scope.person_id).then(function(p) {
$scope.person = p;
});
},
};
});
这个效果很好。
但在下一步中,我希望用户撰写新闻,并且在这些新闻中他们希望提及其他人。所以基本上,我想显示一个文本
'I met <my-person id="42"></my-person> yesterday.'
但是当 angularjs 显示我的新闻条目的上下文时,html 标签当然会被转义并且它也不会被编译。
有没有简单的方法可以做到这一点?这是一个显示我的问题的 jsfiddle:jsfiddle link
您需要在 ng-repeat 块中编译 html。
为此制定如下指令
app.directive('bindHtmlCompile', ['$compile', function ($compile) {
return {
restrict: 'A',
link: function (scope, element, attrs) {
scope.$watch(function () {
return scope.$eval(attrs.bindHtmlCompile);
}, function (value) {
element.html(value);
$compile(element.contents())(scope);
});
}
};
}]);
现在在你的 ng-repeat 中将你的指令添加到 span 中,如下所示:
<span class="row" bind-html-compile="newsEntry.text"></span>
工作代码here
引用here
在我的网站上,我想标准化链接到其他人的方式,所以我为此制定了一个指令:
<my-person id="1"></my-person>
和
app.directive('myPerson', function() {
return {
restrict: 'E',
replace: 'true',
template: '<a href="#/person/{{person.id}}">{{person.name}}</a>',
scope: {
person_id : '=id',
},
controller: function($scope, Repository) {
Repository.getPerson($scope.person_id).then(function(p) {
$scope.person = p;
});
},
};
});
这个效果很好。
但在下一步中,我希望用户撰写新闻,并且在这些新闻中他们希望提及其他人。所以基本上,我想显示一个文本
'I met <my-person id="42"></my-person> yesterday.'
但是当 angularjs 显示我的新闻条目的上下文时,html 标签当然会被转义并且它也不会被编译。
有没有简单的方法可以做到这一点?这是一个显示我的问题的 jsfiddle:jsfiddle link
您需要在 ng-repeat 块中编译 html。
为此制定如下指令
app.directive('bindHtmlCompile', ['$compile', function ($compile) {
return {
restrict: 'A',
link: function (scope, element, attrs) {
scope.$watch(function () {
return scope.$eval(attrs.bindHtmlCompile);
}, function (value) {
element.html(value);
$compile(element.contents())(scope);
});
}
};
}]);
现在在你的 ng-repeat 中将你的指令添加到 span 中,如下所示:
<span class="row" bind-html-compile="newsEntry.text"></span>
工作代码here
引用here