Angularjs adding html to variable with ui-sref link
Asked Answered
C

1

6

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.

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>
Centrality answered 5/5, 2015 at 16:20 Comment(2)
Probably have to use $compile - $sce.trustAsHtml($compile('A <a ui-sref="login">login</a> link')($scope));Pule
Why are you trying to add it dynamically? Can you not just put it in the template/html file?Maxama
S
2

There is a working plunker

I would say, that we can use combination of:

  • $state.href() (doc here) and
  • ng-href (doc here)

(but only in case, if the params passed are part of url)

This would be the result

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

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

Because these are states in plunker

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

Check it here

Sapphera answered 5/5, 2015 at 16:53 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.