Akshay Gaikwad
Akshay Gaikwad

Reputation: 460

ui-sref not working properly when anchor tag is loaded from properties file

Entry in properties file

MYKEY= <a ui-sref="mystate.state">Go to my page using state</a> and <a href="/#/mypage/page">Go to my page using link/a>

I have fetched this key from properties file & applied $sce.trustAsHtml() on it and used in html. I could see link for Go to my page using link but Go to my page using state not working properly as it has ui-sref tag. Can someone please specify reason why it's not working and solution for this.

Note : ui-sref is working properly in my project when it's directly used in html.

Upvotes: 0

Views: 212

Answers (1)

Naren Murali
Naren Murali

Reputation: 56755

It may be because the content is not compiled, hence ui-sref is not working.

I found the below directive which compiles and inserts html code, please check if this solves your issue!

The Directive was got from this SO Answer

var app = angular.module('myApp', []);

app.controller('MyController', function MyController($scope) {
  $scope.test = function() {
    console.log("it works!");
  }
  $scope.html = '<a ui-sref="mystate.state">Go to my page using state</a> and <a href="/#/mypage/page">Go to my page using link</a><button ng-click="test()">click</button>{{asdf}}';
});

app.directive('compile', ['$compile', function ($compile) {
    return function(scope, element, attrs) {
        scope.$watch(
            function(scope) {
                // watch the 'compile' expression for changes
                return scope.$eval(attrs.compile);
            },
            function(value) {
                // when the 'compile' expression changes
                // assign it into the current DOM
                element.html(value);
                // compile the new DOM and link it to the current
                // scope.
                // NOTE: we only compile .childNodes so that
                // we don't get into infinite loop compiling ourselves
                $compile(element.contents())(scope);
            }
        );
    };
}])
<script src="https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.7.5/angular.min.js"></script>
<div ng-controller='MyController' ng-app="myApp">
  <div compile="html"></div>
</div>

Upvotes: 2

Related Questions