How to add AngularJS to your display templates (CSWP) – part 1

August 5, 2014

AngularJS is so popular these days that I wanted to check out the possibilities in combination with display templates. Once you know the steps to combine them, you could add the magic of AngularJS to your templates. Like for example the templating engine, filtering, directives, etc.

In the first post I will tell you more about my approach of how you could databind the result rows to an AngularJS template.

Note: I will be recreating the default Item_TwoLines template.

Referencing AngularJS

Before you could start, you will need to add a reference to the AngularJS JavaScript file. If you already have the AngularJS referenced somewhere in the master page, or on the page, you won’t need to do this step. If you don’t have it, add the reference like this in the control template:

Note: I’m using SP.SOD.registerSod because that way you could ensure that the JavaScript file is loaded before executing your code. $includeScript loads the JavaScript asynchronously, so it could be that the file is not yet loaded when you need it.

Loading AngularJS

Now that the AngularJS JavaScript file is referenced, the next step is to ensure that it is loaded, then we could start add our AngularJS magic. For that I will use the following piece of code:

Creating the module and controller

The Angular module and controller needs to be created in the previous code bock, the code looks as follows:

1
2
3
4

varapp=angular.module('DisplayApp',[]);app.controller('DisplayControl',function($scope){// Write all the control logic in this code block
});

When working with display templates, the HTML that these templates render will be added to the page when the last result is completed rendering. This means that Angular could not automatically start the template binding. To solve this problem, we need to manually trigger it. Angular bootstrap function can be used to achieve this:

1

angular.bootstrap(document,['DisplayApp']);

Providing the data

Next step is providing the search data for your template. The search data could be retrieved from the current context like this:

Template creation

Display templates already use a sort of templating engine. The control template provides the overall layout of how you want to present the results, and the item template will define the layout for the result itself.

But if you want to use the templating engine from AngularJS, it is easier to create the whole template in the control display template and not split it up over two display templates. That means that you can just remove the HTML from the item template (that has been written inside the first DIV element).