Martin Probst
Martin Probst

Reputation: 9641

Post-processing the DOM in AngularJS

I want to add target="_blank" to an HTML fragment that went through the linky filter. That is, I need to post-process the DOM after the content was completely rendered.

See this jsFiddle.

http://jsfiddle.net/ADukg/410/

I suspect it's something around the priority of the directives, but changing that hasn't helped so far.

Upvotes: 1

Views: 1798

Answers (5)

fscof
fscof

Reputation: 1603

Renan's answer works well, but won't work on links that have been added after pageload.

If you need to add _target blank to new links, try using a filter with a watch event:

JS

app.directive('targetBlank', function() {
    return {
        restrict: 'A',
        link: function(scope, element, attrs) {
            scope.$watch(attrs.targetBlank, function(){
                element.find('a').attr('target', '_blank');
            });
        }
    };
});

HTML

<div ng-bind-html="textModel | linky" target-blank="textModel"></div>

Upvotes: 1

user439032
user439032

Reputation:

and what about just using a function in the controller.

I'm using this in the controller:

$scope.getTarget = function(isExternal) {
    return isExternal ? '_blank' : '';
}

and in the html:

<div ng-repeat="slide in slides" data-slider-id="{{$index}}">
    <a ng-hide="{{slide.link == ''}}" 
       href="{{slide.link}}" 
       target="{{getTarget(slide.isExternal)}}">
...

Upvotes: 0

Chandrakant
Chandrakant

Reputation: 11

  1. Open file angular-sanitize.js
  2. Go to line 525
  3. Change it to writer.start('a', {href:url, target:'_blank'});

Alert - linky will add target _blank to every link, now!

Upvotes: 1

jokr
jokr

Reputation: 242

The problem is that the linky filter will add the 'a' tags after the directive is evaluated and element.find('a') won't find anything.

I think the best solution would be to write your own url filter which then calls the linky filter and don't use a directive.

Update

I created a jsfiddle for that as well: http://jsfiddle.net/jomikr/ADukg/420/

Upvotes: 3

Renan Tomal Fernandes
Renan Tomal Fernandes

Reputation: 10978

You can do this with a setTimeout like this. even if the time is 0, it will only run after the angular finish it processing.

Upvotes: 4

Related Questions