Johan Öbrink
Johan Öbrink

Reputation: 143

Angular directive for <a href> links from compiled html

I'm trying to implement an API with angular. The API is at this location.

So, I have a controller that feeds me the data trough a service from the API. The problem is that the API feeds me html with links like this

<a href="/100"></a>
<a href="/101"></a>

Simply put, I would like to rewrite those links on the so that they reroute to my controller again. Like this.

<a href="#100"></a>
<a href="#101"></a>

My plan was to create a directive for the incoming html, to compile it so Angular knows about it.

textTvApp.directive('dynamic', function ($compile) {
  return {
    restrict: 'A',
    replace: true,
    link: function (scope, ele, attrs) {
      scope.$watch(attrs.dynamic, function(html) {          
        ele.html(html);
        $compile(ele.contents())(scope);
      });
    }
  };
});

the view

<div ng-repeat="info in textTvInfo">    
    <div ng-repeat="content in info.content" ng-bind-html="content">        
        <div dynamic="content">

        </div>
    </div>
</div>

This seems to be working all right. My next plan was to have another directive for a-tags which replaces to , but I'm having problem with that directive.

My faulty directive looks like this right now. The idea was to test the rewrite. But nothing seems to be happening.

textTvApp.directive('a', function() {
    return {
        restrict: 'E',
        replace: true,
        template: '<h1>{{result}}</h1>',
        link: function(scope, elem, attrs) {            
            scope.result = "#100";
        }        
   };
});

Upvotes: 1

Views: 874

Answers (1)

Poyraz Yilmaz
Poyraz Yilmaz

Reputation: 5857

You can use angular jquery function to get your html content and edit your a's href attributes with these methods...

here I created a plunker for you http://plnkr.co/edit/WsJO0QXShAHXuXCiq5sl?p=preview

by the way anchor is already registered directive in angularjs core http://docs.angularjs.org/api/ng/directive/a

I don't know if you can create a directive with that name...

Upvotes: 1

Related Questions