我希望ng-重复从一个字符串中的ui构建href。FAQ存储在带有文本链接的数据库中。
JSON
[
{
"question": "How do I find out about you?",
"answer": "Go here "<a ui-sref='root.aboutUs'>about us"</a> page."
}
]控制器
(function() {
'use strict';
angular
.module('test.faqs')
.controller('Faqs', Faqs);
Faqs.$inject = ['faqService', 'exception', '$document', '$sce'];
/* @ngInject */
function Faqs(faqService, exception, $document, $sce) {
var vm = this;
vm.trustAsHtml = $sce.trustAsHtml;
faqService.getFaqs()
.then(function (response){
vm.allFaqs = response;
})
.catch(function (){
exception.catcher('Error retrieving faqs')(message);
});
}
})();<div id="faq_{{$index}}" ng-repeat="faq in faqs.allFaqs track by $index">
<div>
<span ng-bind-html="faqs.trustAsHtml(faq.question)"></span>
</div>
<div>
<span ng-bind-html="faqs.trustAsHtml(faq.answer)"></span>
</div>
我正在寻找一种方法来处理来自json提要的ui-srefs,这样链接才能正常工作。有办法这样做吗?
提前谢谢。
解决了
指令
(function () {
'use strict';
angular
.module('test')
.directive('compileHtml', compileHtml);
/* @ngInject */
compileHtml.$inject = ['$compile', '$sce'];
function compileHtml($compile, $sce) {
return {
restrict: 'A',
replace: true,
link: function (scope, element, attrs) {
var html = attrs.compileHtml;
html = $sce.trustAsHtml(html);
element.html(html);
$compile(element.contents())(scope);
}
}
}
})();<div id="faq_{{$index}}" ng-repeat="faq in faqs.allFaqs track by $index">
<div>
<span compile-html="{{faq.question}}"></span>
</div>
<div>
<span compile-html="{{faq.answer}}"></span>
</div>
</div>感谢戈利尼为我指明了正确的方向!指令将字符串转换为html,然后将其编译回使ui-srefs活跃起来的作用域。
发布于 2016-06-20 18:56:32
您需要的是$compile服务。
更新的柱塞
faqApp.controller('homeCtrl', function($scope, $sce, $compile) {
$scope.test = "hello there!";
$scope.allFaqs = [{
"question": "Where can I get info about you?",
"answer": $compile("<span>Go here: <a ui-sref='about'>about us</a><span>")($scope).html()
}];
$scope.trustAsHtml = $sce.trustAsHtml;
});$compile。注意,html必须有单个根元素。$compile()返回链接函数,然后可以用来链接$scope。.html()应用于链接模板。但我建议你给我一个指令。实际上,如果在某一时刻您必须使用DOM -指令是一种方法。您可能会发现这个所以回答很有用。https://stackoverflow.com/questions/37923895
复制相似问题