首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >动态ui-sref值

动态ui-sref值
EN

Stack Overflow用户
提问于 2016-06-20 13:30:27
回答 1查看 609关注 0票数 3

我希望ng-重复从一个字符串中的ui构建href。FAQ存储在带有文本链接的数据库中。

JSON

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

控制器

代码语言:javascript
复制
(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);
        });
}
})();

代码语言:javascript
复制
<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,这样链接才能正常工作。有办法这样做吗?

提前谢谢。

解决了

指令

代码语言:javascript
复制
(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);
        }
    }
}
})();

代码语言:javascript
复制
<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活跃起来的作用域。

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2016-06-20 18:56:32

您需要的是$compile服务。

更新的柱塞

代码语言:javascript
复制
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. 可以在DOM中注入链接模板。为了使其与您的其余代码一起工作,我将.html()应用于链接模板。但我建议你给我一个指令。实际上,如果在某一时刻您必须使用DOM -指令是一种方法。您可能会发现这个所以回答很有用。
票数 2
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/37923895

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档