Borni Borni - 5 months ago 20
AngularJS Question

wikipedia api - relative urls | remove or redirect links

Currently I've been using the following request to display the wikipedia content on my angularjs app:

https://en.wikipedia.org/w/api.php?action=parse&format=json&callback=JSON_CALLBACK&page=little%20tinamou

Using the following, I display all the text on the page:

var lowercaseBirdname = $filter('lowercase')($scope.birdname);
console.log(lowercaseBirdname);
birdApi.getWikipedia(lowercaseBirdname)
.then(function(res) {
console.log(res.data.parse.text['*']);
var toHtml = res.data.parse.text['*'];
document.getElementById("extract").innerHTML = toHtml;
});


All the images, external links are showing, though in the html you can see that the page has alot of
'/wiki/'
links which redirects me to my own url.

How do I bypass this, do give a redirect to the wikipage on a new tab, or can I simply remove all the links while keeping the layout/images?

Answer

Since angular has embedded jquery functionality as angular.element, you can do and wrap all the html manipulation in a custom directive.

This directive will get the html string from wikipedia api response, load them into an element, lookup and replace for relative urls and with wikipedia base url and will store the result on the directive's element.

Online demo - https://plnkr.co/edit/0wtFVOhxw0NfRw43x8K6?p=preview

html:

<button ng-click="reload()">Reload</button>
<hr>
<div wikipedia-content="getWikipediaContent()"></div>

javascript:

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

var WIKIPEDIA_BASE_URL = 'http://en.wikipedia.org';

app.controller('MainCtrl', function($scope) {
  $scope.name = 'World';

  $scope.reload = function() {

    // hard coded for testing purposes
    $scope.response = {
      "parse": {
        "title": "Little tinamou",
        "pageid": 805527,
        "revid": 697345219,
        "text": {
          "*": "<div>\n<table cl ... "
        }
      }
    };
  };

  $scope.getWikipediaContent = function getWikipediaContent() {

    if (!$scope.response) {
      return '';
    }

    return $scope.response.parse.text['*']
  };

});

app.directive("wikipediaContent", function() {
  return {
    scope: {
      wikipediaContent: '='
    },
    link: function(scope, directiveElement) {


      scope.$watch('wikipediaContent', function() {

        if (!scope.wikipediaContent) {
          return;
        }

        var wikipediaElement = angular.element(scope.wikipediaContent);
        wikipediaElement.find('a').each(function() {

          var element = angular.element(this);
          var href = element.attr('href');

          if (href.match(/^http/)) {
            return;
          }

          element.attr('href', WIKIPEDIA_BASE_URL + href);
        });


        directiveElement.replaceWith(wikipediaElement);

      });
    }
  }
});

https://plnkr.co/edit/0wtFVOhxw0NfRw43x8K6?p=preview

Comments