gpt4 book ai didi

angularjs - 动态 ui-sref 值

转载 作者:行者123 更新时间:2023-12-03 06:47:51 26 4
gpt4 key购买 nike

我希望 ng-repeat 从字符串内的 ui-srefs 构建 href。常见问题解答存储在数据库中,文本中包含链接。

JSON

[
{
"question": "How do I find out about you?",
"answer": "Go here "<a ui-sref='root.aboutUs'>about us"</a> page."
}
]

Controller

(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);
});
}
})();

HTML

<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>

PLUNKER

我正在寻找一种方法来处理来自 json feed 的 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);
}
}
}
})();

HTML

<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>

感谢 goliney 为我指明了正确的方向!指令将字符串转换为 html,然后将其编译回使 ui-srefs 生效的范围。

最佳答案

您需要的是 $compile服务。

已更新PLUNKER

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;
});
  1. 将 html 传递给 $compile。请注意,html 必须具有单个根元素。
  2. $compile() 返回链接函数,然后可用于链接 $scope
  3. 链接模板可以注入(inject)到 DOM 中。为了使其与代码的其余部分一起使用,我将 .html() 应用于链接的模板。但我建议为此制定一个指令。实际上,如果在某些时候您必须使用 DOM - 指令是一种不错的选择。你可能会发现这个SO answer有用。

关于angularjs - 动态 ui-sref 值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37923895/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com