angularjs - 动态 ui-sref 值

标签 angularjs

我希望 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/

相关文章:

javascript - 在一项服务中引用多个 API 调用( Angular )

angularjs - 如何在 Angular 数据表中调用复选框功能?

javascript - 使用 Angular js 中的另一个变量获取 $scope.x1 变量

javascript - JS:查找文本中的URL,建立链接

javascript - 当ui-router改变状态时, Angular Controller 范围不会破坏变量

javascript - Angularjs 自动完成

javascript - 如何在对象内部递归循环

javascript - Protractor 无限循环

angularjs - 具有服务依赖性的 Angular 全局错误处理程序

AngularJS:不同文件中的服务