Angularjs使用ui-sref链接将html添加到变量

2022-01-21 00:00:00 angularjs javascript angular-ui-router

我有以下代码将 html 添加到变量中.但是,当它显示在页面上时,链接不起作用.

I have the following code that adds html to a variable. However, when it get's shown on the page, the link doesn't work.

动态插入 ui-sref 链接的最佳方法是什么?

What's the best way to get a ui-sref link to work when inserting it dynamically?

JAVASCRIPT

.controller('page', function($scope, $rootScope, $http, $state, $sce) {

    $scope.message = $sce.trustAsHtml('A <a ui-sref="login">login</a> link');

})

HTML

<div ng-bind-html="message"></div>

推荐答案

有 一个工作插件

我想说,我们可以使用以下组合:

I would say, that we can use combination of:

  • $state.href() (doc 这里)和
  • ng-href (doc 这里)

(但仅在传递的参数是 url 的一部分的情况下)

这就是结果

<a ng-href="{{$state.href(myStateName, myParams)}}">

现在(在 plunker)将 myStateName 更改为 parent, parent.child, home 它将正确更改生成的href:

And now (in the plunker) we can change myStateName into parent, parent.child, home and it will change properly the generated href:

<input ng-model="myStateName" />
<input ng-model="myParams.param" />

因为这些是 plunker 中的状态

Because these are states in plunker

$stateProvider
  .state('home', {
      url: "/home",
      ...
  })
  .state('parent', {
      url: "/parent?param",
      ...
  })
  .state('parent.child', { 
      url: "/child",
      ...

检查它这里

相关文章