Archive for November 14, 2014

Getting normal link behavior to your App Parts

Lately I’ve been working a lot with App Parts for a customer. The one thing that bothered me most was the behavior of links as a result of the iFrame an App is rendered in. I’ve come up with 2 solid solutions for the links in an App Part to behave like all other links without having to worry about the iFrame.

Objectives

My goal is to keep the default behavior of an <a> element intact. In the browser that means that we should still be able to open up a menu with the right click, but also support a ctrl + click to open the link in a new window. By default when you click a link the page should not be opened in the iFrame but in its parent window instead.

jQuery for the win

Since jQuery is added to your App via NuGet by default (at least for SharePoint Hosted Apps) this was the most obvious Library to fix the problem with. In this example I’ll build a simple SharePoint Hosted App with very little code. First my HTML part:

Since jQuery is a library for DOM modification we need to write a script that modifies the <a> element after it is rendered. We need an action on document ready and a function to iterate all <a> elements. Here’s my code:

Alright so this works, but as you might know I’m very fond of frameworks and especially Angular JS.

AngularJS for the win

In my opinion Angular gives us the best solution since the framework works with databinding and not DOM manipulation which basically means that all the modifications are in place once the page is loaded. No need to iterate the DOM afterwards. First the HTML:

In this solution we create a custom directive. That means that all HTML elements that have this directive (in this case just the <a> element as a directive) will have this same behavior.

Hopefully this will make the life of an App Part developer a lot easier!

Originally posted on: http://blog.point42.nl/2014/11/getting-normal-link-behavior-to-your-app-parts/